Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/absl_py-2.1.0.dist-info/INSTALLER +1 -0
- llmeval-env/lib/python3.10/site-packages/absl_py-2.1.0.dist-info/LICENSE +202 -0
- llmeval-env/lib/python3.10/site-packages/absl_py-2.1.0.dist-info/WHEEL +5 -0
- llmeval-env/lib/python3.10/site-packages/absl_py-2.1.0.dist-info/top_level.txt +1 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/_compat.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/_termui_impl.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/_textwrap.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/_winconsole.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/core.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/decorators.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/exceptions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/formatting.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/globals.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/parser.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/shell_completion.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/termui.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/testing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/types.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/__pycache__/utils.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/click/_compat.py +623 -0
- llmeval-env/lib/python3.10/site-packages/click/_termui_impl.py +739 -0
- llmeval-env/lib/python3.10/site-packages/click/_winconsole.py +279 -0
- llmeval-env/lib/python3.10/site-packages/click/decorators.py +561 -0
- llmeval-env/lib/python3.10/site-packages/click/exceptions.py +288 -0
- llmeval-env/lib/python3.10/site-packages/click/formatting.py +301 -0
- llmeval-env/lib/python3.10/site-packages/click/globals.py +68 -0
- llmeval-env/lib/python3.10/site-packages/click/shell_completion.py +596 -0
- llmeval-env/lib/python3.10/site-packages/click/termui.py +784 -0
- llmeval-env/lib/python3.10/site-packages/click/testing.py +479 -0
- llmeval-env/lib/python3.10/site-packages/click/utils.py +624 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__init__.py +916 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_local_folder.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_multi_commits.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_space_api.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/hf_file_system.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/keras_mixin.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/lfs.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/repocard.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/_commit_api.py +699 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py +327 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py +377 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/_local_folder.py +229 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/_login.py +397 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py +306 -0
- llmeval-env/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py +305 -0
llmeval-env/lib/python3.10/site-packages/absl_py-2.1.0.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
llmeval-env/lib/python3.10/site-packages/absl_py-2.1.0.dist-info/LICENSE
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
Apache License
|
3 |
+
Version 2.0, January 2004
|
4 |
+
http://www.apache.org/licenses/
|
5 |
+
|
6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
7 |
+
|
8 |
+
1. Definitions.
|
9 |
+
|
10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
12 |
+
|
13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
14 |
+
the copyright owner that is granting the License.
|
15 |
+
|
16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
17 |
+
other entities that control, are controlled by, or are under common
|
18 |
+
control with that entity. For the purposes of this definition,
|
19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
20 |
+
direction or management of such entity, whether by contract or
|
21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
23 |
+
|
24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
25 |
+
exercising permissions granted by this License.
|
26 |
+
|
27 |
+
"Source" form shall mean the preferred form for making modifications,
|
28 |
+
including but not limited to software source code, documentation
|
29 |
+
source, and configuration files.
|
30 |
+
|
31 |
+
"Object" form shall mean any form resulting from mechanical
|
32 |
+
transformation or translation of a Source form, including but
|
33 |
+
not limited to compiled object code, generated documentation,
|
34 |
+
and conversions to other media types.
|
35 |
+
|
36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
37 |
+
Object form, made available under the License, as indicated by a
|
38 |
+
copyright notice that is included in or attached to the work
|
39 |
+
(an example is provided in the Appendix below).
|
40 |
+
|
41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
42 |
+
form, that is based on (or derived from) the Work and for which the
|
43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
45 |
+
of this License, Derivative Works shall not include works that remain
|
46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
47 |
+
the Work and Derivative Works thereof.
|
48 |
+
|
49 |
+
"Contribution" shall mean any work of authorship, including
|
50 |
+
the original version of the Work and any modifications or additions
|
51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
55 |
+
means any form of electronic, verbal, or written communication sent
|
56 |
+
to the Licensor or its representatives, including but not limited to
|
57 |
+
communication on electronic mailing lists, source code control systems,
|
58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
60 |
+
excluding communication that is conspicuously marked or otherwise
|
61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
62 |
+
|
63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
65 |
+
subsequently incorporated within the Work.
|
66 |
+
|
67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
72 |
+
Work and such Derivative Works in Source or Object form.
|
73 |
+
|
74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
77 |
+
(except as stated in this section) patent license to make, have made,
|
78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
79 |
+
where such license applies only to those patent claims licensable
|
80 |
+
by such Contributor that are necessarily infringed by their
|
81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
83 |
+
institute patent litigation against any entity (including a
|
84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
85 |
+
or a Contribution incorporated within the Work constitutes direct
|
86 |
+
or contributory patent infringement, then any patent licenses
|
87 |
+
granted to You under this License for that Work shall terminate
|
88 |
+
as of the date such litigation is filed.
|
89 |
+
|
90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
91 |
+
Work or Derivative Works thereof in any medium, with or without
|
92 |
+
modifications, and in Source or Object form, provided that You
|
93 |
+
meet the following conditions:
|
94 |
+
|
95 |
+
(a) You must give any other recipients of the Work or
|
96 |
+
Derivative Works a copy of this License; and
|
97 |
+
|
98 |
+
(b) You must cause any modified files to carry prominent notices
|
99 |
+
stating that You changed the files; and
|
100 |
+
|
101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
102 |
+
that You distribute, all copyright, patent, trademark, and
|
103 |
+
attribution notices from the Source form of the Work,
|
104 |
+
excluding those notices that do not pertain to any part of
|
105 |
+
the Derivative Works; and
|
106 |
+
|
107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
108 |
+
distribution, then any Derivative Works that You distribute must
|
109 |
+
include a readable copy of the attribution notices contained
|
110 |
+
within such NOTICE file, excluding those notices that do not
|
111 |
+
pertain to any part of the Derivative Works, in at least one
|
112 |
+
of the following places: within a NOTICE text file distributed
|
113 |
+
as part of the Derivative Works; within the Source form or
|
114 |
+
documentation, if provided along with the Derivative Works; or,
|
115 |
+
within a display generated by the Derivative Works, if and
|
116 |
+
wherever such third-party notices normally appear. The contents
|
117 |
+
of the NOTICE file are for informational purposes only and
|
118 |
+
do not modify the License. You may add Your own attribution
|
119 |
+
notices within Derivative Works that You distribute, alongside
|
120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
121 |
+
that such additional attribution notices cannot be construed
|
122 |
+
as modifying the License.
|
123 |
+
|
124 |
+
You may add Your own copyright statement to Your modifications and
|
125 |
+
may provide additional or different license terms and conditions
|
126 |
+
for use, reproduction, or distribution of Your modifications, or
|
127 |
+
for any such Derivative Works as a whole, provided Your use,
|
128 |
+
reproduction, and distribution of the Work otherwise complies with
|
129 |
+
the conditions stated in this License.
|
130 |
+
|
131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
133 |
+
by You to the Licensor shall be under the terms and conditions of
|
134 |
+
this License, without any additional terms or conditions.
|
135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
136 |
+
the terms of any separate license agreement you may have executed
|
137 |
+
with Licensor regarding such Contributions.
|
138 |
+
|
139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
141 |
+
except as required for reasonable and customary use in describing the
|
142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
143 |
+
|
144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
145 |
+
agreed to in writing, Licensor provides the Work (and each
|
146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
148 |
+
implied, including, without limitation, any warranties or conditions
|
149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
151 |
+
appropriateness of using or redistributing the Work and assume any
|
152 |
+
risks associated with Your exercise of permissions under this License.
|
153 |
+
|
154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
155 |
+
whether in tort (including negligence), contract, or otherwise,
|
156 |
+
unless required by applicable law (such as deliberate and grossly
|
157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
158 |
+
liable to You for damages, including any direct, indirect, special,
|
159 |
+
incidental, or consequential damages of any character arising as a
|
160 |
+
result of this License or out of the use or inability to use the
|
161 |
+
Work (including but not limited to damages for loss of goodwill,
|
162 |
+
work stoppage, computer failure or malfunction, or any and all
|
163 |
+
other commercial damages or losses), even if such Contributor
|
164 |
+
has been advised of the possibility of such damages.
|
165 |
+
|
166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
169 |
+
or other liability obligations and/or rights consistent with this
|
170 |
+
License. However, in accepting such obligations, You may act only
|
171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
172 |
+
of any other Contributor, and only if You agree to indemnify,
|
173 |
+
defend, and hold each Contributor harmless for any liability
|
174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
175 |
+
of your accepting any such warranty or additional liability.
|
176 |
+
|
177 |
+
END OF TERMS AND CONDITIONS
|
178 |
+
|
179 |
+
APPENDIX: How to apply the Apache License to your work.
|
180 |
+
|
181 |
+
To apply the Apache License to your work, attach the following
|
182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
183 |
+
replaced with your own identifying information. (Don't include
|
184 |
+
the brackets!) The text should be enclosed in the appropriate
|
185 |
+
comment syntax for the file format. We also recommend that a
|
186 |
+
file or class name and description of purpose be included on the
|
187 |
+
same "printed page" as the copyright notice for easier
|
188 |
+
identification within third-party archives.
|
189 |
+
|
190 |
+
Copyright [yyyy] [name of copyright owner]
|
191 |
+
|
192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
193 |
+
you may not use this file except in compliance with the License.
|
194 |
+
You may obtain a copy of the License at
|
195 |
+
|
196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
197 |
+
|
198 |
+
Unless required by applicable law or agreed to in writing, software
|
199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
201 |
+
See the License for the specific language governing permissions and
|
202 |
+
limitations under the License.
|
llmeval-env/lib/python3.10/site-packages/absl_py-2.1.0.dist-info/WHEEL
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.42.0)
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py3-none-any
|
5 |
+
|
llmeval-env/lib/python3.10/site-packages/absl_py-2.1.0.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
absl
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.62 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/_compat.cpython-310.pyc
ADDED
Binary file (15.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/_termui_impl.cpython-310.pyc
ADDED
Binary file (16.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/_textwrap.cpython-310.pyc
ADDED
Binary file (1.56 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/_winconsole.cpython-310.pyc
ADDED
Binary file (7.67 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/core.cpython-310.pyc
ADDED
Binary file (91.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/decorators.cpython-310.pyc
ADDED
Binary file (17.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/exceptions.cpython-310.pyc
ADDED
Binary file (10.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/formatting.cpython-310.pyc
ADDED
Binary file (9.47 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/globals.cpython-310.pyc
ADDED
Binary file (2.44 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/parser.cpython-310.pyc
ADDED
Binary file (13.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/shell_completion.cpython-310.pyc
ADDED
Binary file (16.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/termui.cpython-310.pyc
ADDED
Binary file (26.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/testing.cpython-310.pyc
ADDED
Binary file (15.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/types.cpython-310.pyc
ADDED
Binary file (33.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (18.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/click/_compat.py
ADDED
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import codecs
|
2 |
+
import io
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
import sys
|
6 |
+
import typing as t
|
7 |
+
from weakref import WeakKeyDictionary
|
8 |
+
|
9 |
+
CYGWIN = sys.platform.startswith("cygwin")
|
10 |
+
WIN = sys.platform.startswith("win")
|
11 |
+
auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None
|
12 |
+
_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
|
13 |
+
|
14 |
+
|
15 |
+
def _make_text_stream(
|
16 |
+
stream: t.BinaryIO,
|
17 |
+
encoding: t.Optional[str],
|
18 |
+
errors: t.Optional[str],
|
19 |
+
force_readable: bool = False,
|
20 |
+
force_writable: bool = False,
|
21 |
+
) -> t.TextIO:
|
22 |
+
if encoding is None:
|
23 |
+
encoding = get_best_encoding(stream)
|
24 |
+
if errors is None:
|
25 |
+
errors = "replace"
|
26 |
+
return _NonClosingTextIOWrapper(
|
27 |
+
stream,
|
28 |
+
encoding,
|
29 |
+
errors,
|
30 |
+
line_buffering=True,
|
31 |
+
force_readable=force_readable,
|
32 |
+
force_writable=force_writable,
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
def is_ascii_encoding(encoding: str) -> bool:
|
37 |
+
"""Checks if a given encoding is ascii."""
|
38 |
+
try:
|
39 |
+
return codecs.lookup(encoding).name == "ascii"
|
40 |
+
except LookupError:
|
41 |
+
return False
|
42 |
+
|
43 |
+
|
44 |
+
def get_best_encoding(stream: t.IO[t.Any]) -> str:
|
45 |
+
"""Returns the default stream encoding if not found."""
|
46 |
+
rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()
|
47 |
+
if is_ascii_encoding(rv):
|
48 |
+
return "utf-8"
|
49 |
+
return rv
|
50 |
+
|
51 |
+
|
52 |
+
class _NonClosingTextIOWrapper(io.TextIOWrapper):
|
53 |
+
def __init__(
|
54 |
+
self,
|
55 |
+
stream: t.BinaryIO,
|
56 |
+
encoding: t.Optional[str],
|
57 |
+
errors: t.Optional[str],
|
58 |
+
force_readable: bool = False,
|
59 |
+
force_writable: bool = False,
|
60 |
+
**extra: t.Any,
|
61 |
+
) -> None:
|
62 |
+
self._stream = stream = t.cast(
|
63 |
+
t.BinaryIO, _FixupStream(stream, force_readable, force_writable)
|
64 |
+
)
|
65 |
+
super().__init__(stream, encoding, errors, **extra)
|
66 |
+
|
67 |
+
def __del__(self) -> None:
|
68 |
+
try:
|
69 |
+
self.detach()
|
70 |
+
except Exception:
|
71 |
+
pass
|
72 |
+
|
73 |
+
def isatty(self) -> bool:
|
74 |
+
# https://bitbucket.org/pypy/pypy/issue/1803
|
75 |
+
return self._stream.isatty()
|
76 |
+
|
77 |
+
|
78 |
+
class _FixupStream:
|
79 |
+
"""The new io interface needs more from streams than streams
|
80 |
+
traditionally implement. As such, this fix-up code is necessary in
|
81 |
+
some circumstances.
|
82 |
+
|
83 |
+
The forcing of readable and writable flags are there because some tools
|
84 |
+
put badly patched objects on sys (one such offender are certain version
|
85 |
+
of jupyter notebook).
|
86 |
+
"""
|
87 |
+
|
88 |
+
def __init__(
|
89 |
+
self,
|
90 |
+
stream: t.BinaryIO,
|
91 |
+
force_readable: bool = False,
|
92 |
+
force_writable: bool = False,
|
93 |
+
):
|
94 |
+
self._stream = stream
|
95 |
+
self._force_readable = force_readable
|
96 |
+
self._force_writable = force_writable
|
97 |
+
|
98 |
+
def __getattr__(self, name: str) -> t.Any:
|
99 |
+
return getattr(self._stream, name)
|
100 |
+
|
101 |
+
def read1(self, size: int) -> bytes:
|
102 |
+
f = getattr(self._stream, "read1", None)
|
103 |
+
|
104 |
+
if f is not None:
|
105 |
+
return t.cast(bytes, f(size))
|
106 |
+
|
107 |
+
return self._stream.read(size)
|
108 |
+
|
109 |
+
def readable(self) -> bool:
|
110 |
+
if self._force_readable:
|
111 |
+
return True
|
112 |
+
x = getattr(self._stream, "readable", None)
|
113 |
+
if x is not None:
|
114 |
+
return t.cast(bool, x())
|
115 |
+
try:
|
116 |
+
self._stream.read(0)
|
117 |
+
except Exception:
|
118 |
+
return False
|
119 |
+
return True
|
120 |
+
|
121 |
+
def writable(self) -> bool:
|
122 |
+
if self._force_writable:
|
123 |
+
return True
|
124 |
+
x = getattr(self._stream, "writable", None)
|
125 |
+
if x is not None:
|
126 |
+
return t.cast(bool, x())
|
127 |
+
try:
|
128 |
+
self._stream.write("") # type: ignore
|
129 |
+
except Exception:
|
130 |
+
try:
|
131 |
+
self._stream.write(b"")
|
132 |
+
except Exception:
|
133 |
+
return False
|
134 |
+
return True
|
135 |
+
|
136 |
+
def seekable(self) -> bool:
|
137 |
+
x = getattr(self._stream, "seekable", None)
|
138 |
+
if x is not None:
|
139 |
+
return t.cast(bool, x())
|
140 |
+
try:
|
141 |
+
self._stream.seek(self._stream.tell())
|
142 |
+
except Exception:
|
143 |
+
return False
|
144 |
+
return True
|
145 |
+
|
146 |
+
|
147 |
+
def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool:
|
148 |
+
try:
|
149 |
+
return isinstance(stream.read(0), bytes)
|
150 |
+
except Exception:
|
151 |
+
return default
|
152 |
+
# This happens in some cases where the stream was already
|
153 |
+
# closed. In this case, we assume the default.
|
154 |
+
|
155 |
+
|
156 |
+
def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool:
|
157 |
+
try:
|
158 |
+
stream.write(b"")
|
159 |
+
except Exception:
|
160 |
+
try:
|
161 |
+
stream.write("")
|
162 |
+
return False
|
163 |
+
except Exception:
|
164 |
+
pass
|
165 |
+
return default
|
166 |
+
return True
|
167 |
+
|
168 |
+
|
169 |
+
def _find_binary_reader(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:
|
170 |
+
# We need to figure out if the given stream is already binary.
|
171 |
+
# This can happen because the official docs recommend detaching
|
172 |
+
# the streams to get binary streams. Some code might do this, so
|
173 |
+
# we need to deal with this case explicitly.
|
174 |
+
if _is_binary_reader(stream, False):
|
175 |
+
return t.cast(t.BinaryIO, stream)
|
176 |
+
|
177 |
+
buf = getattr(stream, "buffer", None)
|
178 |
+
|
179 |
+
# Same situation here; this time we assume that the buffer is
|
180 |
+
# actually binary in case it's closed.
|
181 |
+
if buf is not None and _is_binary_reader(buf, True):
|
182 |
+
return t.cast(t.BinaryIO, buf)
|
183 |
+
|
184 |
+
return None
|
185 |
+
|
186 |
+
|
187 |
+
def _find_binary_writer(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:
|
188 |
+
# We need to figure out if the given stream is already binary.
|
189 |
+
# This can happen because the official docs recommend detaching
|
190 |
+
# the streams to get binary streams. Some code might do this, so
|
191 |
+
# we need to deal with this case explicitly.
|
192 |
+
if _is_binary_writer(stream, False):
|
193 |
+
return t.cast(t.BinaryIO, stream)
|
194 |
+
|
195 |
+
buf = getattr(stream, "buffer", None)
|
196 |
+
|
197 |
+
# Same situation here; this time we assume that the buffer is
|
198 |
+
# actually binary in case it's closed.
|
199 |
+
if buf is not None and _is_binary_writer(buf, True):
|
200 |
+
return t.cast(t.BinaryIO, buf)
|
201 |
+
|
202 |
+
return None
|
203 |
+
|
204 |
+
|
205 |
+
def _stream_is_misconfigured(stream: t.TextIO) -> bool:
|
206 |
+
"""A stream is misconfigured if its encoding is ASCII."""
|
207 |
+
# If the stream does not have an encoding set, we assume it's set
|
208 |
+
# to ASCII. This appears to happen in certain unittest
|
209 |
+
# environments. It's not quite clear what the correct behavior is
|
210 |
+
# but this at least will force Click to recover somehow.
|
211 |
+
return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")
|
212 |
+
|
213 |
+
|
214 |
+
def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: t.Optional[str]) -> bool:
|
215 |
+
"""A stream attribute is compatible if it is equal to the
|
216 |
+
desired value or the desired value is unset and the attribute
|
217 |
+
has a value.
|
218 |
+
"""
|
219 |
+
stream_value = getattr(stream, attr, None)
|
220 |
+
return stream_value == value or (value is None and stream_value is not None)
|
221 |
+
|
222 |
+
|
223 |
+
def _is_compatible_text_stream(
|
224 |
+
stream: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]
|
225 |
+
) -> bool:
|
226 |
+
"""Check if a stream's encoding and errors attributes are
|
227 |
+
compatible with the desired values.
|
228 |
+
"""
|
229 |
+
return _is_compat_stream_attr(
|
230 |
+
stream, "encoding", encoding
|
231 |
+
) and _is_compat_stream_attr(stream, "errors", errors)
|
232 |
+
|
233 |
+
|
234 |
+
def _force_correct_text_stream(
|
235 |
+
text_stream: t.IO[t.Any],
|
236 |
+
encoding: t.Optional[str],
|
237 |
+
errors: t.Optional[str],
|
238 |
+
is_binary: t.Callable[[t.IO[t.Any], bool], bool],
|
239 |
+
find_binary: t.Callable[[t.IO[t.Any]], t.Optional[t.BinaryIO]],
|
240 |
+
force_readable: bool = False,
|
241 |
+
force_writable: bool = False,
|
242 |
+
) -> t.TextIO:
|
243 |
+
if is_binary(text_stream, False):
|
244 |
+
binary_reader = t.cast(t.BinaryIO, text_stream)
|
245 |
+
else:
|
246 |
+
text_stream = t.cast(t.TextIO, text_stream)
|
247 |
+
# If the stream looks compatible, and won't default to a
|
248 |
+
# misconfigured ascii encoding, return it as-is.
|
249 |
+
if _is_compatible_text_stream(text_stream, encoding, errors) and not (
|
250 |
+
encoding is None and _stream_is_misconfigured(text_stream)
|
251 |
+
):
|
252 |
+
return text_stream
|
253 |
+
|
254 |
+
# Otherwise, get the underlying binary reader.
|
255 |
+
possible_binary_reader = find_binary(text_stream)
|
256 |
+
|
257 |
+
# If that's not possible, silently use the original reader
|
258 |
+
# and get mojibake instead of exceptions.
|
259 |
+
if possible_binary_reader is None:
|
260 |
+
return text_stream
|
261 |
+
|
262 |
+
binary_reader = possible_binary_reader
|
263 |
+
|
264 |
+
# Default errors to replace instead of strict in order to get
|
265 |
+
# something that works.
|
266 |
+
if errors is None:
|
267 |
+
errors = "replace"
|
268 |
+
|
269 |
+
# Wrap the binary stream in a text stream with the correct
|
270 |
+
# encoding parameters.
|
271 |
+
return _make_text_stream(
|
272 |
+
binary_reader,
|
273 |
+
encoding,
|
274 |
+
errors,
|
275 |
+
force_readable=force_readable,
|
276 |
+
force_writable=force_writable,
|
277 |
+
)
|
278 |
+
|
279 |
+
|
280 |
+
def _force_correct_text_reader(
|
281 |
+
text_reader: t.IO[t.Any],
|
282 |
+
encoding: t.Optional[str],
|
283 |
+
errors: t.Optional[str],
|
284 |
+
force_readable: bool = False,
|
285 |
+
) -> t.TextIO:
|
286 |
+
return _force_correct_text_stream(
|
287 |
+
text_reader,
|
288 |
+
encoding,
|
289 |
+
errors,
|
290 |
+
_is_binary_reader,
|
291 |
+
_find_binary_reader,
|
292 |
+
force_readable=force_readable,
|
293 |
+
)
|
294 |
+
|
295 |
+
|
296 |
+
def _force_correct_text_writer(
|
297 |
+
text_writer: t.IO[t.Any],
|
298 |
+
encoding: t.Optional[str],
|
299 |
+
errors: t.Optional[str],
|
300 |
+
force_writable: bool = False,
|
301 |
+
) -> t.TextIO:
|
302 |
+
return _force_correct_text_stream(
|
303 |
+
text_writer,
|
304 |
+
encoding,
|
305 |
+
errors,
|
306 |
+
_is_binary_writer,
|
307 |
+
_find_binary_writer,
|
308 |
+
force_writable=force_writable,
|
309 |
+
)
|
310 |
+
|
311 |
+
|
312 |
+
def get_binary_stdin() -> t.BinaryIO:
|
313 |
+
reader = _find_binary_reader(sys.stdin)
|
314 |
+
if reader is None:
|
315 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stdin.")
|
316 |
+
return reader
|
317 |
+
|
318 |
+
|
319 |
+
def get_binary_stdout() -> t.BinaryIO:
|
320 |
+
writer = _find_binary_writer(sys.stdout)
|
321 |
+
if writer is None:
|
322 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stdout.")
|
323 |
+
return writer
|
324 |
+
|
325 |
+
|
326 |
+
def get_binary_stderr() -> t.BinaryIO:
|
327 |
+
writer = _find_binary_writer(sys.stderr)
|
328 |
+
if writer is None:
|
329 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stderr.")
|
330 |
+
return writer
|
331 |
+
|
332 |
+
|
333 |
+
def get_text_stdin(
|
334 |
+
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
|
335 |
+
) -> t.TextIO:
|
336 |
+
rv = _get_windows_console_stream(sys.stdin, encoding, errors)
|
337 |
+
if rv is not None:
|
338 |
+
return rv
|
339 |
+
return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)
|
340 |
+
|
341 |
+
|
342 |
+
def get_text_stdout(
|
343 |
+
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
|
344 |
+
) -> t.TextIO:
|
345 |
+
rv = _get_windows_console_stream(sys.stdout, encoding, errors)
|
346 |
+
if rv is not None:
|
347 |
+
return rv
|
348 |
+
return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)
|
349 |
+
|
350 |
+
|
351 |
+
def get_text_stderr(
|
352 |
+
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
|
353 |
+
) -> t.TextIO:
|
354 |
+
rv = _get_windows_console_stream(sys.stderr, encoding, errors)
|
355 |
+
if rv is not None:
|
356 |
+
return rv
|
357 |
+
return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)
|
358 |
+
|
359 |
+
|
360 |
+
def _wrap_io_open(
|
361 |
+
file: t.Union[str, "os.PathLike[str]", int],
|
362 |
+
mode: str,
|
363 |
+
encoding: t.Optional[str],
|
364 |
+
errors: t.Optional[str],
|
365 |
+
) -> t.IO[t.Any]:
|
366 |
+
"""Handles not passing ``encoding`` and ``errors`` in binary mode."""
|
367 |
+
if "b" in mode:
|
368 |
+
return open(file, mode)
|
369 |
+
|
370 |
+
return open(file, mode, encoding=encoding, errors=errors)
|
371 |
+
|
372 |
+
|
373 |
+
def open_stream(
|
374 |
+
filename: "t.Union[str, os.PathLike[str]]",
|
375 |
+
mode: str = "r",
|
376 |
+
encoding: t.Optional[str] = None,
|
377 |
+
errors: t.Optional[str] = "strict",
|
378 |
+
atomic: bool = False,
|
379 |
+
) -> t.Tuple[t.IO[t.Any], bool]:
|
380 |
+
binary = "b" in mode
|
381 |
+
filename = os.fspath(filename)
|
382 |
+
|
383 |
+
# Standard streams first. These are simple because they ignore the
|
384 |
+
# atomic flag. Use fsdecode to handle Path("-").
|
385 |
+
if os.fsdecode(filename) == "-":
|
386 |
+
if any(m in mode for m in ["w", "a", "x"]):
|
387 |
+
if binary:
|
388 |
+
return get_binary_stdout(), False
|
389 |
+
return get_text_stdout(encoding=encoding, errors=errors), False
|
390 |
+
if binary:
|
391 |
+
return get_binary_stdin(), False
|
392 |
+
return get_text_stdin(encoding=encoding, errors=errors), False
|
393 |
+
|
394 |
+
# Non-atomic writes directly go out through the regular open functions.
|
395 |
+
if not atomic:
|
396 |
+
return _wrap_io_open(filename, mode, encoding, errors), True
|
397 |
+
|
398 |
+
# Some usability stuff for atomic writes
|
399 |
+
if "a" in mode:
|
400 |
+
raise ValueError(
|
401 |
+
"Appending to an existing file is not supported, because that"
|
402 |
+
" would involve an expensive `copy`-operation to a temporary"
|
403 |
+
" file. Open the file in normal `w`-mode and copy explicitly"
|
404 |
+
" if that's what you're after."
|
405 |
+
)
|
406 |
+
if "x" in mode:
|
407 |
+
raise ValueError("Use the `overwrite`-parameter instead.")
|
408 |
+
if "w" not in mode:
|
409 |
+
raise ValueError("Atomic writes only make sense with `w`-mode.")
|
410 |
+
|
411 |
+
# Atomic writes are more complicated. They work by opening a file
|
412 |
+
# as a proxy in the same folder and then using the fdopen
|
413 |
+
# functionality to wrap it in a Python file. Then we wrap it in an
|
414 |
+
# atomic file that moves the file over on close.
|
415 |
+
import errno
|
416 |
+
import random
|
417 |
+
|
418 |
+
try:
|
419 |
+
perm: t.Optional[int] = os.stat(filename).st_mode
|
420 |
+
except OSError:
|
421 |
+
perm = None
|
422 |
+
|
423 |
+
flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
|
424 |
+
|
425 |
+
if binary:
|
426 |
+
flags |= getattr(os, "O_BINARY", 0)
|
427 |
+
|
428 |
+
while True:
|
429 |
+
tmp_filename = os.path.join(
|
430 |
+
os.path.dirname(filename),
|
431 |
+
f".__atomic-write{random.randrange(1 << 32):08x}",
|
432 |
+
)
|
433 |
+
try:
|
434 |
+
fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)
|
435 |
+
break
|
436 |
+
except OSError as e:
|
437 |
+
if e.errno == errno.EEXIST or (
|
438 |
+
os.name == "nt"
|
439 |
+
and e.errno == errno.EACCES
|
440 |
+
and os.path.isdir(e.filename)
|
441 |
+
and os.access(e.filename, os.W_OK)
|
442 |
+
):
|
443 |
+
continue
|
444 |
+
raise
|
445 |
+
|
446 |
+
if perm is not None:
|
447 |
+
os.chmod(tmp_filename, perm) # in case perm includes bits in umask
|
448 |
+
|
449 |
+
f = _wrap_io_open(fd, mode, encoding, errors)
|
450 |
+
af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))
|
451 |
+
return t.cast(t.IO[t.Any], af), True
|
452 |
+
|
453 |
+
|
454 |
+
class _AtomicFile:
|
455 |
+
def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None:
|
456 |
+
self._f = f
|
457 |
+
self._tmp_filename = tmp_filename
|
458 |
+
self._real_filename = real_filename
|
459 |
+
self.closed = False
|
460 |
+
|
461 |
+
@property
|
462 |
+
def name(self) -> str:
|
463 |
+
return self._real_filename
|
464 |
+
|
465 |
+
def close(self, delete: bool = False) -> None:
|
466 |
+
if self.closed:
|
467 |
+
return
|
468 |
+
self._f.close()
|
469 |
+
os.replace(self._tmp_filename, self._real_filename)
|
470 |
+
self.closed = True
|
471 |
+
|
472 |
+
def __getattr__(self, name: str) -> t.Any:
|
473 |
+
return getattr(self._f, name)
|
474 |
+
|
475 |
+
def __enter__(self) -> "_AtomicFile":
|
476 |
+
return self
|
477 |
+
|
478 |
+
def __exit__(self, exc_type: t.Optional[t.Type[BaseException]], *_: t.Any) -> None:
|
479 |
+
self.close(delete=exc_type is not None)
|
480 |
+
|
481 |
+
def __repr__(self) -> str:
|
482 |
+
return repr(self._f)
|
483 |
+
|
484 |
+
|
485 |
+
def strip_ansi(value: str) -> str:
|
486 |
+
return _ansi_re.sub("", value)
|
487 |
+
|
488 |
+
|
489 |
+
def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:
|
490 |
+
while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):
|
491 |
+
stream = stream._stream
|
492 |
+
|
493 |
+
return stream.__class__.__module__.startswith("ipykernel.")
|
494 |
+
|
495 |
+
|
496 |
+
def should_strip_ansi(
|
497 |
+
stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None
|
498 |
+
) -> bool:
|
499 |
+
if color is None:
|
500 |
+
if stream is None:
|
501 |
+
stream = sys.stdin
|
502 |
+
return not isatty(stream) and not _is_jupyter_kernel_output(stream)
|
503 |
+
return not color
|
504 |
+
|
505 |
+
|
506 |
+
# On Windows, wrap the output streams with colorama to support ANSI
|
507 |
+
# color codes.
|
508 |
+
# NOTE: double check is needed so mypy does not analyze this on Linux
|
509 |
+
if sys.platform.startswith("win") and WIN:
|
510 |
+
from ._winconsole import _get_windows_console_stream
|
511 |
+
|
512 |
+
def _get_argv_encoding() -> str:
|
513 |
+
import locale
|
514 |
+
|
515 |
+
return locale.getpreferredencoding()
|
516 |
+
|
517 |
+
_ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
|
518 |
+
|
519 |
+
def auto_wrap_for_ansi( # noqa: F811
|
520 |
+
stream: t.TextIO, color: t.Optional[bool] = None
|
521 |
+
) -> t.TextIO:
|
522 |
+
"""Support ANSI color and style codes on Windows by wrapping a
|
523 |
+
stream with colorama.
|
524 |
+
"""
|
525 |
+
try:
|
526 |
+
cached = _ansi_stream_wrappers.get(stream)
|
527 |
+
except Exception:
|
528 |
+
cached = None
|
529 |
+
|
530 |
+
if cached is not None:
|
531 |
+
return cached
|
532 |
+
|
533 |
+
import colorama
|
534 |
+
|
535 |
+
strip = should_strip_ansi(stream, color)
|
536 |
+
ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
|
537 |
+
rv = t.cast(t.TextIO, ansi_wrapper.stream)
|
538 |
+
_write = rv.write
|
539 |
+
|
540 |
+
def _safe_write(s):
|
541 |
+
try:
|
542 |
+
return _write(s)
|
543 |
+
except BaseException:
|
544 |
+
ansi_wrapper.reset_all()
|
545 |
+
raise
|
546 |
+
|
547 |
+
rv.write = _safe_write
|
548 |
+
|
549 |
+
try:
|
550 |
+
_ansi_stream_wrappers[stream] = rv
|
551 |
+
except Exception:
|
552 |
+
pass
|
553 |
+
|
554 |
+
return rv
|
555 |
+
|
556 |
+
else:
|
557 |
+
|
558 |
+
def _get_argv_encoding() -> str:
|
559 |
+
return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()
|
560 |
+
|
561 |
+
def _get_windows_console_stream(
|
562 |
+
f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]
|
563 |
+
) -> t.Optional[t.TextIO]:
|
564 |
+
return None
|
565 |
+
|
566 |
+
|
567 |
+
def term_len(x: str) -> int:
|
568 |
+
return len(strip_ansi(x))
|
569 |
+
|
570 |
+
|
571 |
+
def isatty(stream: t.IO[t.Any]) -> bool:
|
572 |
+
try:
|
573 |
+
return stream.isatty()
|
574 |
+
except Exception:
|
575 |
+
return False
|
576 |
+
|
577 |
+
|
578 |
+
def _make_cached_stream_func(
|
579 |
+
src_func: t.Callable[[], t.Optional[t.TextIO]],
|
580 |
+
wrapper_func: t.Callable[[], t.TextIO],
|
581 |
+
) -> t.Callable[[], t.Optional[t.TextIO]]:
|
582 |
+
cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
|
583 |
+
|
584 |
+
def func() -> t.Optional[t.TextIO]:
|
585 |
+
stream = src_func()
|
586 |
+
|
587 |
+
if stream is None:
|
588 |
+
return None
|
589 |
+
|
590 |
+
try:
|
591 |
+
rv = cache.get(stream)
|
592 |
+
except Exception:
|
593 |
+
rv = None
|
594 |
+
if rv is not None:
|
595 |
+
return rv
|
596 |
+
rv = wrapper_func()
|
597 |
+
try:
|
598 |
+
cache[stream] = rv
|
599 |
+
except Exception:
|
600 |
+
pass
|
601 |
+
return rv
|
602 |
+
|
603 |
+
return func
|
604 |
+
|
605 |
+
|
606 |
+
_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)
|
607 |
+
_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)
|
608 |
+
_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)
|
609 |
+
|
610 |
+
|
611 |
+
binary_streams: t.Mapping[str, t.Callable[[], t.BinaryIO]] = {
|
612 |
+
"stdin": get_binary_stdin,
|
613 |
+
"stdout": get_binary_stdout,
|
614 |
+
"stderr": get_binary_stderr,
|
615 |
+
}
|
616 |
+
|
617 |
+
text_streams: t.Mapping[
|
618 |
+
str, t.Callable[[t.Optional[str], t.Optional[str]], t.TextIO]
|
619 |
+
] = {
|
620 |
+
"stdin": get_text_stdin,
|
621 |
+
"stdout": get_text_stdout,
|
622 |
+
"stderr": get_text_stderr,
|
623 |
+
}
|
llmeval-env/lib/python3.10/site-packages/click/_termui_impl.py
ADDED
@@ -0,0 +1,739 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module contains implementations for the termui module. To keep the
|
3 |
+
import time of Click down, some infrequently used functionality is
|
4 |
+
placed in this module and only imported as needed.
|
5 |
+
"""
|
6 |
+
import contextlib
|
7 |
+
import math
|
8 |
+
import os
|
9 |
+
import sys
|
10 |
+
import time
|
11 |
+
import typing as t
|
12 |
+
from gettext import gettext as _
|
13 |
+
from io import StringIO
|
14 |
+
from types import TracebackType
|
15 |
+
|
16 |
+
from ._compat import _default_text_stdout
|
17 |
+
from ._compat import CYGWIN
|
18 |
+
from ._compat import get_best_encoding
|
19 |
+
from ._compat import isatty
|
20 |
+
from ._compat import open_stream
|
21 |
+
from ._compat import strip_ansi
|
22 |
+
from ._compat import term_len
|
23 |
+
from ._compat import WIN
|
24 |
+
from .exceptions import ClickException
|
25 |
+
from .utils import echo
|
26 |
+
|
27 |
+
V = t.TypeVar("V")
|
28 |
+
|
29 |
+
if os.name == "nt":
|
30 |
+
BEFORE_BAR = "\r"
|
31 |
+
AFTER_BAR = "\n"
|
32 |
+
else:
|
33 |
+
BEFORE_BAR = "\r\033[?25l"
|
34 |
+
AFTER_BAR = "\033[?25h\n"
|
35 |
+
|
36 |
+
|
37 |
+
class ProgressBar(t.Generic[V]):
|
38 |
+
def __init__(
|
39 |
+
self,
|
40 |
+
iterable: t.Optional[t.Iterable[V]],
|
41 |
+
length: t.Optional[int] = None,
|
42 |
+
fill_char: str = "#",
|
43 |
+
empty_char: str = " ",
|
44 |
+
bar_template: str = "%(bar)s",
|
45 |
+
info_sep: str = " ",
|
46 |
+
show_eta: bool = True,
|
47 |
+
show_percent: t.Optional[bool] = None,
|
48 |
+
show_pos: bool = False,
|
49 |
+
item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,
|
50 |
+
label: t.Optional[str] = None,
|
51 |
+
file: t.Optional[t.TextIO] = None,
|
52 |
+
color: t.Optional[bool] = None,
|
53 |
+
update_min_steps: int = 1,
|
54 |
+
width: int = 30,
|
55 |
+
) -> None:
|
56 |
+
self.fill_char = fill_char
|
57 |
+
self.empty_char = empty_char
|
58 |
+
self.bar_template = bar_template
|
59 |
+
self.info_sep = info_sep
|
60 |
+
self.show_eta = show_eta
|
61 |
+
self.show_percent = show_percent
|
62 |
+
self.show_pos = show_pos
|
63 |
+
self.item_show_func = item_show_func
|
64 |
+
self.label: str = label or ""
|
65 |
+
|
66 |
+
if file is None:
|
67 |
+
file = _default_text_stdout()
|
68 |
+
|
69 |
+
# There are no standard streams attached to write to. For example,
|
70 |
+
# pythonw on Windows.
|
71 |
+
if file is None:
|
72 |
+
file = StringIO()
|
73 |
+
|
74 |
+
self.file = file
|
75 |
+
self.color = color
|
76 |
+
self.update_min_steps = update_min_steps
|
77 |
+
self._completed_intervals = 0
|
78 |
+
self.width: int = width
|
79 |
+
self.autowidth: bool = width == 0
|
80 |
+
|
81 |
+
if length is None:
|
82 |
+
from operator import length_hint
|
83 |
+
|
84 |
+
length = length_hint(iterable, -1)
|
85 |
+
|
86 |
+
if length == -1:
|
87 |
+
length = None
|
88 |
+
if iterable is None:
|
89 |
+
if length is None:
|
90 |
+
raise TypeError("iterable or length is required")
|
91 |
+
iterable = t.cast(t.Iterable[V], range(length))
|
92 |
+
self.iter: t.Iterable[V] = iter(iterable)
|
93 |
+
self.length = length
|
94 |
+
self.pos = 0
|
95 |
+
self.avg: t.List[float] = []
|
96 |
+
self.last_eta: float
|
97 |
+
self.start: float
|
98 |
+
self.start = self.last_eta = time.time()
|
99 |
+
self.eta_known: bool = False
|
100 |
+
self.finished: bool = False
|
101 |
+
self.max_width: t.Optional[int] = None
|
102 |
+
self.entered: bool = False
|
103 |
+
self.current_item: t.Optional[V] = None
|
104 |
+
self.is_hidden: bool = not isatty(self.file)
|
105 |
+
self._last_line: t.Optional[str] = None
|
106 |
+
|
107 |
+
def __enter__(self) -> "ProgressBar[V]":
|
108 |
+
self.entered = True
|
109 |
+
self.render_progress()
|
110 |
+
return self
|
111 |
+
|
112 |
+
def __exit__(
|
113 |
+
self,
|
114 |
+
exc_type: t.Optional[t.Type[BaseException]],
|
115 |
+
exc_value: t.Optional[BaseException],
|
116 |
+
tb: t.Optional[TracebackType],
|
117 |
+
) -> None:
|
118 |
+
self.render_finish()
|
119 |
+
|
120 |
+
def __iter__(self) -> t.Iterator[V]:
|
121 |
+
if not self.entered:
|
122 |
+
raise RuntimeError("You need to use progress bars in a with block.")
|
123 |
+
self.render_progress()
|
124 |
+
return self.generator()
|
125 |
+
|
126 |
+
def __next__(self) -> V:
|
127 |
+
# Iteration is defined in terms of a generator function,
|
128 |
+
# returned by iter(self); use that to define next(). This works
|
129 |
+
# because `self.iter` is an iterable consumed by that generator,
|
130 |
+
# so it is re-entry safe. Calling `next(self.generator())`
|
131 |
+
# twice works and does "what you want".
|
132 |
+
return next(iter(self))
|
133 |
+
|
134 |
+
def render_finish(self) -> None:
|
135 |
+
if self.is_hidden:
|
136 |
+
return
|
137 |
+
self.file.write(AFTER_BAR)
|
138 |
+
self.file.flush()
|
139 |
+
|
140 |
+
@property
|
141 |
+
def pct(self) -> float:
|
142 |
+
if self.finished:
|
143 |
+
return 1.0
|
144 |
+
return min(self.pos / (float(self.length or 1) or 1), 1.0)
|
145 |
+
|
146 |
+
@property
|
147 |
+
def time_per_iteration(self) -> float:
|
148 |
+
if not self.avg:
|
149 |
+
return 0.0
|
150 |
+
return sum(self.avg) / float(len(self.avg))
|
151 |
+
|
152 |
+
@property
|
153 |
+
def eta(self) -> float:
|
154 |
+
if self.length is not None and not self.finished:
|
155 |
+
return self.time_per_iteration * (self.length - self.pos)
|
156 |
+
return 0.0
|
157 |
+
|
158 |
+
def format_eta(self) -> str:
|
159 |
+
if self.eta_known:
|
160 |
+
t = int(self.eta)
|
161 |
+
seconds = t % 60
|
162 |
+
t //= 60
|
163 |
+
minutes = t % 60
|
164 |
+
t //= 60
|
165 |
+
hours = t % 24
|
166 |
+
t //= 24
|
167 |
+
if t > 0:
|
168 |
+
return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"
|
169 |
+
else:
|
170 |
+
return f"{hours:02}:{minutes:02}:{seconds:02}"
|
171 |
+
return ""
|
172 |
+
|
173 |
+
def format_pos(self) -> str:
|
174 |
+
pos = str(self.pos)
|
175 |
+
if self.length is not None:
|
176 |
+
pos += f"/{self.length}"
|
177 |
+
return pos
|
178 |
+
|
179 |
+
def format_pct(self) -> str:
|
180 |
+
return f"{int(self.pct * 100): 4}%"[1:]
|
181 |
+
|
182 |
+
def format_bar(self) -> str:
|
183 |
+
if self.length is not None:
|
184 |
+
bar_length = int(self.pct * self.width)
|
185 |
+
bar = self.fill_char * bar_length
|
186 |
+
bar += self.empty_char * (self.width - bar_length)
|
187 |
+
elif self.finished:
|
188 |
+
bar = self.fill_char * self.width
|
189 |
+
else:
|
190 |
+
chars = list(self.empty_char * (self.width or 1))
|
191 |
+
if self.time_per_iteration != 0:
|
192 |
+
chars[
|
193 |
+
int(
|
194 |
+
(math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)
|
195 |
+
* self.width
|
196 |
+
)
|
197 |
+
] = self.fill_char
|
198 |
+
bar = "".join(chars)
|
199 |
+
return bar
|
200 |
+
|
201 |
+
def format_progress_line(self) -> str:
|
202 |
+
show_percent = self.show_percent
|
203 |
+
|
204 |
+
info_bits = []
|
205 |
+
if self.length is not None and show_percent is None:
|
206 |
+
show_percent = not self.show_pos
|
207 |
+
|
208 |
+
if self.show_pos:
|
209 |
+
info_bits.append(self.format_pos())
|
210 |
+
if show_percent:
|
211 |
+
info_bits.append(self.format_pct())
|
212 |
+
if self.show_eta and self.eta_known and not self.finished:
|
213 |
+
info_bits.append(self.format_eta())
|
214 |
+
if self.item_show_func is not None:
|
215 |
+
item_info = self.item_show_func(self.current_item)
|
216 |
+
if item_info is not None:
|
217 |
+
info_bits.append(item_info)
|
218 |
+
|
219 |
+
return (
|
220 |
+
self.bar_template
|
221 |
+
% {
|
222 |
+
"label": self.label,
|
223 |
+
"bar": self.format_bar(),
|
224 |
+
"info": self.info_sep.join(info_bits),
|
225 |
+
}
|
226 |
+
).rstrip()
|
227 |
+
|
228 |
+
def render_progress(self) -> None:
|
229 |
+
import shutil
|
230 |
+
|
231 |
+
if self.is_hidden:
|
232 |
+
# Only output the label as it changes if the output is not a
|
233 |
+
# TTY. Use file=stderr if you expect to be piping stdout.
|
234 |
+
if self._last_line != self.label:
|
235 |
+
self._last_line = self.label
|
236 |
+
echo(self.label, file=self.file, color=self.color)
|
237 |
+
|
238 |
+
return
|
239 |
+
|
240 |
+
buf = []
|
241 |
+
# Update width in case the terminal has been resized
|
242 |
+
if self.autowidth:
|
243 |
+
old_width = self.width
|
244 |
+
self.width = 0
|
245 |
+
clutter_length = term_len(self.format_progress_line())
|
246 |
+
new_width = max(0, shutil.get_terminal_size().columns - clutter_length)
|
247 |
+
if new_width < old_width:
|
248 |
+
buf.append(BEFORE_BAR)
|
249 |
+
buf.append(" " * self.max_width) # type: ignore
|
250 |
+
self.max_width = new_width
|
251 |
+
self.width = new_width
|
252 |
+
|
253 |
+
clear_width = self.width
|
254 |
+
if self.max_width is not None:
|
255 |
+
clear_width = self.max_width
|
256 |
+
|
257 |
+
buf.append(BEFORE_BAR)
|
258 |
+
line = self.format_progress_line()
|
259 |
+
line_len = term_len(line)
|
260 |
+
if self.max_width is None or self.max_width < line_len:
|
261 |
+
self.max_width = line_len
|
262 |
+
|
263 |
+
buf.append(line)
|
264 |
+
buf.append(" " * (clear_width - line_len))
|
265 |
+
line = "".join(buf)
|
266 |
+
# Render the line only if it changed.
|
267 |
+
|
268 |
+
if line != self._last_line:
|
269 |
+
self._last_line = line
|
270 |
+
echo(line, file=self.file, color=self.color, nl=False)
|
271 |
+
self.file.flush()
|
272 |
+
|
273 |
+
def make_step(self, n_steps: int) -> None:
|
274 |
+
self.pos += n_steps
|
275 |
+
if self.length is not None and self.pos >= self.length:
|
276 |
+
self.finished = True
|
277 |
+
|
278 |
+
if (time.time() - self.last_eta) < 1.0:
|
279 |
+
return
|
280 |
+
|
281 |
+
self.last_eta = time.time()
|
282 |
+
|
283 |
+
# self.avg is a rolling list of length <= 7 of steps where steps are
|
284 |
+
# defined as time elapsed divided by the total progress through
|
285 |
+
# self.length.
|
286 |
+
if self.pos:
|
287 |
+
step = (time.time() - self.start) / self.pos
|
288 |
+
else:
|
289 |
+
step = time.time() - self.start
|
290 |
+
|
291 |
+
self.avg = self.avg[-6:] + [step]
|
292 |
+
|
293 |
+
self.eta_known = self.length is not None
|
294 |
+
|
295 |
+
def update(self, n_steps: int, current_item: t.Optional[V] = None) -> None:
|
296 |
+
"""Update the progress bar by advancing a specified number of
|
297 |
+
steps, and optionally set the ``current_item`` for this new
|
298 |
+
position.
|
299 |
+
|
300 |
+
:param n_steps: Number of steps to advance.
|
301 |
+
:param current_item: Optional item to set as ``current_item``
|
302 |
+
for the updated position.
|
303 |
+
|
304 |
+
.. versionchanged:: 8.0
|
305 |
+
Added the ``current_item`` optional parameter.
|
306 |
+
|
307 |
+
.. versionchanged:: 8.0
|
308 |
+
Only render when the number of steps meets the
|
309 |
+
``update_min_steps`` threshold.
|
310 |
+
"""
|
311 |
+
if current_item is not None:
|
312 |
+
self.current_item = current_item
|
313 |
+
|
314 |
+
self._completed_intervals += n_steps
|
315 |
+
|
316 |
+
if self._completed_intervals >= self.update_min_steps:
|
317 |
+
self.make_step(self._completed_intervals)
|
318 |
+
self.render_progress()
|
319 |
+
self._completed_intervals = 0
|
320 |
+
|
321 |
+
def finish(self) -> None:
|
322 |
+
self.eta_known = False
|
323 |
+
self.current_item = None
|
324 |
+
self.finished = True
|
325 |
+
|
326 |
+
def generator(self) -> t.Iterator[V]:
|
327 |
+
"""Return a generator which yields the items added to the bar
|
328 |
+
during construction, and updates the progress bar *after* the
|
329 |
+
yielded block returns.
|
330 |
+
"""
|
331 |
+
# WARNING: the iterator interface for `ProgressBar` relies on
|
332 |
+
# this and only works because this is a simple generator which
|
333 |
+
# doesn't create or manage additional state. If this function
|
334 |
+
# changes, the impact should be evaluated both against
|
335 |
+
# `iter(bar)` and `next(bar)`. `next()` in particular may call
|
336 |
+
# `self.generator()` repeatedly, and this must remain safe in
|
337 |
+
# order for that interface to work.
|
338 |
+
if not self.entered:
|
339 |
+
raise RuntimeError("You need to use progress bars in a with block.")
|
340 |
+
|
341 |
+
if self.is_hidden:
|
342 |
+
yield from self.iter
|
343 |
+
else:
|
344 |
+
for rv in self.iter:
|
345 |
+
self.current_item = rv
|
346 |
+
|
347 |
+
# This allows show_item_func to be updated before the
|
348 |
+
# item is processed. Only trigger at the beginning of
|
349 |
+
# the update interval.
|
350 |
+
if self._completed_intervals == 0:
|
351 |
+
self.render_progress()
|
352 |
+
|
353 |
+
yield rv
|
354 |
+
self.update(1)
|
355 |
+
|
356 |
+
self.finish()
|
357 |
+
self.render_progress()
|
358 |
+
|
359 |
+
|
360 |
+
def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:
|
361 |
+
"""Decide what method to use for paging through text."""
|
362 |
+
stdout = _default_text_stdout()
|
363 |
+
|
364 |
+
# There are no standard streams attached to write to. For example,
|
365 |
+
# pythonw on Windows.
|
366 |
+
if stdout is None:
|
367 |
+
stdout = StringIO()
|
368 |
+
|
369 |
+
if not isatty(sys.stdin) or not isatty(stdout):
|
370 |
+
return _nullpager(stdout, generator, color)
|
371 |
+
pager_cmd = (os.environ.get("PAGER", None) or "").strip()
|
372 |
+
if pager_cmd:
|
373 |
+
if WIN:
|
374 |
+
return _tempfilepager(generator, pager_cmd, color)
|
375 |
+
return _pipepager(generator, pager_cmd, color)
|
376 |
+
if os.environ.get("TERM") in ("dumb", "emacs"):
|
377 |
+
return _nullpager(stdout, generator, color)
|
378 |
+
if WIN or sys.platform.startswith("os2"):
|
379 |
+
return _tempfilepager(generator, "more <", color)
|
380 |
+
if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:
|
381 |
+
return _pipepager(generator, "less", color)
|
382 |
+
|
383 |
+
import tempfile
|
384 |
+
|
385 |
+
fd, filename = tempfile.mkstemp()
|
386 |
+
os.close(fd)
|
387 |
+
try:
|
388 |
+
if hasattr(os, "system") and os.system(f'more "{filename}"') == 0:
|
389 |
+
return _pipepager(generator, "more", color)
|
390 |
+
return _nullpager(stdout, generator, color)
|
391 |
+
finally:
|
392 |
+
os.unlink(filename)
|
393 |
+
|
394 |
+
|
395 |
+
def _pipepager(generator: t.Iterable[str], cmd: str, color: t.Optional[bool]) -> None:
|
396 |
+
"""Page through text by feeding it to another program. Invoking a
|
397 |
+
pager through this might support colors.
|
398 |
+
"""
|
399 |
+
import subprocess
|
400 |
+
|
401 |
+
env = dict(os.environ)
|
402 |
+
|
403 |
+
# If we're piping to less we might support colors under the
|
404 |
+
# condition that
|
405 |
+
cmd_detail = cmd.rsplit("/", 1)[-1].split()
|
406 |
+
if color is None and cmd_detail[0] == "less":
|
407 |
+
less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"
|
408 |
+
if not less_flags:
|
409 |
+
env["LESS"] = "-R"
|
410 |
+
color = True
|
411 |
+
elif "r" in less_flags or "R" in less_flags:
|
412 |
+
color = True
|
413 |
+
|
414 |
+
c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)
|
415 |
+
stdin = t.cast(t.BinaryIO, c.stdin)
|
416 |
+
encoding = get_best_encoding(stdin)
|
417 |
+
try:
|
418 |
+
for text in generator:
|
419 |
+
if not color:
|
420 |
+
text = strip_ansi(text)
|
421 |
+
|
422 |
+
stdin.write(text.encode(encoding, "replace"))
|
423 |
+
except (OSError, KeyboardInterrupt):
|
424 |
+
pass
|
425 |
+
else:
|
426 |
+
stdin.close()
|
427 |
+
|
428 |
+
# Less doesn't respect ^C, but catches it for its own UI purposes (aborting
|
429 |
+
# search or other commands inside less).
|
430 |
+
#
|
431 |
+
# That means when the user hits ^C, the parent process (click) terminates,
|
432 |
+
# but less is still alive, paging the output and messing up the terminal.
|
433 |
+
#
|
434 |
+
# If the user wants to make the pager exit on ^C, they should set
|
435 |
+
# `LESS='-K'`. It's not our decision to make.
|
436 |
+
while True:
|
437 |
+
try:
|
438 |
+
c.wait()
|
439 |
+
except KeyboardInterrupt:
|
440 |
+
pass
|
441 |
+
else:
|
442 |
+
break
|
443 |
+
|
444 |
+
|
445 |
+
def _tempfilepager(
|
446 |
+
generator: t.Iterable[str], cmd: str, color: t.Optional[bool]
|
447 |
+
) -> None:
|
448 |
+
"""Page through text by invoking a program on a temporary file."""
|
449 |
+
import tempfile
|
450 |
+
|
451 |
+
fd, filename = tempfile.mkstemp()
|
452 |
+
# TODO: This never terminates if the passed generator never terminates.
|
453 |
+
text = "".join(generator)
|
454 |
+
if not color:
|
455 |
+
text = strip_ansi(text)
|
456 |
+
encoding = get_best_encoding(sys.stdout)
|
457 |
+
with open_stream(filename, "wb")[0] as f:
|
458 |
+
f.write(text.encode(encoding))
|
459 |
+
try:
|
460 |
+
os.system(f'{cmd} "{filename}"')
|
461 |
+
finally:
|
462 |
+
os.close(fd)
|
463 |
+
os.unlink(filename)
|
464 |
+
|
465 |
+
|
466 |
+
def _nullpager(
|
467 |
+
stream: t.TextIO, generator: t.Iterable[str], color: t.Optional[bool]
|
468 |
+
) -> None:
|
469 |
+
"""Simply print unformatted text. This is the ultimate fallback."""
|
470 |
+
for text in generator:
|
471 |
+
if not color:
|
472 |
+
text = strip_ansi(text)
|
473 |
+
stream.write(text)
|
474 |
+
|
475 |
+
|
476 |
+
class Editor:
|
477 |
+
def __init__(
|
478 |
+
self,
|
479 |
+
editor: t.Optional[str] = None,
|
480 |
+
env: t.Optional[t.Mapping[str, str]] = None,
|
481 |
+
require_save: bool = True,
|
482 |
+
extension: str = ".txt",
|
483 |
+
) -> None:
|
484 |
+
self.editor = editor
|
485 |
+
self.env = env
|
486 |
+
self.require_save = require_save
|
487 |
+
self.extension = extension
|
488 |
+
|
489 |
+
def get_editor(self) -> str:
|
490 |
+
if self.editor is not None:
|
491 |
+
return self.editor
|
492 |
+
for key in "VISUAL", "EDITOR":
|
493 |
+
rv = os.environ.get(key)
|
494 |
+
if rv:
|
495 |
+
return rv
|
496 |
+
if WIN:
|
497 |
+
return "notepad"
|
498 |
+
for editor in "sensible-editor", "vim", "nano":
|
499 |
+
if os.system(f"which {editor} >/dev/null 2>&1") == 0:
|
500 |
+
return editor
|
501 |
+
return "vi"
|
502 |
+
|
503 |
+
def edit_file(self, filename: str) -> None:
|
504 |
+
import subprocess
|
505 |
+
|
506 |
+
editor = self.get_editor()
|
507 |
+
environ: t.Optional[t.Dict[str, str]] = None
|
508 |
+
|
509 |
+
if self.env:
|
510 |
+
environ = os.environ.copy()
|
511 |
+
environ.update(self.env)
|
512 |
+
|
513 |
+
try:
|
514 |
+
c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True)
|
515 |
+
exit_code = c.wait()
|
516 |
+
if exit_code != 0:
|
517 |
+
raise ClickException(
|
518 |
+
_("{editor}: Editing failed").format(editor=editor)
|
519 |
+
)
|
520 |
+
except OSError as e:
|
521 |
+
raise ClickException(
|
522 |
+
_("{editor}: Editing failed: {e}").format(editor=editor, e=e)
|
523 |
+
) from e
|
524 |
+
|
525 |
+
def edit(self, text: t.Optional[t.AnyStr]) -> t.Optional[t.AnyStr]:
|
526 |
+
import tempfile
|
527 |
+
|
528 |
+
if not text:
|
529 |
+
data = b""
|
530 |
+
elif isinstance(text, (bytes, bytearray)):
|
531 |
+
data = text
|
532 |
+
else:
|
533 |
+
if text and not text.endswith("\n"):
|
534 |
+
text += "\n"
|
535 |
+
|
536 |
+
if WIN:
|
537 |
+
data = text.replace("\n", "\r\n").encode("utf-8-sig")
|
538 |
+
else:
|
539 |
+
data = text.encode("utf-8")
|
540 |
+
|
541 |
+
fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)
|
542 |
+
f: t.BinaryIO
|
543 |
+
|
544 |
+
try:
|
545 |
+
with os.fdopen(fd, "wb") as f:
|
546 |
+
f.write(data)
|
547 |
+
|
548 |
+
# If the filesystem resolution is 1 second, like Mac OS
|
549 |
+
# 10.12 Extended, or 2 seconds, like FAT32, and the editor
|
550 |
+
# closes very fast, require_save can fail. Set the modified
|
551 |
+
# time to be 2 seconds in the past to work around this.
|
552 |
+
os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))
|
553 |
+
# Depending on the resolution, the exact value might not be
|
554 |
+
# recorded, so get the new recorded value.
|
555 |
+
timestamp = os.path.getmtime(name)
|
556 |
+
|
557 |
+
self.edit_file(name)
|
558 |
+
|
559 |
+
if self.require_save and os.path.getmtime(name) == timestamp:
|
560 |
+
return None
|
561 |
+
|
562 |
+
with open(name, "rb") as f:
|
563 |
+
rv = f.read()
|
564 |
+
|
565 |
+
if isinstance(text, (bytes, bytearray)):
|
566 |
+
return rv
|
567 |
+
|
568 |
+
return rv.decode("utf-8-sig").replace("\r\n", "\n") # type: ignore
|
569 |
+
finally:
|
570 |
+
os.unlink(name)
|
571 |
+
|
572 |
+
|
573 |
+
def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
|
574 |
+
import subprocess
|
575 |
+
|
576 |
+
def _unquote_file(url: str) -> str:
|
577 |
+
from urllib.parse import unquote
|
578 |
+
|
579 |
+
if url.startswith("file://"):
|
580 |
+
url = unquote(url[7:])
|
581 |
+
|
582 |
+
return url
|
583 |
+
|
584 |
+
if sys.platform == "darwin":
|
585 |
+
args = ["open"]
|
586 |
+
if wait:
|
587 |
+
args.append("-W")
|
588 |
+
if locate:
|
589 |
+
args.append("-R")
|
590 |
+
args.append(_unquote_file(url))
|
591 |
+
null = open("/dev/null", "w")
|
592 |
+
try:
|
593 |
+
return subprocess.Popen(args, stderr=null).wait()
|
594 |
+
finally:
|
595 |
+
null.close()
|
596 |
+
elif WIN:
|
597 |
+
if locate:
|
598 |
+
url = _unquote_file(url.replace('"', ""))
|
599 |
+
args = f'explorer /select,"{url}"'
|
600 |
+
else:
|
601 |
+
url = url.replace('"', "")
|
602 |
+
wait_str = "/WAIT" if wait else ""
|
603 |
+
args = f'start {wait_str} "" "{url}"'
|
604 |
+
return os.system(args)
|
605 |
+
elif CYGWIN:
|
606 |
+
if locate:
|
607 |
+
url = os.path.dirname(_unquote_file(url).replace('"', ""))
|
608 |
+
args = f'cygstart "{url}"'
|
609 |
+
else:
|
610 |
+
url = url.replace('"', "")
|
611 |
+
wait_str = "-w" if wait else ""
|
612 |
+
args = f'cygstart {wait_str} "{url}"'
|
613 |
+
return os.system(args)
|
614 |
+
|
615 |
+
try:
|
616 |
+
if locate:
|
617 |
+
url = os.path.dirname(_unquote_file(url)) or "."
|
618 |
+
else:
|
619 |
+
url = _unquote_file(url)
|
620 |
+
c = subprocess.Popen(["xdg-open", url])
|
621 |
+
if wait:
|
622 |
+
return c.wait()
|
623 |
+
return 0
|
624 |
+
except OSError:
|
625 |
+
if url.startswith(("http://", "https://")) and not locate and not wait:
|
626 |
+
import webbrowser
|
627 |
+
|
628 |
+
webbrowser.open(url)
|
629 |
+
return 0
|
630 |
+
return 1
|
631 |
+
|
632 |
+
|
633 |
+
def _translate_ch_to_exc(ch: str) -> t.Optional[BaseException]:
|
634 |
+
if ch == "\x03":
|
635 |
+
raise KeyboardInterrupt()
|
636 |
+
|
637 |
+
if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
|
638 |
+
raise EOFError()
|
639 |
+
|
640 |
+
if ch == "\x1a" and WIN: # Windows, Ctrl+Z
|
641 |
+
raise EOFError()
|
642 |
+
|
643 |
+
return None
|
644 |
+
|
645 |
+
|
646 |
+
if WIN:
|
647 |
+
import msvcrt
|
648 |
+
|
649 |
+
@contextlib.contextmanager
|
650 |
+
def raw_terminal() -> t.Iterator[int]:
|
651 |
+
yield -1
|
652 |
+
|
653 |
+
def getchar(echo: bool) -> str:
|
654 |
+
# The function `getch` will return a bytes object corresponding to
|
655 |
+
# the pressed character. Since Windows 10 build 1803, it will also
|
656 |
+
# return \x00 when called a second time after pressing a regular key.
|
657 |
+
#
|
658 |
+
# `getwch` does not share this probably-bugged behavior. Moreover, it
|
659 |
+
# returns a Unicode object by default, which is what we want.
|
660 |
+
#
|
661 |
+
# Either of these functions will return \x00 or \xe0 to indicate
|
662 |
+
# a special key, and you need to call the same function again to get
|
663 |
+
# the "rest" of the code. The fun part is that \u00e0 is
|
664 |
+
# "latin small letter a with grave", so if you type that on a French
|
665 |
+
# keyboard, you _also_ get a \xe0.
|
666 |
+
# E.g., consider the Up arrow. This returns \xe0 and then \x48. The
|
667 |
+
# resulting Unicode string reads as "a with grave" + "capital H".
|
668 |
+
# This is indistinguishable from when the user actually types
|
669 |
+
# "a with grave" and then "capital H".
|
670 |
+
#
|
671 |
+
# When \xe0 is returned, we assume it's part of a special-key sequence
|
672 |
+
# and call `getwch` again, but that means that when the user types
|
673 |
+
# the \u00e0 character, `getchar` doesn't return until a second
|
674 |
+
# character is typed.
|
675 |
+
# The alternative is returning immediately, but that would mess up
|
676 |
+
# cross-platform handling of arrow keys and others that start with
|
677 |
+
# \xe0. Another option is using `getch`, but then we can't reliably
|
678 |
+
# read non-ASCII characters, because return values of `getch` are
|
679 |
+
# limited to the current 8-bit codepage.
|
680 |
+
#
|
681 |
+
# Anyway, Click doesn't claim to do this Right(tm), and using `getwch`
|
682 |
+
# is doing the right thing in more situations than with `getch`.
|
683 |
+
func: t.Callable[[], str]
|
684 |
+
|
685 |
+
if echo:
|
686 |
+
func = msvcrt.getwche # type: ignore
|
687 |
+
else:
|
688 |
+
func = msvcrt.getwch # type: ignore
|
689 |
+
|
690 |
+
rv = func()
|
691 |
+
|
692 |
+
if rv in ("\x00", "\xe0"):
|
693 |
+
# \x00 and \xe0 are control characters that indicate special key,
|
694 |
+
# see above.
|
695 |
+
rv += func()
|
696 |
+
|
697 |
+
_translate_ch_to_exc(rv)
|
698 |
+
return rv
|
699 |
+
|
700 |
+
else:
|
701 |
+
import tty
|
702 |
+
import termios
|
703 |
+
|
704 |
+
@contextlib.contextmanager
|
705 |
+
def raw_terminal() -> t.Iterator[int]:
|
706 |
+
f: t.Optional[t.TextIO]
|
707 |
+
fd: int
|
708 |
+
|
709 |
+
if not isatty(sys.stdin):
|
710 |
+
f = open("/dev/tty")
|
711 |
+
fd = f.fileno()
|
712 |
+
else:
|
713 |
+
fd = sys.stdin.fileno()
|
714 |
+
f = None
|
715 |
+
|
716 |
+
try:
|
717 |
+
old_settings = termios.tcgetattr(fd)
|
718 |
+
|
719 |
+
try:
|
720 |
+
tty.setraw(fd)
|
721 |
+
yield fd
|
722 |
+
finally:
|
723 |
+
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
|
724 |
+
sys.stdout.flush()
|
725 |
+
|
726 |
+
if f is not None:
|
727 |
+
f.close()
|
728 |
+
except termios.error:
|
729 |
+
pass
|
730 |
+
|
731 |
+
def getchar(echo: bool) -> str:
|
732 |
+
with raw_terminal() as fd:
|
733 |
+
ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
|
734 |
+
|
735 |
+
if echo and isatty(sys.stdout):
|
736 |
+
sys.stdout.write(ch)
|
737 |
+
|
738 |
+
_translate_ch_to_exc(ch)
|
739 |
+
return ch
|
llmeval-env/lib/python3.10/site-packages/click/_winconsole.py
ADDED
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This module is based on the excellent work by Adam Bartoš who
|
2 |
+
# provided a lot of what went into the implementation here in
|
3 |
+
# the discussion to issue1602 in the Python bug tracker.
|
4 |
+
#
|
5 |
+
# There are some general differences in regards to how this works
|
6 |
+
# compared to the original patches as we do not need to patch
|
7 |
+
# the entire interpreter but just work in our little world of
|
8 |
+
# echo and prompt.
|
9 |
+
import io
|
10 |
+
import sys
|
11 |
+
import time
|
12 |
+
import typing as t
|
13 |
+
from ctypes import byref
|
14 |
+
from ctypes import c_char
|
15 |
+
from ctypes import c_char_p
|
16 |
+
from ctypes import c_int
|
17 |
+
from ctypes import c_ssize_t
|
18 |
+
from ctypes import c_ulong
|
19 |
+
from ctypes import c_void_p
|
20 |
+
from ctypes import POINTER
|
21 |
+
from ctypes import py_object
|
22 |
+
from ctypes import Structure
|
23 |
+
from ctypes.wintypes import DWORD
|
24 |
+
from ctypes.wintypes import HANDLE
|
25 |
+
from ctypes.wintypes import LPCWSTR
|
26 |
+
from ctypes.wintypes import LPWSTR
|
27 |
+
|
28 |
+
from ._compat import _NonClosingTextIOWrapper
|
29 |
+
|
30 |
+
assert sys.platform == "win32"
|
31 |
+
import msvcrt # noqa: E402
|
32 |
+
from ctypes import windll # noqa: E402
|
33 |
+
from ctypes import WINFUNCTYPE # noqa: E402
|
34 |
+
|
35 |
+
c_ssize_p = POINTER(c_ssize_t)
|
36 |
+
|
37 |
+
kernel32 = windll.kernel32
|
38 |
+
GetStdHandle = kernel32.GetStdHandle
|
39 |
+
ReadConsoleW = kernel32.ReadConsoleW
|
40 |
+
WriteConsoleW = kernel32.WriteConsoleW
|
41 |
+
GetConsoleMode = kernel32.GetConsoleMode
|
42 |
+
GetLastError = kernel32.GetLastError
|
43 |
+
GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
|
44 |
+
CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
|
45 |
+
("CommandLineToArgvW", windll.shell32)
|
46 |
+
)
|
47 |
+
LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))
|
48 |
+
|
49 |
+
STDIN_HANDLE = GetStdHandle(-10)
|
50 |
+
STDOUT_HANDLE = GetStdHandle(-11)
|
51 |
+
STDERR_HANDLE = GetStdHandle(-12)
|
52 |
+
|
53 |
+
PyBUF_SIMPLE = 0
|
54 |
+
PyBUF_WRITABLE = 1
|
55 |
+
|
56 |
+
ERROR_SUCCESS = 0
|
57 |
+
ERROR_NOT_ENOUGH_MEMORY = 8
|
58 |
+
ERROR_OPERATION_ABORTED = 995
|
59 |
+
|
60 |
+
STDIN_FILENO = 0
|
61 |
+
STDOUT_FILENO = 1
|
62 |
+
STDERR_FILENO = 2
|
63 |
+
|
64 |
+
EOF = b"\x1a"
|
65 |
+
MAX_BYTES_WRITTEN = 32767
|
66 |
+
|
67 |
+
try:
|
68 |
+
from ctypes import pythonapi
|
69 |
+
except ImportError:
|
70 |
+
# On PyPy we cannot get buffers so our ability to operate here is
|
71 |
+
# severely limited.
|
72 |
+
get_buffer = None
|
73 |
+
else:
|
74 |
+
|
75 |
+
class Py_buffer(Structure):
|
76 |
+
_fields_ = [
|
77 |
+
("buf", c_void_p),
|
78 |
+
("obj", py_object),
|
79 |
+
("len", c_ssize_t),
|
80 |
+
("itemsize", c_ssize_t),
|
81 |
+
("readonly", c_int),
|
82 |
+
("ndim", c_int),
|
83 |
+
("format", c_char_p),
|
84 |
+
("shape", c_ssize_p),
|
85 |
+
("strides", c_ssize_p),
|
86 |
+
("suboffsets", c_ssize_p),
|
87 |
+
("internal", c_void_p),
|
88 |
+
]
|
89 |
+
|
90 |
+
PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
|
91 |
+
PyBuffer_Release = pythonapi.PyBuffer_Release
|
92 |
+
|
93 |
+
def get_buffer(obj, writable=False):
|
94 |
+
buf = Py_buffer()
|
95 |
+
flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE
|
96 |
+
PyObject_GetBuffer(py_object(obj), byref(buf), flags)
|
97 |
+
|
98 |
+
try:
|
99 |
+
buffer_type = c_char * buf.len
|
100 |
+
return buffer_type.from_address(buf.buf)
|
101 |
+
finally:
|
102 |
+
PyBuffer_Release(byref(buf))
|
103 |
+
|
104 |
+
|
105 |
+
class _WindowsConsoleRawIOBase(io.RawIOBase):
|
106 |
+
def __init__(self, handle):
|
107 |
+
self.handle = handle
|
108 |
+
|
109 |
+
def isatty(self):
|
110 |
+
super().isatty()
|
111 |
+
return True
|
112 |
+
|
113 |
+
|
114 |
+
class _WindowsConsoleReader(_WindowsConsoleRawIOBase):
|
115 |
+
def readable(self):
|
116 |
+
return True
|
117 |
+
|
118 |
+
def readinto(self, b):
|
119 |
+
bytes_to_be_read = len(b)
|
120 |
+
if not bytes_to_be_read:
|
121 |
+
return 0
|
122 |
+
elif bytes_to_be_read % 2:
|
123 |
+
raise ValueError(
|
124 |
+
"cannot read odd number of bytes from UTF-16-LE encoded console"
|
125 |
+
)
|
126 |
+
|
127 |
+
buffer = get_buffer(b, writable=True)
|
128 |
+
code_units_to_be_read = bytes_to_be_read // 2
|
129 |
+
code_units_read = c_ulong()
|
130 |
+
|
131 |
+
rv = ReadConsoleW(
|
132 |
+
HANDLE(self.handle),
|
133 |
+
buffer,
|
134 |
+
code_units_to_be_read,
|
135 |
+
byref(code_units_read),
|
136 |
+
None,
|
137 |
+
)
|
138 |
+
if GetLastError() == ERROR_OPERATION_ABORTED:
|
139 |
+
# wait for KeyboardInterrupt
|
140 |
+
time.sleep(0.1)
|
141 |
+
if not rv:
|
142 |
+
raise OSError(f"Windows error: {GetLastError()}")
|
143 |
+
|
144 |
+
if buffer[0] == EOF:
|
145 |
+
return 0
|
146 |
+
return 2 * code_units_read.value
|
147 |
+
|
148 |
+
|
149 |
+
class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):
|
150 |
+
def writable(self):
|
151 |
+
return True
|
152 |
+
|
153 |
+
@staticmethod
|
154 |
+
def _get_error_message(errno):
|
155 |
+
if errno == ERROR_SUCCESS:
|
156 |
+
return "ERROR_SUCCESS"
|
157 |
+
elif errno == ERROR_NOT_ENOUGH_MEMORY:
|
158 |
+
return "ERROR_NOT_ENOUGH_MEMORY"
|
159 |
+
return f"Windows error {errno}"
|
160 |
+
|
161 |
+
def write(self, b):
|
162 |
+
bytes_to_be_written = len(b)
|
163 |
+
buf = get_buffer(b)
|
164 |
+
code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2
|
165 |
+
code_units_written = c_ulong()
|
166 |
+
|
167 |
+
WriteConsoleW(
|
168 |
+
HANDLE(self.handle),
|
169 |
+
buf,
|
170 |
+
code_units_to_be_written,
|
171 |
+
byref(code_units_written),
|
172 |
+
None,
|
173 |
+
)
|
174 |
+
bytes_written = 2 * code_units_written.value
|
175 |
+
|
176 |
+
if bytes_written == 0 and bytes_to_be_written > 0:
|
177 |
+
raise OSError(self._get_error_message(GetLastError()))
|
178 |
+
return bytes_written
|
179 |
+
|
180 |
+
|
181 |
+
class ConsoleStream:
|
182 |
+
def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:
|
183 |
+
self._text_stream = text_stream
|
184 |
+
self.buffer = byte_stream
|
185 |
+
|
186 |
+
@property
|
187 |
+
def name(self) -> str:
|
188 |
+
return self.buffer.name
|
189 |
+
|
190 |
+
def write(self, x: t.AnyStr) -> int:
|
191 |
+
if isinstance(x, str):
|
192 |
+
return self._text_stream.write(x)
|
193 |
+
try:
|
194 |
+
self.flush()
|
195 |
+
except Exception:
|
196 |
+
pass
|
197 |
+
return self.buffer.write(x)
|
198 |
+
|
199 |
+
def writelines(self, lines: t.Iterable[t.AnyStr]) -> None:
|
200 |
+
for line in lines:
|
201 |
+
self.write(line)
|
202 |
+
|
203 |
+
def __getattr__(self, name: str) -> t.Any:
|
204 |
+
return getattr(self._text_stream, name)
|
205 |
+
|
206 |
+
def isatty(self) -> bool:
|
207 |
+
return self.buffer.isatty()
|
208 |
+
|
209 |
+
def __repr__(self):
|
210 |
+
return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"
|
211 |
+
|
212 |
+
|
213 |
+
def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:
|
214 |
+
text_stream = _NonClosingTextIOWrapper(
|
215 |
+
io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
|
216 |
+
"utf-16-le",
|
217 |
+
"strict",
|
218 |
+
line_buffering=True,
|
219 |
+
)
|
220 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
221 |
+
|
222 |
+
|
223 |
+
def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:
|
224 |
+
text_stream = _NonClosingTextIOWrapper(
|
225 |
+
io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
|
226 |
+
"utf-16-le",
|
227 |
+
"strict",
|
228 |
+
line_buffering=True,
|
229 |
+
)
|
230 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
231 |
+
|
232 |
+
|
233 |
+
def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:
|
234 |
+
text_stream = _NonClosingTextIOWrapper(
|
235 |
+
io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
|
236 |
+
"utf-16-le",
|
237 |
+
"strict",
|
238 |
+
line_buffering=True,
|
239 |
+
)
|
240 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
241 |
+
|
242 |
+
|
243 |
+
_stream_factories: t.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {
|
244 |
+
0: _get_text_stdin,
|
245 |
+
1: _get_text_stdout,
|
246 |
+
2: _get_text_stderr,
|
247 |
+
}
|
248 |
+
|
249 |
+
|
250 |
+
def _is_console(f: t.TextIO) -> bool:
|
251 |
+
if not hasattr(f, "fileno"):
|
252 |
+
return False
|
253 |
+
|
254 |
+
try:
|
255 |
+
fileno = f.fileno()
|
256 |
+
except (OSError, io.UnsupportedOperation):
|
257 |
+
return False
|
258 |
+
|
259 |
+
handle = msvcrt.get_osfhandle(fileno)
|
260 |
+
return bool(GetConsoleMode(handle, byref(DWORD())))
|
261 |
+
|
262 |
+
|
263 |
+
def _get_windows_console_stream(
|
264 |
+
f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]
|
265 |
+
) -> t.Optional[t.TextIO]:
|
266 |
+
if (
|
267 |
+
get_buffer is not None
|
268 |
+
and encoding in {"utf-16-le", None}
|
269 |
+
and errors in {"strict", None}
|
270 |
+
and _is_console(f)
|
271 |
+
):
|
272 |
+
func = _stream_factories.get(f.fileno())
|
273 |
+
if func is not None:
|
274 |
+
b = getattr(f, "buffer", None)
|
275 |
+
|
276 |
+
if b is None:
|
277 |
+
return None
|
278 |
+
|
279 |
+
return func(b)
|
llmeval-env/lib/python3.10/site-packages/click/decorators.py
ADDED
@@ -0,0 +1,561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
import types
|
3 |
+
import typing as t
|
4 |
+
from functools import update_wrapper
|
5 |
+
from gettext import gettext as _
|
6 |
+
|
7 |
+
from .core import Argument
|
8 |
+
from .core import Command
|
9 |
+
from .core import Context
|
10 |
+
from .core import Group
|
11 |
+
from .core import Option
|
12 |
+
from .core import Parameter
|
13 |
+
from .globals import get_current_context
|
14 |
+
from .utils import echo
|
15 |
+
|
16 |
+
if t.TYPE_CHECKING:
|
17 |
+
import typing_extensions as te
|
18 |
+
|
19 |
+
P = te.ParamSpec("P")
|
20 |
+
|
21 |
+
R = t.TypeVar("R")
|
22 |
+
T = t.TypeVar("T")
|
23 |
+
_AnyCallable = t.Callable[..., t.Any]
|
24 |
+
FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])
|
25 |
+
|
26 |
+
|
27 |
+
def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":
|
28 |
+
"""Marks a callback as wanting to receive the current context
|
29 |
+
object as first argument.
|
30 |
+
"""
|
31 |
+
|
32 |
+
def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":
|
33 |
+
return f(get_current_context(), *args, **kwargs)
|
34 |
+
|
35 |
+
return update_wrapper(new_func, f)
|
36 |
+
|
37 |
+
|
38 |
+
def pass_obj(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":
|
39 |
+
"""Similar to :func:`pass_context`, but only pass the object on the
|
40 |
+
context onwards (:attr:`Context.obj`). This is useful if that object
|
41 |
+
represents the state of a nested system.
|
42 |
+
"""
|
43 |
+
|
44 |
+
def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":
|
45 |
+
return f(get_current_context().obj, *args, **kwargs)
|
46 |
+
|
47 |
+
return update_wrapper(new_func, f)
|
48 |
+
|
49 |
+
|
50 |
+
def make_pass_decorator(
|
51 |
+
object_type: t.Type[T], ensure: bool = False
|
52 |
+
) -> t.Callable[["t.Callable[te.Concatenate[T, P], R]"], "t.Callable[P, R]"]:
|
53 |
+
"""Given an object type this creates a decorator that will work
|
54 |
+
similar to :func:`pass_obj` but instead of passing the object of the
|
55 |
+
current context, it will find the innermost context of type
|
56 |
+
:func:`object_type`.
|
57 |
+
|
58 |
+
This generates a decorator that works roughly like this::
|
59 |
+
|
60 |
+
from functools import update_wrapper
|
61 |
+
|
62 |
+
def decorator(f):
|
63 |
+
@pass_context
|
64 |
+
def new_func(ctx, *args, **kwargs):
|
65 |
+
obj = ctx.find_object(object_type)
|
66 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
67 |
+
return update_wrapper(new_func, f)
|
68 |
+
return decorator
|
69 |
+
|
70 |
+
:param object_type: the type of the object to pass.
|
71 |
+
:param ensure: if set to `True`, a new object will be created and
|
72 |
+
remembered on the context if it's not there yet.
|
73 |
+
"""
|
74 |
+
|
75 |
+
def decorator(f: "t.Callable[te.Concatenate[T, P], R]") -> "t.Callable[P, R]":
|
76 |
+
def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":
|
77 |
+
ctx = get_current_context()
|
78 |
+
|
79 |
+
obj: t.Optional[T]
|
80 |
+
if ensure:
|
81 |
+
obj = ctx.ensure_object(object_type)
|
82 |
+
else:
|
83 |
+
obj = ctx.find_object(object_type)
|
84 |
+
|
85 |
+
if obj is None:
|
86 |
+
raise RuntimeError(
|
87 |
+
"Managed to invoke callback without a context"
|
88 |
+
f" object of type {object_type.__name__!r}"
|
89 |
+
" existing."
|
90 |
+
)
|
91 |
+
|
92 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
93 |
+
|
94 |
+
return update_wrapper(new_func, f)
|
95 |
+
|
96 |
+
return decorator # type: ignore[return-value]
|
97 |
+
|
98 |
+
|
99 |
+
def pass_meta_key(
|
100 |
+
key: str, *, doc_description: t.Optional[str] = None
|
101 |
+
) -> "t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]":
|
102 |
+
"""Create a decorator that passes a key from
|
103 |
+
:attr:`click.Context.meta` as the first argument to the decorated
|
104 |
+
function.
|
105 |
+
|
106 |
+
:param key: Key in ``Context.meta`` to pass.
|
107 |
+
:param doc_description: Description of the object being passed,
|
108 |
+
inserted into the decorator's docstring. Defaults to "the 'key'
|
109 |
+
key from Context.meta".
|
110 |
+
|
111 |
+
.. versionadded:: 8.0
|
112 |
+
"""
|
113 |
+
|
114 |
+
def decorator(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":
|
115 |
+
def new_func(*args: "P.args", **kwargs: "P.kwargs") -> R:
|
116 |
+
ctx = get_current_context()
|
117 |
+
obj = ctx.meta[key]
|
118 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
119 |
+
|
120 |
+
return update_wrapper(new_func, f)
|
121 |
+
|
122 |
+
if doc_description is None:
|
123 |
+
doc_description = f"the {key!r} key from :attr:`click.Context.meta`"
|
124 |
+
|
125 |
+
decorator.__doc__ = (
|
126 |
+
f"Decorator that passes {doc_description} as the first argument"
|
127 |
+
" to the decorated function."
|
128 |
+
)
|
129 |
+
return decorator # type: ignore[return-value]
|
130 |
+
|
131 |
+
|
132 |
+
CmdType = t.TypeVar("CmdType", bound=Command)
|
133 |
+
|
134 |
+
|
135 |
+
# variant: no call, directly as decorator for a function.
|
136 |
+
@t.overload
|
137 |
+
def command(name: _AnyCallable) -> Command:
|
138 |
+
...
|
139 |
+
|
140 |
+
|
141 |
+
# variant: with positional name and with positional or keyword cls argument:
|
142 |
+
# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)
|
143 |
+
@t.overload
|
144 |
+
def command(
|
145 |
+
name: t.Optional[str],
|
146 |
+
cls: t.Type[CmdType],
|
147 |
+
**attrs: t.Any,
|
148 |
+
) -> t.Callable[[_AnyCallable], CmdType]:
|
149 |
+
...
|
150 |
+
|
151 |
+
|
152 |
+
# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)
|
153 |
+
@t.overload
|
154 |
+
def command(
|
155 |
+
name: None = None,
|
156 |
+
*,
|
157 |
+
cls: t.Type[CmdType],
|
158 |
+
**attrs: t.Any,
|
159 |
+
) -> t.Callable[[_AnyCallable], CmdType]:
|
160 |
+
...
|
161 |
+
|
162 |
+
|
163 |
+
# variant: with optional string name, no cls argument provided.
|
164 |
+
@t.overload
|
165 |
+
def command(
|
166 |
+
name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any
|
167 |
+
) -> t.Callable[[_AnyCallable], Command]:
|
168 |
+
...
|
169 |
+
|
170 |
+
|
171 |
+
def command(
|
172 |
+
name: t.Union[t.Optional[str], _AnyCallable] = None,
|
173 |
+
cls: t.Optional[t.Type[CmdType]] = None,
|
174 |
+
**attrs: t.Any,
|
175 |
+
) -> t.Union[Command, t.Callable[[_AnyCallable], t.Union[Command, CmdType]]]:
|
176 |
+
r"""Creates a new :class:`Command` and uses the decorated function as
|
177 |
+
callback. This will also automatically attach all decorated
|
178 |
+
:func:`option`\s and :func:`argument`\s as parameters to the command.
|
179 |
+
|
180 |
+
The name of the command defaults to the name of the function with
|
181 |
+
underscores replaced by dashes. If you want to change that, you can
|
182 |
+
pass the intended name as the first argument.
|
183 |
+
|
184 |
+
All keyword arguments are forwarded to the underlying command class.
|
185 |
+
For the ``params`` argument, any decorated params are appended to
|
186 |
+
the end of the list.
|
187 |
+
|
188 |
+
Once decorated the function turns into a :class:`Command` instance
|
189 |
+
that can be invoked as a command line utility or be attached to a
|
190 |
+
command :class:`Group`.
|
191 |
+
|
192 |
+
:param name: the name of the command. This defaults to the function
|
193 |
+
name with underscores replaced by dashes.
|
194 |
+
:param cls: the command class to instantiate. This defaults to
|
195 |
+
:class:`Command`.
|
196 |
+
|
197 |
+
.. versionchanged:: 8.1
|
198 |
+
This decorator can be applied without parentheses.
|
199 |
+
|
200 |
+
.. versionchanged:: 8.1
|
201 |
+
The ``params`` argument can be used. Decorated params are
|
202 |
+
appended to the end of the list.
|
203 |
+
"""
|
204 |
+
|
205 |
+
func: t.Optional[t.Callable[[_AnyCallable], t.Any]] = None
|
206 |
+
|
207 |
+
if callable(name):
|
208 |
+
func = name
|
209 |
+
name = None
|
210 |
+
assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
|
211 |
+
assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
|
212 |
+
|
213 |
+
if cls is None:
|
214 |
+
cls = t.cast(t.Type[CmdType], Command)
|
215 |
+
|
216 |
+
def decorator(f: _AnyCallable) -> CmdType:
|
217 |
+
if isinstance(f, Command):
|
218 |
+
raise TypeError("Attempted to convert a callback into a command twice.")
|
219 |
+
|
220 |
+
attr_params = attrs.pop("params", None)
|
221 |
+
params = attr_params if attr_params is not None else []
|
222 |
+
|
223 |
+
try:
|
224 |
+
decorator_params = f.__click_params__ # type: ignore
|
225 |
+
except AttributeError:
|
226 |
+
pass
|
227 |
+
else:
|
228 |
+
del f.__click_params__ # type: ignore
|
229 |
+
params.extend(reversed(decorator_params))
|
230 |
+
|
231 |
+
if attrs.get("help") is None:
|
232 |
+
attrs["help"] = f.__doc__
|
233 |
+
|
234 |
+
if t.TYPE_CHECKING:
|
235 |
+
assert cls is not None
|
236 |
+
assert not callable(name)
|
237 |
+
|
238 |
+
cmd = cls(
|
239 |
+
name=name or f.__name__.lower().replace("_", "-"),
|
240 |
+
callback=f,
|
241 |
+
params=params,
|
242 |
+
**attrs,
|
243 |
+
)
|
244 |
+
cmd.__doc__ = f.__doc__
|
245 |
+
return cmd
|
246 |
+
|
247 |
+
if func is not None:
|
248 |
+
return decorator(func)
|
249 |
+
|
250 |
+
return decorator
|
251 |
+
|
252 |
+
|
253 |
+
GrpType = t.TypeVar("GrpType", bound=Group)
|
254 |
+
|
255 |
+
|
256 |
+
# variant: no call, directly as decorator for a function.
|
257 |
+
@t.overload
|
258 |
+
def group(name: _AnyCallable) -> Group:
|
259 |
+
...
|
260 |
+
|
261 |
+
|
262 |
+
# variant: with positional name and with positional or keyword cls argument:
|
263 |
+
# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)
|
264 |
+
@t.overload
|
265 |
+
def group(
|
266 |
+
name: t.Optional[str],
|
267 |
+
cls: t.Type[GrpType],
|
268 |
+
**attrs: t.Any,
|
269 |
+
) -> t.Callable[[_AnyCallable], GrpType]:
|
270 |
+
...
|
271 |
+
|
272 |
+
|
273 |
+
# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)
|
274 |
+
@t.overload
|
275 |
+
def group(
|
276 |
+
name: None = None,
|
277 |
+
*,
|
278 |
+
cls: t.Type[GrpType],
|
279 |
+
**attrs: t.Any,
|
280 |
+
) -> t.Callable[[_AnyCallable], GrpType]:
|
281 |
+
...
|
282 |
+
|
283 |
+
|
284 |
+
# variant: with optional string name, no cls argument provided.
|
285 |
+
@t.overload
|
286 |
+
def group(
|
287 |
+
name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any
|
288 |
+
) -> t.Callable[[_AnyCallable], Group]:
|
289 |
+
...
|
290 |
+
|
291 |
+
|
292 |
+
def group(
|
293 |
+
name: t.Union[str, _AnyCallable, None] = None,
|
294 |
+
cls: t.Optional[t.Type[GrpType]] = None,
|
295 |
+
**attrs: t.Any,
|
296 |
+
) -> t.Union[Group, t.Callable[[_AnyCallable], t.Union[Group, GrpType]]]:
|
297 |
+
"""Creates a new :class:`Group` with a function as callback. This
|
298 |
+
works otherwise the same as :func:`command` just that the `cls`
|
299 |
+
parameter is set to :class:`Group`.
|
300 |
+
|
301 |
+
.. versionchanged:: 8.1
|
302 |
+
This decorator can be applied without parentheses.
|
303 |
+
"""
|
304 |
+
if cls is None:
|
305 |
+
cls = t.cast(t.Type[GrpType], Group)
|
306 |
+
|
307 |
+
if callable(name):
|
308 |
+
return command(cls=cls, **attrs)(name)
|
309 |
+
|
310 |
+
return command(name, cls, **attrs)
|
311 |
+
|
312 |
+
|
313 |
+
def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None:
|
314 |
+
if isinstance(f, Command):
|
315 |
+
f.params.append(param)
|
316 |
+
else:
|
317 |
+
if not hasattr(f, "__click_params__"):
|
318 |
+
f.__click_params__ = [] # type: ignore
|
319 |
+
|
320 |
+
f.__click_params__.append(param) # type: ignore
|
321 |
+
|
322 |
+
|
323 |
+
def argument(
|
324 |
+
*param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any
|
325 |
+
) -> t.Callable[[FC], FC]:
|
326 |
+
"""Attaches an argument to the command. All positional arguments are
|
327 |
+
passed as parameter declarations to :class:`Argument`; all keyword
|
328 |
+
arguments are forwarded unchanged (except ``cls``).
|
329 |
+
This is equivalent to creating an :class:`Argument` instance manually
|
330 |
+
and attaching it to the :attr:`Command.params` list.
|
331 |
+
|
332 |
+
For the default argument class, refer to :class:`Argument` and
|
333 |
+
:class:`Parameter` for descriptions of parameters.
|
334 |
+
|
335 |
+
:param cls: the argument class to instantiate. This defaults to
|
336 |
+
:class:`Argument`.
|
337 |
+
:param param_decls: Passed as positional arguments to the constructor of
|
338 |
+
``cls``.
|
339 |
+
:param attrs: Passed as keyword arguments to the constructor of ``cls``.
|
340 |
+
"""
|
341 |
+
if cls is None:
|
342 |
+
cls = Argument
|
343 |
+
|
344 |
+
def decorator(f: FC) -> FC:
|
345 |
+
_param_memo(f, cls(param_decls, **attrs))
|
346 |
+
return f
|
347 |
+
|
348 |
+
return decorator
|
349 |
+
|
350 |
+
|
351 |
+
def option(
|
352 |
+
*param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any
|
353 |
+
) -> t.Callable[[FC], FC]:
|
354 |
+
"""Attaches an option to the command. All positional arguments are
|
355 |
+
passed as parameter declarations to :class:`Option`; all keyword
|
356 |
+
arguments are forwarded unchanged (except ``cls``).
|
357 |
+
This is equivalent to creating an :class:`Option` instance manually
|
358 |
+
and attaching it to the :attr:`Command.params` list.
|
359 |
+
|
360 |
+
For the default option class, refer to :class:`Option` and
|
361 |
+
:class:`Parameter` for descriptions of parameters.
|
362 |
+
|
363 |
+
:param cls: the option class to instantiate. This defaults to
|
364 |
+
:class:`Option`.
|
365 |
+
:param param_decls: Passed as positional arguments to the constructor of
|
366 |
+
``cls``.
|
367 |
+
:param attrs: Passed as keyword arguments to the constructor of ``cls``.
|
368 |
+
"""
|
369 |
+
if cls is None:
|
370 |
+
cls = Option
|
371 |
+
|
372 |
+
def decorator(f: FC) -> FC:
|
373 |
+
_param_memo(f, cls(param_decls, **attrs))
|
374 |
+
return f
|
375 |
+
|
376 |
+
return decorator
|
377 |
+
|
378 |
+
|
379 |
+
def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
380 |
+
"""Add a ``--yes`` option which shows a prompt before continuing if
|
381 |
+
not passed. If the prompt is declined, the program will exit.
|
382 |
+
|
383 |
+
:param param_decls: One or more option names. Defaults to the single
|
384 |
+
value ``"--yes"``.
|
385 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
386 |
+
"""
|
387 |
+
|
388 |
+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
|
389 |
+
if not value:
|
390 |
+
ctx.abort()
|
391 |
+
|
392 |
+
if not param_decls:
|
393 |
+
param_decls = ("--yes",)
|
394 |
+
|
395 |
+
kwargs.setdefault("is_flag", True)
|
396 |
+
kwargs.setdefault("callback", callback)
|
397 |
+
kwargs.setdefault("expose_value", False)
|
398 |
+
kwargs.setdefault("prompt", "Do you want to continue?")
|
399 |
+
kwargs.setdefault("help", "Confirm the action without prompting.")
|
400 |
+
return option(*param_decls, **kwargs)
|
401 |
+
|
402 |
+
|
403 |
+
def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
404 |
+
"""Add a ``--password`` option which prompts for a password, hiding
|
405 |
+
input and asking to enter the value again for confirmation.
|
406 |
+
|
407 |
+
:param param_decls: One or more option names. Defaults to the single
|
408 |
+
value ``"--password"``.
|
409 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
410 |
+
"""
|
411 |
+
if not param_decls:
|
412 |
+
param_decls = ("--password",)
|
413 |
+
|
414 |
+
kwargs.setdefault("prompt", True)
|
415 |
+
kwargs.setdefault("confirmation_prompt", True)
|
416 |
+
kwargs.setdefault("hide_input", True)
|
417 |
+
return option(*param_decls, **kwargs)
|
418 |
+
|
419 |
+
|
420 |
+
def version_option(
|
421 |
+
version: t.Optional[str] = None,
|
422 |
+
*param_decls: str,
|
423 |
+
package_name: t.Optional[str] = None,
|
424 |
+
prog_name: t.Optional[str] = None,
|
425 |
+
message: t.Optional[str] = None,
|
426 |
+
**kwargs: t.Any,
|
427 |
+
) -> t.Callable[[FC], FC]:
|
428 |
+
"""Add a ``--version`` option which immediately prints the version
|
429 |
+
number and exits the program.
|
430 |
+
|
431 |
+
If ``version`` is not provided, Click will try to detect it using
|
432 |
+
:func:`importlib.metadata.version` to get the version for the
|
433 |
+
``package_name``. On Python < 3.8, the ``importlib_metadata``
|
434 |
+
backport must be installed.
|
435 |
+
|
436 |
+
If ``package_name`` is not provided, Click will try to detect it by
|
437 |
+
inspecting the stack frames. This will be used to detect the
|
438 |
+
version, so it must match the name of the installed package.
|
439 |
+
|
440 |
+
:param version: The version number to show. If not provided, Click
|
441 |
+
will try to detect it.
|
442 |
+
:param param_decls: One or more option names. Defaults to the single
|
443 |
+
value ``"--version"``.
|
444 |
+
:param package_name: The package name to detect the version from. If
|
445 |
+
not provided, Click will try to detect it.
|
446 |
+
:param prog_name: The name of the CLI to show in the message. If not
|
447 |
+
provided, it will be detected from the command.
|
448 |
+
:param message: The message to show. The values ``%(prog)s``,
|
449 |
+
``%(package)s``, and ``%(version)s`` are available. Defaults to
|
450 |
+
``"%(prog)s, version %(version)s"``.
|
451 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
452 |
+
:raise RuntimeError: ``version`` could not be detected.
|
453 |
+
|
454 |
+
.. versionchanged:: 8.0
|
455 |
+
Add the ``package_name`` parameter, and the ``%(package)s``
|
456 |
+
value for messages.
|
457 |
+
|
458 |
+
.. versionchanged:: 8.0
|
459 |
+
Use :mod:`importlib.metadata` instead of ``pkg_resources``. The
|
460 |
+
version is detected based on the package name, not the entry
|
461 |
+
point name. The Python package name must match the installed
|
462 |
+
package name, or be passed with ``package_name=``.
|
463 |
+
"""
|
464 |
+
if message is None:
|
465 |
+
message = _("%(prog)s, version %(version)s")
|
466 |
+
|
467 |
+
if version is None and package_name is None:
|
468 |
+
frame = inspect.currentframe()
|
469 |
+
f_back = frame.f_back if frame is not None else None
|
470 |
+
f_globals = f_back.f_globals if f_back is not None else None
|
471 |
+
# break reference cycle
|
472 |
+
# https://docs.python.org/3/library/inspect.html#the-interpreter-stack
|
473 |
+
del frame
|
474 |
+
|
475 |
+
if f_globals is not None:
|
476 |
+
package_name = f_globals.get("__name__")
|
477 |
+
|
478 |
+
if package_name == "__main__":
|
479 |
+
package_name = f_globals.get("__package__")
|
480 |
+
|
481 |
+
if package_name:
|
482 |
+
package_name = package_name.partition(".")[0]
|
483 |
+
|
484 |
+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
|
485 |
+
if not value or ctx.resilient_parsing:
|
486 |
+
return
|
487 |
+
|
488 |
+
nonlocal prog_name
|
489 |
+
nonlocal version
|
490 |
+
|
491 |
+
if prog_name is None:
|
492 |
+
prog_name = ctx.find_root().info_name
|
493 |
+
|
494 |
+
if version is None and package_name is not None:
|
495 |
+
metadata: t.Optional[types.ModuleType]
|
496 |
+
|
497 |
+
try:
|
498 |
+
from importlib import metadata # type: ignore
|
499 |
+
except ImportError:
|
500 |
+
# Python < 3.8
|
501 |
+
import importlib_metadata as metadata # type: ignore
|
502 |
+
|
503 |
+
try:
|
504 |
+
version = metadata.version(package_name) # type: ignore
|
505 |
+
except metadata.PackageNotFoundError: # type: ignore
|
506 |
+
raise RuntimeError(
|
507 |
+
f"{package_name!r} is not installed. Try passing"
|
508 |
+
" 'package_name' instead."
|
509 |
+
) from None
|
510 |
+
|
511 |
+
if version is None:
|
512 |
+
raise RuntimeError(
|
513 |
+
f"Could not determine the version for {package_name!r} automatically."
|
514 |
+
)
|
515 |
+
|
516 |
+
echo(
|
517 |
+
message % {"prog": prog_name, "package": package_name, "version": version},
|
518 |
+
color=ctx.color,
|
519 |
+
)
|
520 |
+
ctx.exit()
|
521 |
+
|
522 |
+
if not param_decls:
|
523 |
+
param_decls = ("--version",)
|
524 |
+
|
525 |
+
kwargs.setdefault("is_flag", True)
|
526 |
+
kwargs.setdefault("expose_value", False)
|
527 |
+
kwargs.setdefault("is_eager", True)
|
528 |
+
kwargs.setdefault("help", _("Show the version and exit."))
|
529 |
+
kwargs["callback"] = callback
|
530 |
+
return option(*param_decls, **kwargs)
|
531 |
+
|
532 |
+
|
533 |
+
def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
534 |
+
"""Add a ``--help`` option which immediately prints the help page
|
535 |
+
and exits the program.
|
536 |
+
|
537 |
+
This is usually unnecessary, as the ``--help`` option is added to
|
538 |
+
each command automatically unless ``add_help_option=False`` is
|
539 |
+
passed.
|
540 |
+
|
541 |
+
:param param_decls: One or more option names. Defaults to the single
|
542 |
+
value ``"--help"``.
|
543 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
544 |
+
"""
|
545 |
+
|
546 |
+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
|
547 |
+
if not value or ctx.resilient_parsing:
|
548 |
+
return
|
549 |
+
|
550 |
+
echo(ctx.get_help(), color=ctx.color)
|
551 |
+
ctx.exit()
|
552 |
+
|
553 |
+
if not param_decls:
|
554 |
+
param_decls = ("--help",)
|
555 |
+
|
556 |
+
kwargs.setdefault("is_flag", True)
|
557 |
+
kwargs.setdefault("expose_value", False)
|
558 |
+
kwargs.setdefault("is_eager", True)
|
559 |
+
kwargs.setdefault("help", _("Show this message and exit."))
|
560 |
+
kwargs["callback"] = callback
|
561 |
+
return option(*param_decls, **kwargs)
|
llmeval-env/lib/python3.10/site-packages/click/exceptions.py
ADDED
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
from gettext import gettext as _
|
3 |
+
from gettext import ngettext
|
4 |
+
|
5 |
+
from ._compat import get_text_stderr
|
6 |
+
from .utils import echo
|
7 |
+
from .utils import format_filename
|
8 |
+
|
9 |
+
if t.TYPE_CHECKING:
|
10 |
+
from .core import Command
|
11 |
+
from .core import Context
|
12 |
+
from .core import Parameter
|
13 |
+
|
14 |
+
|
15 |
+
def _join_param_hints(
|
16 |
+
param_hint: t.Optional[t.Union[t.Sequence[str], str]]
|
17 |
+
) -> t.Optional[str]:
|
18 |
+
if param_hint is not None and not isinstance(param_hint, str):
|
19 |
+
return " / ".join(repr(x) for x in param_hint)
|
20 |
+
|
21 |
+
return param_hint
|
22 |
+
|
23 |
+
|
24 |
+
class ClickException(Exception):
|
25 |
+
"""An exception that Click can handle and show to the user."""
|
26 |
+
|
27 |
+
#: The exit code for this exception.
|
28 |
+
exit_code = 1
|
29 |
+
|
30 |
+
def __init__(self, message: str) -> None:
|
31 |
+
super().__init__(message)
|
32 |
+
self.message = message
|
33 |
+
|
34 |
+
def format_message(self) -> str:
|
35 |
+
return self.message
|
36 |
+
|
37 |
+
def __str__(self) -> str:
|
38 |
+
return self.message
|
39 |
+
|
40 |
+
def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:
|
41 |
+
if file is None:
|
42 |
+
file = get_text_stderr()
|
43 |
+
|
44 |
+
echo(_("Error: {message}").format(message=self.format_message()), file=file)
|
45 |
+
|
46 |
+
|
47 |
+
class UsageError(ClickException):
|
48 |
+
"""An internal exception that signals a usage error. This typically
|
49 |
+
aborts any further handling.
|
50 |
+
|
51 |
+
:param message: the error message to display.
|
52 |
+
:param ctx: optionally the context that caused this error. Click will
|
53 |
+
fill in the context automatically in some situations.
|
54 |
+
"""
|
55 |
+
|
56 |
+
exit_code = 2
|
57 |
+
|
58 |
+
def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:
|
59 |
+
super().__init__(message)
|
60 |
+
self.ctx = ctx
|
61 |
+
self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None
|
62 |
+
|
63 |
+
def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:
|
64 |
+
if file is None:
|
65 |
+
file = get_text_stderr()
|
66 |
+
color = None
|
67 |
+
hint = ""
|
68 |
+
if (
|
69 |
+
self.ctx is not None
|
70 |
+
and self.ctx.command.get_help_option(self.ctx) is not None
|
71 |
+
):
|
72 |
+
hint = _("Try '{command} {option}' for help.").format(
|
73 |
+
command=self.ctx.command_path, option=self.ctx.help_option_names[0]
|
74 |
+
)
|
75 |
+
hint = f"{hint}\n"
|
76 |
+
if self.ctx is not None:
|
77 |
+
color = self.ctx.color
|
78 |
+
echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)
|
79 |
+
echo(
|
80 |
+
_("Error: {message}").format(message=self.format_message()),
|
81 |
+
file=file,
|
82 |
+
color=color,
|
83 |
+
)
|
84 |
+
|
85 |
+
|
86 |
+
class BadParameter(UsageError):
|
87 |
+
"""An exception that formats out a standardized error message for a
|
88 |
+
bad parameter. This is useful when thrown from a callback or type as
|
89 |
+
Click will attach contextual information to it (for instance, which
|
90 |
+
parameter it is).
|
91 |
+
|
92 |
+
.. versionadded:: 2.0
|
93 |
+
|
94 |
+
:param param: the parameter object that caused this error. This can
|
95 |
+
be left out, and Click will attach this info itself
|
96 |
+
if possible.
|
97 |
+
:param param_hint: a string that shows up as parameter name. This
|
98 |
+
can be used as alternative to `param` in cases
|
99 |
+
where custom validation should happen. If it is
|
100 |
+
a string it's used as such, if it's a list then
|
101 |
+
each item is quoted and separated.
|
102 |
+
"""
|
103 |
+
|
104 |
+
def __init__(
|
105 |
+
self,
|
106 |
+
message: str,
|
107 |
+
ctx: t.Optional["Context"] = None,
|
108 |
+
param: t.Optional["Parameter"] = None,
|
109 |
+
param_hint: t.Optional[str] = None,
|
110 |
+
) -> None:
|
111 |
+
super().__init__(message, ctx)
|
112 |
+
self.param = param
|
113 |
+
self.param_hint = param_hint
|
114 |
+
|
115 |
+
def format_message(self) -> str:
|
116 |
+
if self.param_hint is not None:
|
117 |
+
param_hint = self.param_hint
|
118 |
+
elif self.param is not None:
|
119 |
+
param_hint = self.param.get_error_hint(self.ctx) # type: ignore
|
120 |
+
else:
|
121 |
+
return _("Invalid value: {message}").format(message=self.message)
|
122 |
+
|
123 |
+
return _("Invalid value for {param_hint}: {message}").format(
|
124 |
+
param_hint=_join_param_hints(param_hint), message=self.message
|
125 |
+
)
|
126 |
+
|
127 |
+
|
128 |
+
class MissingParameter(BadParameter):
|
129 |
+
"""Raised if click required an option or argument but it was not
|
130 |
+
provided when invoking the script.
|
131 |
+
|
132 |
+
.. versionadded:: 4.0
|
133 |
+
|
134 |
+
:param param_type: a string that indicates the type of the parameter.
|
135 |
+
The default is to inherit the parameter type from
|
136 |
+
the given `param`. Valid values are ``'parameter'``,
|
137 |
+
``'option'`` or ``'argument'``.
|
138 |
+
"""
|
139 |
+
|
140 |
+
def __init__(
|
141 |
+
self,
|
142 |
+
message: t.Optional[str] = None,
|
143 |
+
ctx: t.Optional["Context"] = None,
|
144 |
+
param: t.Optional["Parameter"] = None,
|
145 |
+
param_hint: t.Optional[str] = None,
|
146 |
+
param_type: t.Optional[str] = None,
|
147 |
+
) -> None:
|
148 |
+
super().__init__(message or "", ctx, param, param_hint)
|
149 |
+
self.param_type = param_type
|
150 |
+
|
151 |
+
def format_message(self) -> str:
|
152 |
+
if self.param_hint is not None:
|
153 |
+
param_hint: t.Optional[str] = self.param_hint
|
154 |
+
elif self.param is not None:
|
155 |
+
param_hint = self.param.get_error_hint(self.ctx) # type: ignore
|
156 |
+
else:
|
157 |
+
param_hint = None
|
158 |
+
|
159 |
+
param_hint = _join_param_hints(param_hint)
|
160 |
+
param_hint = f" {param_hint}" if param_hint else ""
|
161 |
+
|
162 |
+
param_type = self.param_type
|
163 |
+
if param_type is None and self.param is not None:
|
164 |
+
param_type = self.param.param_type_name
|
165 |
+
|
166 |
+
msg = self.message
|
167 |
+
if self.param is not None:
|
168 |
+
msg_extra = self.param.type.get_missing_message(self.param)
|
169 |
+
if msg_extra:
|
170 |
+
if msg:
|
171 |
+
msg += f". {msg_extra}"
|
172 |
+
else:
|
173 |
+
msg = msg_extra
|
174 |
+
|
175 |
+
msg = f" {msg}" if msg else ""
|
176 |
+
|
177 |
+
# Translate param_type for known types.
|
178 |
+
if param_type == "argument":
|
179 |
+
missing = _("Missing argument")
|
180 |
+
elif param_type == "option":
|
181 |
+
missing = _("Missing option")
|
182 |
+
elif param_type == "parameter":
|
183 |
+
missing = _("Missing parameter")
|
184 |
+
else:
|
185 |
+
missing = _("Missing {param_type}").format(param_type=param_type)
|
186 |
+
|
187 |
+
return f"{missing}{param_hint}.{msg}"
|
188 |
+
|
189 |
+
def __str__(self) -> str:
|
190 |
+
if not self.message:
|
191 |
+
param_name = self.param.name if self.param else None
|
192 |
+
return _("Missing parameter: {param_name}").format(param_name=param_name)
|
193 |
+
else:
|
194 |
+
return self.message
|
195 |
+
|
196 |
+
|
197 |
+
class NoSuchOption(UsageError):
|
198 |
+
"""Raised if click attempted to handle an option that does not
|
199 |
+
exist.
|
200 |
+
|
201 |
+
.. versionadded:: 4.0
|
202 |
+
"""
|
203 |
+
|
204 |
+
def __init__(
|
205 |
+
self,
|
206 |
+
option_name: str,
|
207 |
+
message: t.Optional[str] = None,
|
208 |
+
possibilities: t.Optional[t.Sequence[str]] = None,
|
209 |
+
ctx: t.Optional["Context"] = None,
|
210 |
+
) -> None:
|
211 |
+
if message is None:
|
212 |
+
message = _("No such option: {name}").format(name=option_name)
|
213 |
+
|
214 |
+
super().__init__(message, ctx)
|
215 |
+
self.option_name = option_name
|
216 |
+
self.possibilities = possibilities
|
217 |
+
|
218 |
+
def format_message(self) -> str:
|
219 |
+
if not self.possibilities:
|
220 |
+
return self.message
|
221 |
+
|
222 |
+
possibility_str = ", ".join(sorted(self.possibilities))
|
223 |
+
suggest = ngettext(
|
224 |
+
"Did you mean {possibility}?",
|
225 |
+
"(Possible options: {possibilities})",
|
226 |
+
len(self.possibilities),
|
227 |
+
).format(possibility=possibility_str, possibilities=possibility_str)
|
228 |
+
return f"{self.message} {suggest}"
|
229 |
+
|
230 |
+
|
231 |
+
class BadOptionUsage(UsageError):
|
232 |
+
"""Raised if an option is generally supplied but the use of the option
|
233 |
+
was incorrect. This is for instance raised if the number of arguments
|
234 |
+
for an option is not correct.
|
235 |
+
|
236 |
+
.. versionadded:: 4.0
|
237 |
+
|
238 |
+
:param option_name: the name of the option being used incorrectly.
|
239 |
+
"""
|
240 |
+
|
241 |
+
def __init__(
|
242 |
+
self, option_name: str, message: str, ctx: t.Optional["Context"] = None
|
243 |
+
) -> None:
|
244 |
+
super().__init__(message, ctx)
|
245 |
+
self.option_name = option_name
|
246 |
+
|
247 |
+
|
248 |
+
class BadArgumentUsage(UsageError):
|
249 |
+
"""Raised if an argument is generally supplied but the use of the argument
|
250 |
+
was incorrect. This is for instance raised if the number of values
|
251 |
+
for an argument is not correct.
|
252 |
+
|
253 |
+
.. versionadded:: 6.0
|
254 |
+
"""
|
255 |
+
|
256 |
+
|
257 |
+
class FileError(ClickException):
|
258 |
+
"""Raised if a file cannot be opened."""
|
259 |
+
|
260 |
+
def __init__(self, filename: str, hint: t.Optional[str] = None) -> None:
|
261 |
+
if hint is None:
|
262 |
+
hint = _("unknown error")
|
263 |
+
|
264 |
+
super().__init__(hint)
|
265 |
+
self.ui_filename: str = format_filename(filename)
|
266 |
+
self.filename = filename
|
267 |
+
|
268 |
+
def format_message(self) -> str:
|
269 |
+
return _("Could not open file {filename!r}: {message}").format(
|
270 |
+
filename=self.ui_filename, message=self.message
|
271 |
+
)
|
272 |
+
|
273 |
+
|
274 |
+
class Abort(RuntimeError):
|
275 |
+
"""An internal signalling exception that signals Click to abort."""
|
276 |
+
|
277 |
+
|
278 |
+
class Exit(RuntimeError):
|
279 |
+
"""An exception that indicates that the application should exit with some
|
280 |
+
status code.
|
281 |
+
|
282 |
+
:param code: the status code to exit with.
|
283 |
+
"""
|
284 |
+
|
285 |
+
__slots__ = ("exit_code",)
|
286 |
+
|
287 |
+
def __init__(self, code: int = 0) -> None:
|
288 |
+
self.exit_code: int = code
|
llmeval-env/lib/python3.10/site-packages/click/formatting.py
ADDED
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
from contextlib import contextmanager
|
3 |
+
from gettext import gettext as _
|
4 |
+
|
5 |
+
from ._compat import term_len
|
6 |
+
from .parser import split_opt
|
7 |
+
|
8 |
+
# Can force a width. This is used by the test system
|
9 |
+
FORCED_WIDTH: t.Optional[int] = None
|
10 |
+
|
11 |
+
|
12 |
+
def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]:
|
13 |
+
widths: t.Dict[int, int] = {}
|
14 |
+
|
15 |
+
for row in rows:
|
16 |
+
for idx, col in enumerate(row):
|
17 |
+
widths[idx] = max(widths.get(idx, 0), term_len(col))
|
18 |
+
|
19 |
+
return tuple(y for x, y in sorted(widths.items()))
|
20 |
+
|
21 |
+
|
22 |
+
def iter_rows(
|
23 |
+
rows: t.Iterable[t.Tuple[str, str]], col_count: int
|
24 |
+
) -> t.Iterator[t.Tuple[str, ...]]:
|
25 |
+
for row in rows:
|
26 |
+
yield row + ("",) * (col_count - len(row))
|
27 |
+
|
28 |
+
|
29 |
+
def wrap_text(
|
30 |
+
text: str,
|
31 |
+
width: int = 78,
|
32 |
+
initial_indent: str = "",
|
33 |
+
subsequent_indent: str = "",
|
34 |
+
preserve_paragraphs: bool = False,
|
35 |
+
) -> str:
|
36 |
+
"""A helper function that intelligently wraps text. By default, it
|
37 |
+
assumes that it operates on a single paragraph of text but if the
|
38 |
+
`preserve_paragraphs` parameter is provided it will intelligently
|
39 |
+
handle paragraphs (defined by two empty lines).
|
40 |
+
|
41 |
+
If paragraphs are handled, a paragraph can be prefixed with an empty
|
42 |
+
line containing the ``\\b`` character (``\\x08``) to indicate that
|
43 |
+
no rewrapping should happen in that block.
|
44 |
+
|
45 |
+
:param text: the text that should be rewrapped.
|
46 |
+
:param width: the maximum width for the text.
|
47 |
+
:param initial_indent: the initial indent that should be placed on the
|
48 |
+
first line as a string.
|
49 |
+
:param subsequent_indent: the indent string that should be placed on
|
50 |
+
each consecutive line.
|
51 |
+
:param preserve_paragraphs: if this flag is set then the wrapping will
|
52 |
+
intelligently handle paragraphs.
|
53 |
+
"""
|
54 |
+
from ._textwrap import TextWrapper
|
55 |
+
|
56 |
+
text = text.expandtabs()
|
57 |
+
wrapper = TextWrapper(
|
58 |
+
width,
|
59 |
+
initial_indent=initial_indent,
|
60 |
+
subsequent_indent=subsequent_indent,
|
61 |
+
replace_whitespace=False,
|
62 |
+
)
|
63 |
+
if not preserve_paragraphs:
|
64 |
+
return wrapper.fill(text)
|
65 |
+
|
66 |
+
p: t.List[t.Tuple[int, bool, str]] = []
|
67 |
+
buf: t.List[str] = []
|
68 |
+
indent = None
|
69 |
+
|
70 |
+
def _flush_par() -> None:
|
71 |
+
if not buf:
|
72 |
+
return
|
73 |
+
if buf[0].strip() == "\b":
|
74 |
+
p.append((indent or 0, True, "\n".join(buf[1:])))
|
75 |
+
else:
|
76 |
+
p.append((indent or 0, False, " ".join(buf)))
|
77 |
+
del buf[:]
|
78 |
+
|
79 |
+
for line in text.splitlines():
|
80 |
+
if not line:
|
81 |
+
_flush_par()
|
82 |
+
indent = None
|
83 |
+
else:
|
84 |
+
if indent is None:
|
85 |
+
orig_len = term_len(line)
|
86 |
+
line = line.lstrip()
|
87 |
+
indent = orig_len - term_len(line)
|
88 |
+
buf.append(line)
|
89 |
+
_flush_par()
|
90 |
+
|
91 |
+
rv = []
|
92 |
+
for indent, raw, text in p:
|
93 |
+
with wrapper.extra_indent(" " * indent):
|
94 |
+
if raw:
|
95 |
+
rv.append(wrapper.indent_only(text))
|
96 |
+
else:
|
97 |
+
rv.append(wrapper.fill(text))
|
98 |
+
|
99 |
+
return "\n\n".join(rv)
|
100 |
+
|
101 |
+
|
102 |
+
class HelpFormatter:
|
103 |
+
"""This class helps with formatting text-based help pages. It's
|
104 |
+
usually just needed for very special internal cases, but it's also
|
105 |
+
exposed so that developers can write their own fancy outputs.
|
106 |
+
|
107 |
+
At present, it always writes into memory.
|
108 |
+
|
109 |
+
:param indent_increment: the additional increment for each level.
|
110 |
+
:param width: the width for the text. This defaults to the terminal
|
111 |
+
width clamped to a maximum of 78.
|
112 |
+
"""
|
113 |
+
|
114 |
+
def __init__(
|
115 |
+
self,
|
116 |
+
indent_increment: int = 2,
|
117 |
+
width: t.Optional[int] = None,
|
118 |
+
max_width: t.Optional[int] = None,
|
119 |
+
) -> None:
|
120 |
+
import shutil
|
121 |
+
|
122 |
+
self.indent_increment = indent_increment
|
123 |
+
if max_width is None:
|
124 |
+
max_width = 80
|
125 |
+
if width is None:
|
126 |
+
width = FORCED_WIDTH
|
127 |
+
if width is None:
|
128 |
+
width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)
|
129 |
+
self.width = width
|
130 |
+
self.current_indent = 0
|
131 |
+
self.buffer: t.List[str] = []
|
132 |
+
|
133 |
+
def write(self, string: str) -> None:
|
134 |
+
"""Writes a unicode string into the internal buffer."""
|
135 |
+
self.buffer.append(string)
|
136 |
+
|
137 |
+
def indent(self) -> None:
|
138 |
+
"""Increases the indentation."""
|
139 |
+
self.current_indent += self.indent_increment
|
140 |
+
|
141 |
+
def dedent(self) -> None:
|
142 |
+
"""Decreases the indentation."""
|
143 |
+
self.current_indent -= self.indent_increment
|
144 |
+
|
145 |
+
def write_usage(
|
146 |
+
self, prog: str, args: str = "", prefix: t.Optional[str] = None
|
147 |
+
) -> None:
|
148 |
+
"""Writes a usage line into the buffer.
|
149 |
+
|
150 |
+
:param prog: the program name.
|
151 |
+
:param args: whitespace separated list of arguments.
|
152 |
+
:param prefix: The prefix for the first line. Defaults to
|
153 |
+
``"Usage: "``.
|
154 |
+
"""
|
155 |
+
if prefix is None:
|
156 |
+
prefix = f"{_('Usage:')} "
|
157 |
+
|
158 |
+
usage_prefix = f"{prefix:>{self.current_indent}}{prog} "
|
159 |
+
text_width = self.width - self.current_indent
|
160 |
+
|
161 |
+
if text_width >= (term_len(usage_prefix) + 20):
|
162 |
+
# The arguments will fit to the right of the prefix.
|
163 |
+
indent = " " * term_len(usage_prefix)
|
164 |
+
self.write(
|
165 |
+
wrap_text(
|
166 |
+
args,
|
167 |
+
text_width,
|
168 |
+
initial_indent=usage_prefix,
|
169 |
+
subsequent_indent=indent,
|
170 |
+
)
|
171 |
+
)
|
172 |
+
else:
|
173 |
+
# The prefix is too long, put the arguments on the next line.
|
174 |
+
self.write(usage_prefix)
|
175 |
+
self.write("\n")
|
176 |
+
indent = " " * (max(self.current_indent, term_len(prefix)) + 4)
|
177 |
+
self.write(
|
178 |
+
wrap_text(
|
179 |
+
args, text_width, initial_indent=indent, subsequent_indent=indent
|
180 |
+
)
|
181 |
+
)
|
182 |
+
|
183 |
+
self.write("\n")
|
184 |
+
|
185 |
+
def write_heading(self, heading: str) -> None:
|
186 |
+
"""Writes a heading into the buffer."""
|
187 |
+
self.write(f"{'':>{self.current_indent}}{heading}:\n")
|
188 |
+
|
189 |
+
def write_paragraph(self) -> None:
|
190 |
+
"""Writes a paragraph into the buffer."""
|
191 |
+
if self.buffer:
|
192 |
+
self.write("\n")
|
193 |
+
|
194 |
+
def write_text(self, text: str) -> None:
|
195 |
+
"""Writes re-indented text into the buffer. This rewraps and
|
196 |
+
preserves paragraphs.
|
197 |
+
"""
|
198 |
+
indent = " " * self.current_indent
|
199 |
+
self.write(
|
200 |
+
wrap_text(
|
201 |
+
text,
|
202 |
+
self.width,
|
203 |
+
initial_indent=indent,
|
204 |
+
subsequent_indent=indent,
|
205 |
+
preserve_paragraphs=True,
|
206 |
+
)
|
207 |
+
)
|
208 |
+
self.write("\n")
|
209 |
+
|
210 |
+
def write_dl(
|
211 |
+
self,
|
212 |
+
rows: t.Sequence[t.Tuple[str, str]],
|
213 |
+
col_max: int = 30,
|
214 |
+
col_spacing: int = 2,
|
215 |
+
) -> None:
|
216 |
+
"""Writes a definition list into the buffer. This is how options
|
217 |
+
and commands are usually formatted.
|
218 |
+
|
219 |
+
:param rows: a list of two item tuples for the terms and values.
|
220 |
+
:param col_max: the maximum width of the first column.
|
221 |
+
:param col_spacing: the number of spaces between the first and
|
222 |
+
second column.
|
223 |
+
"""
|
224 |
+
rows = list(rows)
|
225 |
+
widths = measure_table(rows)
|
226 |
+
if len(widths) != 2:
|
227 |
+
raise TypeError("Expected two columns for definition list")
|
228 |
+
|
229 |
+
first_col = min(widths[0], col_max) + col_spacing
|
230 |
+
|
231 |
+
for first, second in iter_rows(rows, len(widths)):
|
232 |
+
self.write(f"{'':>{self.current_indent}}{first}")
|
233 |
+
if not second:
|
234 |
+
self.write("\n")
|
235 |
+
continue
|
236 |
+
if term_len(first) <= first_col - col_spacing:
|
237 |
+
self.write(" " * (first_col - term_len(first)))
|
238 |
+
else:
|
239 |
+
self.write("\n")
|
240 |
+
self.write(" " * (first_col + self.current_indent))
|
241 |
+
|
242 |
+
text_width = max(self.width - first_col - 2, 10)
|
243 |
+
wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)
|
244 |
+
lines = wrapped_text.splitlines()
|
245 |
+
|
246 |
+
if lines:
|
247 |
+
self.write(f"{lines[0]}\n")
|
248 |
+
|
249 |
+
for line in lines[1:]:
|
250 |
+
self.write(f"{'':>{first_col + self.current_indent}}{line}\n")
|
251 |
+
else:
|
252 |
+
self.write("\n")
|
253 |
+
|
254 |
+
@contextmanager
|
255 |
+
def section(self, name: str) -> t.Iterator[None]:
|
256 |
+
"""Helpful context manager that writes a paragraph, a heading,
|
257 |
+
and the indents.
|
258 |
+
|
259 |
+
:param name: the section name that is written as heading.
|
260 |
+
"""
|
261 |
+
self.write_paragraph()
|
262 |
+
self.write_heading(name)
|
263 |
+
self.indent()
|
264 |
+
try:
|
265 |
+
yield
|
266 |
+
finally:
|
267 |
+
self.dedent()
|
268 |
+
|
269 |
+
@contextmanager
|
270 |
+
def indentation(self) -> t.Iterator[None]:
|
271 |
+
"""A context manager that increases the indentation."""
|
272 |
+
self.indent()
|
273 |
+
try:
|
274 |
+
yield
|
275 |
+
finally:
|
276 |
+
self.dedent()
|
277 |
+
|
278 |
+
def getvalue(self) -> str:
|
279 |
+
"""Returns the buffer contents."""
|
280 |
+
return "".join(self.buffer)
|
281 |
+
|
282 |
+
|
283 |
+
def join_options(options: t.Sequence[str]) -> t.Tuple[str, bool]:
|
284 |
+
"""Given a list of option strings this joins them in the most appropriate
|
285 |
+
way and returns them in the form ``(formatted_string,
|
286 |
+
any_prefix_is_slash)`` where the second item in the tuple is a flag that
|
287 |
+
indicates if any of the option prefixes was a slash.
|
288 |
+
"""
|
289 |
+
rv = []
|
290 |
+
any_prefix_is_slash = False
|
291 |
+
|
292 |
+
for opt in options:
|
293 |
+
prefix = split_opt(opt)[0]
|
294 |
+
|
295 |
+
if prefix == "/":
|
296 |
+
any_prefix_is_slash = True
|
297 |
+
|
298 |
+
rv.append((len(prefix), opt))
|
299 |
+
|
300 |
+
rv.sort(key=lambda x: x[0])
|
301 |
+
return ", ".join(x[1] for x in rv), any_prefix_is_slash
|
llmeval-env/lib/python3.10/site-packages/click/globals.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
from threading import local
|
3 |
+
|
4 |
+
if t.TYPE_CHECKING:
|
5 |
+
import typing_extensions as te
|
6 |
+
from .core import Context
|
7 |
+
|
8 |
+
_local = local()
|
9 |
+
|
10 |
+
|
11 |
+
@t.overload
|
12 |
+
def get_current_context(silent: "te.Literal[False]" = False) -> "Context":
|
13 |
+
...
|
14 |
+
|
15 |
+
|
16 |
+
@t.overload
|
17 |
+
def get_current_context(silent: bool = ...) -> t.Optional["Context"]:
|
18 |
+
...
|
19 |
+
|
20 |
+
|
21 |
+
def get_current_context(silent: bool = False) -> t.Optional["Context"]:
|
22 |
+
"""Returns the current click context. This can be used as a way to
|
23 |
+
access the current context object from anywhere. This is a more implicit
|
24 |
+
alternative to the :func:`pass_context` decorator. This function is
|
25 |
+
primarily useful for helpers such as :func:`echo` which might be
|
26 |
+
interested in changing its behavior based on the current context.
|
27 |
+
|
28 |
+
To push the current context, :meth:`Context.scope` can be used.
|
29 |
+
|
30 |
+
.. versionadded:: 5.0
|
31 |
+
|
32 |
+
:param silent: if set to `True` the return value is `None` if no context
|
33 |
+
is available. The default behavior is to raise a
|
34 |
+
:exc:`RuntimeError`.
|
35 |
+
"""
|
36 |
+
try:
|
37 |
+
return t.cast("Context", _local.stack[-1])
|
38 |
+
except (AttributeError, IndexError) as e:
|
39 |
+
if not silent:
|
40 |
+
raise RuntimeError("There is no active click context.") from e
|
41 |
+
|
42 |
+
return None
|
43 |
+
|
44 |
+
|
45 |
+
def push_context(ctx: "Context") -> None:
|
46 |
+
"""Pushes a new context to the current stack."""
|
47 |
+
_local.__dict__.setdefault("stack", []).append(ctx)
|
48 |
+
|
49 |
+
|
50 |
+
def pop_context() -> None:
|
51 |
+
"""Removes the top level from the stack."""
|
52 |
+
_local.stack.pop()
|
53 |
+
|
54 |
+
|
55 |
+
def resolve_color_default(color: t.Optional[bool] = None) -> t.Optional[bool]:
|
56 |
+
"""Internal helper to get the default value of the color flag. If a
|
57 |
+
value is passed it's returned unchanged, otherwise it's looked up from
|
58 |
+
the current context.
|
59 |
+
"""
|
60 |
+
if color is not None:
|
61 |
+
return color
|
62 |
+
|
63 |
+
ctx = get_current_context(silent=True)
|
64 |
+
|
65 |
+
if ctx is not None:
|
66 |
+
return ctx.color
|
67 |
+
|
68 |
+
return None
|
llmeval-env/lib/python3.10/site-packages/click/shell_completion.py
ADDED
@@ -0,0 +1,596 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import typing as t
|
4 |
+
from gettext import gettext as _
|
5 |
+
|
6 |
+
from .core import Argument
|
7 |
+
from .core import BaseCommand
|
8 |
+
from .core import Context
|
9 |
+
from .core import MultiCommand
|
10 |
+
from .core import Option
|
11 |
+
from .core import Parameter
|
12 |
+
from .core import ParameterSource
|
13 |
+
from .parser import split_arg_string
|
14 |
+
from .utils import echo
|
15 |
+
|
16 |
+
|
17 |
+
def shell_complete(
|
18 |
+
cli: BaseCommand,
|
19 |
+
ctx_args: t.MutableMapping[str, t.Any],
|
20 |
+
prog_name: str,
|
21 |
+
complete_var: str,
|
22 |
+
instruction: str,
|
23 |
+
) -> int:
|
24 |
+
"""Perform shell completion for the given CLI program.
|
25 |
+
|
26 |
+
:param cli: Command being called.
|
27 |
+
:param ctx_args: Extra arguments to pass to
|
28 |
+
``cli.make_context``.
|
29 |
+
:param prog_name: Name of the executable in the shell.
|
30 |
+
:param complete_var: Name of the environment variable that holds
|
31 |
+
the completion instruction.
|
32 |
+
:param instruction: Value of ``complete_var`` with the completion
|
33 |
+
instruction and shell, in the form ``instruction_shell``.
|
34 |
+
:return: Status code to exit with.
|
35 |
+
"""
|
36 |
+
shell, _, instruction = instruction.partition("_")
|
37 |
+
comp_cls = get_completion_class(shell)
|
38 |
+
|
39 |
+
if comp_cls is None:
|
40 |
+
return 1
|
41 |
+
|
42 |
+
comp = comp_cls(cli, ctx_args, prog_name, complete_var)
|
43 |
+
|
44 |
+
if instruction == "source":
|
45 |
+
echo(comp.source())
|
46 |
+
return 0
|
47 |
+
|
48 |
+
if instruction == "complete":
|
49 |
+
echo(comp.complete())
|
50 |
+
return 0
|
51 |
+
|
52 |
+
return 1
|
53 |
+
|
54 |
+
|
55 |
+
class CompletionItem:
|
56 |
+
"""Represents a completion value and metadata about the value. The
|
57 |
+
default metadata is ``type`` to indicate special shell handling,
|
58 |
+
and ``help`` if a shell supports showing a help string next to the
|
59 |
+
value.
|
60 |
+
|
61 |
+
Arbitrary parameters can be passed when creating the object, and
|
62 |
+
accessed using ``item.attr``. If an attribute wasn't passed,
|
63 |
+
accessing it returns ``None``.
|
64 |
+
|
65 |
+
:param value: The completion suggestion.
|
66 |
+
:param type: Tells the shell script to provide special completion
|
67 |
+
support for the type. Click uses ``"dir"`` and ``"file"``.
|
68 |
+
:param help: String shown next to the value if supported.
|
69 |
+
:param kwargs: Arbitrary metadata. The built-in implementations
|
70 |
+
don't use this, but custom type completions paired with custom
|
71 |
+
shell support could use it.
|
72 |
+
"""
|
73 |
+
|
74 |
+
__slots__ = ("value", "type", "help", "_info")
|
75 |
+
|
76 |
+
def __init__(
|
77 |
+
self,
|
78 |
+
value: t.Any,
|
79 |
+
type: str = "plain",
|
80 |
+
help: t.Optional[str] = None,
|
81 |
+
**kwargs: t.Any,
|
82 |
+
) -> None:
|
83 |
+
self.value: t.Any = value
|
84 |
+
self.type: str = type
|
85 |
+
self.help: t.Optional[str] = help
|
86 |
+
self._info = kwargs
|
87 |
+
|
88 |
+
def __getattr__(self, name: str) -> t.Any:
|
89 |
+
return self._info.get(name)
|
90 |
+
|
91 |
+
|
92 |
+
# Only Bash >= 4.4 has the nosort option.
|
93 |
+
_SOURCE_BASH = """\
|
94 |
+
%(complete_func)s() {
|
95 |
+
local IFS=$'\\n'
|
96 |
+
local response
|
97 |
+
|
98 |
+
response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
|
99 |
+
%(complete_var)s=bash_complete $1)
|
100 |
+
|
101 |
+
for completion in $response; do
|
102 |
+
IFS=',' read type value <<< "$completion"
|
103 |
+
|
104 |
+
if [[ $type == 'dir' ]]; then
|
105 |
+
COMPREPLY=()
|
106 |
+
compopt -o dirnames
|
107 |
+
elif [[ $type == 'file' ]]; then
|
108 |
+
COMPREPLY=()
|
109 |
+
compopt -o default
|
110 |
+
elif [[ $type == 'plain' ]]; then
|
111 |
+
COMPREPLY+=($value)
|
112 |
+
fi
|
113 |
+
done
|
114 |
+
|
115 |
+
return 0
|
116 |
+
}
|
117 |
+
|
118 |
+
%(complete_func)s_setup() {
|
119 |
+
complete -o nosort -F %(complete_func)s %(prog_name)s
|
120 |
+
}
|
121 |
+
|
122 |
+
%(complete_func)s_setup;
|
123 |
+
"""
|
124 |
+
|
125 |
+
_SOURCE_ZSH = """\
|
126 |
+
#compdef %(prog_name)s
|
127 |
+
|
128 |
+
%(complete_func)s() {
|
129 |
+
local -a completions
|
130 |
+
local -a completions_with_descriptions
|
131 |
+
local -a response
|
132 |
+
(( ! $+commands[%(prog_name)s] )) && return 1
|
133 |
+
|
134 |
+
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \
|
135 |
+
%(complete_var)s=zsh_complete %(prog_name)s)}")
|
136 |
+
|
137 |
+
for type key descr in ${response}; do
|
138 |
+
if [[ "$type" == "plain" ]]; then
|
139 |
+
if [[ "$descr" == "_" ]]; then
|
140 |
+
completions+=("$key")
|
141 |
+
else
|
142 |
+
completions_with_descriptions+=("$key":"$descr")
|
143 |
+
fi
|
144 |
+
elif [[ "$type" == "dir" ]]; then
|
145 |
+
_path_files -/
|
146 |
+
elif [[ "$type" == "file" ]]; then
|
147 |
+
_path_files -f
|
148 |
+
fi
|
149 |
+
done
|
150 |
+
|
151 |
+
if [ -n "$completions_with_descriptions" ]; then
|
152 |
+
_describe -V unsorted completions_with_descriptions -U
|
153 |
+
fi
|
154 |
+
|
155 |
+
if [ -n "$completions" ]; then
|
156 |
+
compadd -U -V unsorted -a completions
|
157 |
+
fi
|
158 |
+
}
|
159 |
+
|
160 |
+
if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
|
161 |
+
# autoload from fpath, call function directly
|
162 |
+
%(complete_func)s "$@"
|
163 |
+
else
|
164 |
+
# eval/source/. command, register function for later
|
165 |
+
compdef %(complete_func)s %(prog_name)s
|
166 |
+
fi
|
167 |
+
"""
|
168 |
+
|
169 |
+
_SOURCE_FISH = """\
|
170 |
+
function %(complete_func)s;
|
171 |
+
set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \
|
172 |
+
COMP_CWORD=(commandline -t) %(prog_name)s);
|
173 |
+
|
174 |
+
for completion in $response;
|
175 |
+
set -l metadata (string split "," $completion);
|
176 |
+
|
177 |
+
if test $metadata[1] = "dir";
|
178 |
+
__fish_complete_directories $metadata[2];
|
179 |
+
else if test $metadata[1] = "file";
|
180 |
+
__fish_complete_path $metadata[2];
|
181 |
+
else if test $metadata[1] = "plain";
|
182 |
+
echo $metadata[2];
|
183 |
+
end;
|
184 |
+
end;
|
185 |
+
end;
|
186 |
+
|
187 |
+
complete --no-files --command %(prog_name)s --arguments \
|
188 |
+
"(%(complete_func)s)";
|
189 |
+
"""
|
190 |
+
|
191 |
+
|
192 |
+
class ShellComplete:
|
193 |
+
"""Base class for providing shell completion support. A subclass for
|
194 |
+
a given shell will override attributes and methods to implement the
|
195 |
+
completion instructions (``source`` and ``complete``).
|
196 |
+
|
197 |
+
:param cli: Command being called.
|
198 |
+
:param prog_name: Name of the executable in the shell.
|
199 |
+
:param complete_var: Name of the environment variable that holds
|
200 |
+
the completion instruction.
|
201 |
+
|
202 |
+
.. versionadded:: 8.0
|
203 |
+
"""
|
204 |
+
|
205 |
+
name: t.ClassVar[str]
|
206 |
+
"""Name to register the shell as with :func:`add_completion_class`.
|
207 |
+
This is used in completion instructions (``{name}_source`` and
|
208 |
+
``{name}_complete``).
|
209 |
+
"""
|
210 |
+
|
211 |
+
source_template: t.ClassVar[str]
|
212 |
+
"""Completion script template formatted by :meth:`source`. This must
|
213 |
+
be provided by subclasses.
|
214 |
+
"""
|
215 |
+
|
216 |
+
def __init__(
|
217 |
+
self,
|
218 |
+
cli: BaseCommand,
|
219 |
+
ctx_args: t.MutableMapping[str, t.Any],
|
220 |
+
prog_name: str,
|
221 |
+
complete_var: str,
|
222 |
+
) -> None:
|
223 |
+
self.cli = cli
|
224 |
+
self.ctx_args = ctx_args
|
225 |
+
self.prog_name = prog_name
|
226 |
+
self.complete_var = complete_var
|
227 |
+
|
228 |
+
@property
|
229 |
+
def func_name(self) -> str:
|
230 |
+
"""The name of the shell function defined by the completion
|
231 |
+
script.
|
232 |
+
"""
|
233 |
+
safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)
|
234 |
+
return f"_{safe_name}_completion"
|
235 |
+
|
236 |
+
def source_vars(self) -> t.Dict[str, t.Any]:
|
237 |
+
"""Vars for formatting :attr:`source_template`.
|
238 |
+
|
239 |
+
By default this provides ``complete_func``, ``complete_var``,
|
240 |
+
and ``prog_name``.
|
241 |
+
"""
|
242 |
+
return {
|
243 |
+
"complete_func": self.func_name,
|
244 |
+
"complete_var": self.complete_var,
|
245 |
+
"prog_name": self.prog_name,
|
246 |
+
}
|
247 |
+
|
248 |
+
def source(self) -> str:
|
249 |
+
"""Produce the shell script that defines the completion
|
250 |
+
function. By default this ``%``-style formats
|
251 |
+
:attr:`source_template` with the dict returned by
|
252 |
+
:meth:`source_vars`.
|
253 |
+
"""
|
254 |
+
return self.source_template % self.source_vars()
|
255 |
+
|
256 |
+
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
|
257 |
+
"""Use the env vars defined by the shell script to return a
|
258 |
+
tuple of ``args, incomplete``. This must be implemented by
|
259 |
+
subclasses.
|
260 |
+
"""
|
261 |
+
raise NotImplementedError
|
262 |
+
|
263 |
+
def get_completions(
|
264 |
+
self, args: t.List[str], incomplete: str
|
265 |
+
) -> t.List[CompletionItem]:
|
266 |
+
"""Determine the context and last complete command or parameter
|
267 |
+
from the complete args. Call that object's ``shell_complete``
|
268 |
+
method to get the completions for the incomplete value.
|
269 |
+
|
270 |
+
:param args: List of complete args before the incomplete value.
|
271 |
+
:param incomplete: Value being completed. May be empty.
|
272 |
+
"""
|
273 |
+
ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)
|
274 |
+
obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
|
275 |
+
return obj.shell_complete(ctx, incomplete)
|
276 |
+
|
277 |
+
def format_completion(self, item: CompletionItem) -> str:
|
278 |
+
"""Format a completion item into the form recognized by the
|
279 |
+
shell script. This must be implemented by subclasses.
|
280 |
+
|
281 |
+
:param item: Completion item to format.
|
282 |
+
"""
|
283 |
+
raise NotImplementedError
|
284 |
+
|
285 |
+
def complete(self) -> str:
|
286 |
+
"""Produce the completion data to send back to the shell.
|
287 |
+
|
288 |
+
By default this calls :meth:`get_completion_args`, gets the
|
289 |
+
completions, then calls :meth:`format_completion` for each
|
290 |
+
completion.
|
291 |
+
"""
|
292 |
+
args, incomplete = self.get_completion_args()
|
293 |
+
completions = self.get_completions(args, incomplete)
|
294 |
+
out = [self.format_completion(item) for item in completions]
|
295 |
+
return "\n".join(out)
|
296 |
+
|
297 |
+
|
298 |
+
class BashComplete(ShellComplete):
|
299 |
+
"""Shell completion for Bash."""
|
300 |
+
|
301 |
+
name = "bash"
|
302 |
+
source_template = _SOURCE_BASH
|
303 |
+
|
304 |
+
@staticmethod
|
305 |
+
def _check_version() -> None:
|
306 |
+
import subprocess
|
307 |
+
|
308 |
+
output = subprocess.run(
|
309 |
+
["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE
|
310 |
+
)
|
311 |
+
match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
|
312 |
+
|
313 |
+
if match is not None:
|
314 |
+
major, minor = match.groups()
|
315 |
+
|
316 |
+
if major < "4" or major == "4" and minor < "4":
|
317 |
+
echo(
|
318 |
+
_(
|
319 |
+
"Shell completion is not supported for Bash"
|
320 |
+
" versions older than 4.4."
|
321 |
+
),
|
322 |
+
err=True,
|
323 |
+
)
|
324 |
+
else:
|
325 |
+
echo(
|
326 |
+
_("Couldn't detect Bash version, shell completion is not supported."),
|
327 |
+
err=True,
|
328 |
+
)
|
329 |
+
|
330 |
+
def source(self) -> str:
|
331 |
+
self._check_version()
|
332 |
+
return super().source()
|
333 |
+
|
334 |
+
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
|
335 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
336 |
+
cword = int(os.environ["COMP_CWORD"])
|
337 |
+
args = cwords[1:cword]
|
338 |
+
|
339 |
+
try:
|
340 |
+
incomplete = cwords[cword]
|
341 |
+
except IndexError:
|
342 |
+
incomplete = ""
|
343 |
+
|
344 |
+
return args, incomplete
|
345 |
+
|
346 |
+
def format_completion(self, item: CompletionItem) -> str:
|
347 |
+
return f"{item.type},{item.value}"
|
348 |
+
|
349 |
+
|
350 |
+
class ZshComplete(ShellComplete):
|
351 |
+
"""Shell completion for Zsh."""
|
352 |
+
|
353 |
+
name = "zsh"
|
354 |
+
source_template = _SOURCE_ZSH
|
355 |
+
|
356 |
+
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
|
357 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
358 |
+
cword = int(os.environ["COMP_CWORD"])
|
359 |
+
args = cwords[1:cword]
|
360 |
+
|
361 |
+
try:
|
362 |
+
incomplete = cwords[cword]
|
363 |
+
except IndexError:
|
364 |
+
incomplete = ""
|
365 |
+
|
366 |
+
return args, incomplete
|
367 |
+
|
368 |
+
def format_completion(self, item: CompletionItem) -> str:
|
369 |
+
return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"
|
370 |
+
|
371 |
+
|
372 |
+
class FishComplete(ShellComplete):
|
373 |
+
"""Shell completion for Fish."""
|
374 |
+
|
375 |
+
name = "fish"
|
376 |
+
source_template = _SOURCE_FISH
|
377 |
+
|
378 |
+
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
|
379 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
380 |
+
incomplete = os.environ["COMP_CWORD"]
|
381 |
+
args = cwords[1:]
|
382 |
+
|
383 |
+
# Fish stores the partial word in both COMP_WORDS and
|
384 |
+
# COMP_CWORD, remove it from complete args.
|
385 |
+
if incomplete and args and args[-1] == incomplete:
|
386 |
+
args.pop()
|
387 |
+
|
388 |
+
return args, incomplete
|
389 |
+
|
390 |
+
def format_completion(self, item: CompletionItem) -> str:
|
391 |
+
if item.help:
|
392 |
+
return f"{item.type},{item.value}\t{item.help}"
|
393 |
+
|
394 |
+
return f"{item.type},{item.value}"
|
395 |
+
|
396 |
+
|
397 |
+
ShellCompleteType = t.TypeVar("ShellCompleteType", bound=t.Type[ShellComplete])
|
398 |
+
|
399 |
+
|
400 |
+
_available_shells: t.Dict[str, t.Type[ShellComplete]] = {
|
401 |
+
"bash": BashComplete,
|
402 |
+
"fish": FishComplete,
|
403 |
+
"zsh": ZshComplete,
|
404 |
+
}
|
405 |
+
|
406 |
+
|
407 |
+
def add_completion_class(
|
408 |
+
cls: ShellCompleteType, name: t.Optional[str] = None
|
409 |
+
) -> ShellCompleteType:
|
410 |
+
"""Register a :class:`ShellComplete` subclass under the given name.
|
411 |
+
The name will be provided by the completion instruction environment
|
412 |
+
variable during completion.
|
413 |
+
|
414 |
+
:param cls: The completion class that will handle completion for the
|
415 |
+
shell.
|
416 |
+
:param name: Name to register the class under. Defaults to the
|
417 |
+
class's ``name`` attribute.
|
418 |
+
"""
|
419 |
+
if name is None:
|
420 |
+
name = cls.name
|
421 |
+
|
422 |
+
_available_shells[name] = cls
|
423 |
+
|
424 |
+
return cls
|
425 |
+
|
426 |
+
|
427 |
+
def get_completion_class(shell: str) -> t.Optional[t.Type[ShellComplete]]:
|
428 |
+
"""Look up a registered :class:`ShellComplete` subclass by the name
|
429 |
+
provided by the completion instruction environment variable. If the
|
430 |
+
name isn't registered, returns ``None``.
|
431 |
+
|
432 |
+
:param shell: Name the class is registered under.
|
433 |
+
"""
|
434 |
+
return _available_shells.get(shell)
|
435 |
+
|
436 |
+
|
437 |
+
def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:
|
438 |
+
"""Determine if the given parameter is an argument that can still
|
439 |
+
accept values.
|
440 |
+
|
441 |
+
:param ctx: Invocation context for the command represented by the
|
442 |
+
parsed complete args.
|
443 |
+
:param param: Argument object being checked.
|
444 |
+
"""
|
445 |
+
if not isinstance(param, Argument):
|
446 |
+
return False
|
447 |
+
|
448 |
+
assert param.name is not None
|
449 |
+
# Will be None if expose_value is False.
|
450 |
+
value = ctx.params.get(param.name)
|
451 |
+
return (
|
452 |
+
param.nargs == -1
|
453 |
+
or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE
|
454 |
+
or (
|
455 |
+
param.nargs > 1
|
456 |
+
and isinstance(value, (tuple, list))
|
457 |
+
and len(value) < param.nargs
|
458 |
+
)
|
459 |
+
)
|
460 |
+
|
461 |
+
|
462 |
+
def _start_of_option(ctx: Context, value: str) -> bool:
|
463 |
+
"""Check if the value looks like the start of an option."""
|
464 |
+
if not value:
|
465 |
+
return False
|
466 |
+
|
467 |
+
c = value[0]
|
468 |
+
return c in ctx._opt_prefixes
|
469 |
+
|
470 |
+
|
471 |
+
def _is_incomplete_option(ctx: Context, args: t.List[str], param: Parameter) -> bool:
|
472 |
+
"""Determine if the given parameter is an option that needs a value.
|
473 |
+
|
474 |
+
:param args: List of complete args before the incomplete value.
|
475 |
+
:param param: Option object being checked.
|
476 |
+
"""
|
477 |
+
if not isinstance(param, Option):
|
478 |
+
return False
|
479 |
+
|
480 |
+
if param.is_flag or param.count:
|
481 |
+
return False
|
482 |
+
|
483 |
+
last_option = None
|
484 |
+
|
485 |
+
for index, arg in enumerate(reversed(args)):
|
486 |
+
if index + 1 > param.nargs:
|
487 |
+
break
|
488 |
+
|
489 |
+
if _start_of_option(ctx, arg):
|
490 |
+
last_option = arg
|
491 |
+
|
492 |
+
return last_option is not None and last_option in param.opts
|
493 |
+
|
494 |
+
|
495 |
+
def _resolve_context(
|
496 |
+
cli: BaseCommand,
|
497 |
+
ctx_args: t.MutableMapping[str, t.Any],
|
498 |
+
prog_name: str,
|
499 |
+
args: t.List[str],
|
500 |
+
) -> Context:
|
501 |
+
"""Produce the context hierarchy starting with the command and
|
502 |
+
traversing the complete arguments. This only follows the commands,
|
503 |
+
it doesn't trigger input prompts or callbacks.
|
504 |
+
|
505 |
+
:param cli: Command being called.
|
506 |
+
:param prog_name: Name of the executable in the shell.
|
507 |
+
:param args: List of complete args before the incomplete value.
|
508 |
+
"""
|
509 |
+
ctx_args["resilient_parsing"] = True
|
510 |
+
ctx = cli.make_context(prog_name, args.copy(), **ctx_args)
|
511 |
+
args = ctx.protected_args + ctx.args
|
512 |
+
|
513 |
+
while args:
|
514 |
+
command = ctx.command
|
515 |
+
|
516 |
+
if isinstance(command, MultiCommand):
|
517 |
+
if not command.chain:
|
518 |
+
name, cmd, args = command.resolve_command(ctx, args)
|
519 |
+
|
520 |
+
if cmd is None:
|
521 |
+
return ctx
|
522 |
+
|
523 |
+
ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)
|
524 |
+
args = ctx.protected_args + ctx.args
|
525 |
+
else:
|
526 |
+
sub_ctx = ctx
|
527 |
+
|
528 |
+
while args:
|
529 |
+
name, cmd, args = command.resolve_command(ctx, args)
|
530 |
+
|
531 |
+
if cmd is None:
|
532 |
+
return ctx
|
533 |
+
|
534 |
+
sub_ctx = cmd.make_context(
|
535 |
+
name,
|
536 |
+
args,
|
537 |
+
parent=ctx,
|
538 |
+
allow_extra_args=True,
|
539 |
+
allow_interspersed_args=False,
|
540 |
+
resilient_parsing=True,
|
541 |
+
)
|
542 |
+
args = sub_ctx.args
|
543 |
+
|
544 |
+
ctx = sub_ctx
|
545 |
+
args = [*sub_ctx.protected_args, *sub_ctx.args]
|
546 |
+
else:
|
547 |
+
break
|
548 |
+
|
549 |
+
return ctx
|
550 |
+
|
551 |
+
|
552 |
+
def _resolve_incomplete(
|
553 |
+
ctx: Context, args: t.List[str], incomplete: str
|
554 |
+
) -> t.Tuple[t.Union[BaseCommand, Parameter], str]:
|
555 |
+
"""Find the Click object that will handle the completion of the
|
556 |
+
incomplete value. Return the object and the incomplete value.
|
557 |
+
|
558 |
+
:param ctx: Invocation context for the command represented by
|
559 |
+
the parsed complete args.
|
560 |
+
:param args: List of complete args before the incomplete value.
|
561 |
+
:param incomplete: Value being completed. May be empty.
|
562 |
+
"""
|
563 |
+
# Different shells treat an "=" between a long option name and
|
564 |
+
# value differently. Might keep the value joined, return the "="
|
565 |
+
# as a separate item, or return the split name and value. Always
|
566 |
+
# split and discard the "=" to make completion easier.
|
567 |
+
if incomplete == "=":
|
568 |
+
incomplete = ""
|
569 |
+
elif "=" in incomplete and _start_of_option(ctx, incomplete):
|
570 |
+
name, _, incomplete = incomplete.partition("=")
|
571 |
+
args.append(name)
|
572 |
+
|
573 |
+
# The "--" marker tells Click to stop treating values as options
|
574 |
+
# even if they start with the option character. If it hasn't been
|
575 |
+
# given and the incomplete arg looks like an option, the current
|
576 |
+
# command will provide option name completions.
|
577 |
+
if "--" not in args and _start_of_option(ctx, incomplete):
|
578 |
+
return ctx.command, incomplete
|
579 |
+
|
580 |
+
params = ctx.command.get_params(ctx)
|
581 |
+
|
582 |
+
# If the last complete arg is an option name with an incomplete
|
583 |
+
# value, the option will provide value completions.
|
584 |
+
for param in params:
|
585 |
+
if _is_incomplete_option(ctx, args, param):
|
586 |
+
return param, incomplete
|
587 |
+
|
588 |
+
# It's not an option name or value. The first argument without a
|
589 |
+
# parsed value will provide value completions.
|
590 |
+
for param in params:
|
591 |
+
if _is_incomplete_argument(ctx, param):
|
592 |
+
return param, incomplete
|
593 |
+
|
594 |
+
# There were no unparsed arguments, the command may be a group that
|
595 |
+
# will provide command name completions.
|
596 |
+
return ctx.command, incomplete
|
llmeval-env/lib/python3.10/site-packages/click/termui.py
ADDED
@@ -0,0 +1,784 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
import io
|
3 |
+
import itertools
|
4 |
+
import sys
|
5 |
+
import typing as t
|
6 |
+
from gettext import gettext as _
|
7 |
+
|
8 |
+
from ._compat import isatty
|
9 |
+
from ._compat import strip_ansi
|
10 |
+
from .exceptions import Abort
|
11 |
+
from .exceptions import UsageError
|
12 |
+
from .globals import resolve_color_default
|
13 |
+
from .types import Choice
|
14 |
+
from .types import convert_type
|
15 |
+
from .types import ParamType
|
16 |
+
from .utils import echo
|
17 |
+
from .utils import LazyFile
|
18 |
+
|
19 |
+
if t.TYPE_CHECKING:
|
20 |
+
from ._termui_impl import ProgressBar
|
21 |
+
|
22 |
+
V = t.TypeVar("V")
|
23 |
+
|
24 |
+
# The prompt functions to use. The doc tools currently override these
|
25 |
+
# functions to customize how they work.
|
26 |
+
visible_prompt_func: t.Callable[[str], str] = input
|
27 |
+
|
28 |
+
_ansi_colors = {
|
29 |
+
"black": 30,
|
30 |
+
"red": 31,
|
31 |
+
"green": 32,
|
32 |
+
"yellow": 33,
|
33 |
+
"blue": 34,
|
34 |
+
"magenta": 35,
|
35 |
+
"cyan": 36,
|
36 |
+
"white": 37,
|
37 |
+
"reset": 39,
|
38 |
+
"bright_black": 90,
|
39 |
+
"bright_red": 91,
|
40 |
+
"bright_green": 92,
|
41 |
+
"bright_yellow": 93,
|
42 |
+
"bright_blue": 94,
|
43 |
+
"bright_magenta": 95,
|
44 |
+
"bright_cyan": 96,
|
45 |
+
"bright_white": 97,
|
46 |
+
}
|
47 |
+
_ansi_reset_all = "\033[0m"
|
48 |
+
|
49 |
+
|
50 |
+
def hidden_prompt_func(prompt: str) -> str:
|
51 |
+
import getpass
|
52 |
+
|
53 |
+
return getpass.getpass(prompt)
|
54 |
+
|
55 |
+
|
56 |
+
def _build_prompt(
|
57 |
+
text: str,
|
58 |
+
suffix: str,
|
59 |
+
show_default: bool = False,
|
60 |
+
default: t.Optional[t.Any] = None,
|
61 |
+
show_choices: bool = True,
|
62 |
+
type: t.Optional[ParamType] = None,
|
63 |
+
) -> str:
|
64 |
+
prompt = text
|
65 |
+
if type is not None and show_choices and isinstance(type, Choice):
|
66 |
+
prompt += f" ({', '.join(map(str, type.choices))})"
|
67 |
+
if default is not None and show_default:
|
68 |
+
prompt = f"{prompt} [{_format_default(default)}]"
|
69 |
+
return f"{prompt}{suffix}"
|
70 |
+
|
71 |
+
|
72 |
+
def _format_default(default: t.Any) -> t.Any:
|
73 |
+
if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
|
74 |
+
return default.name
|
75 |
+
|
76 |
+
return default
|
77 |
+
|
78 |
+
|
79 |
+
def prompt(
|
80 |
+
text: str,
|
81 |
+
default: t.Optional[t.Any] = None,
|
82 |
+
hide_input: bool = False,
|
83 |
+
confirmation_prompt: t.Union[bool, str] = False,
|
84 |
+
type: t.Optional[t.Union[ParamType, t.Any]] = None,
|
85 |
+
value_proc: t.Optional[t.Callable[[str], t.Any]] = None,
|
86 |
+
prompt_suffix: str = ": ",
|
87 |
+
show_default: bool = True,
|
88 |
+
err: bool = False,
|
89 |
+
show_choices: bool = True,
|
90 |
+
) -> t.Any:
|
91 |
+
"""Prompts a user for input. This is a convenience function that can
|
92 |
+
be used to prompt a user for input later.
|
93 |
+
|
94 |
+
If the user aborts the input by sending an interrupt signal, this
|
95 |
+
function will catch it and raise a :exc:`Abort` exception.
|
96 |
+
|
97 |
+
:param text: the text to show for the prompt.
|
98 |
+
:param default: the default value to use if no input happens. If this
|
99 |
+
is not given it will prompt until it's aborted.
|
100 |
+
:param hide_input: if this is set to true then the input value will
|
101 |
+
be hidden.
|
102 |
+
:param confirmation_prompt: Prompt a second time to confirm the
|
103 |
+
value. Can be set to a string instead of ``True`` to customize
|
104 |
+
the message.
|
105 |
+
:param type: the type to use to check the value against.
|
106 |
+
:param value_proc: if this parameter is provided it's a function that
|
107 |
+
is invoked instead of the type conversion to
|
108 |
+
convert a value.
|
109 |
+
:param prompt_suffix: a suffix that should be added to the prompt.
|
110 |
+
:param show_default: shows or hides the default value in the prompt.
|
111 |
+
:param err: if set to true the file defaults to ``stderr`` instead of
|
112 |
+
``stdout``, the same as with echo.
|
113 |
+
:param show_choices: Show or hide choices if the passed type is a Choice.
|
114 |
+
For example if type is a Choice of either day or week,
|
115 |
+
show_choices is true and text is "Group by" then the
|
116 |
+
prompt will be "Group by (day, week): ".
|
117 |
+
|
118 |
+
.. versionadded:: 8.0
|
119 |
+
``confirmation_prompt`` can be a custom string.
|
120 |
+
|
121 |
+
.. versionadded:: 7.0
|
122 |
+
Added the ``show_choices`` parameter.
|
123 |
+
|
124 |
+
.. versionadded:: 6.0
|
125 |
+
Added unicode support for cmd.exe on Windows.
|
126 |
+
|
127 |
+
.. versionadded:: 4.0
|
128 |
+
Added the `err` parameter.
|
129 |
+
|
130 |
+
"""
|
131 |
+
|
132 |
+
def prompt_func(text: str) -> str:
|
133 |
+
f = hidden_prompt_func if hide_input else visible_prompt_func
|
134 |
+
try:
|
135 |
+
# Write the prompt separately so that we get nice
|
136 |
+
# coloring through colorama on Windows
|
137 |
+
echo(text.rstrip(" "), nl=False, err=err)
|
138 |
+
# Echo a space to stdout to work around an issue where
|
139 |
+
# readline causes backspace to clear the whole line.
|
140 |
+
return f(" ")
|
141 |
+
except (KeyboardInterrupt, EOFError):
|
142 |
+
# getpass doesn't print a newline if the user aborts input with ^C.
|
143 |
+
# Allegedly this behavior is inherited from getpass(3).
|
144 |
+
# A doc bug has been filed at https://bugs.python.org/issue24711
|
145 |
+
if hide_input:
|
146 |
+
echo(None, err=err)
|
147 |
+
raise Abort() from None
|
148 |
+
|
149 |
+
if value_proc is None:
|
150 |
+
value_proc = convert_type(type, default)
|
151 |
+
|
152 |
+
prompt = _build_prompt(
|
153 |
+
text, prompt_suffix, show_default, default, show_choices, type
|
154 |
+
)
|
155 |
+
|
156 |
+
if confirmation_prompt:
|
157 |
+
if confirmation_prompt is True:
|
158 |
+
confirmation_prompt = _("Repeat for confirmation")
|
159 |
+
|
160 |
+
confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
|
161 |
+
|
162 |
+
while True:
|
163 |
+
while True:
|
164 |
+
value = prompt_func(prompt)
|
165 |
+
if value:
|
166 |
+
break
|
167 |
+
elif default is not None:
|
168 |
+
value = default
|
169 |
+
break
|
170 |
+
try:
|
171 |
+
result = value_proc(value)
|
172 |
+
except UsageError as e:
|
173 |
+
if hide_input:
|
174 |
+
echo(_("Error: The value you entered was invalid."), err=err)
|
175 |
+
else:
|
176 |
+
echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306
|
177 |
+
continue
|
178 |
+
if not confirmation_prompt:
|
179 |
+
return result
|
180 |
+
while True:
|
181 |
+
value2 = prompt_func(confirmation_prompt)
|
182 |
+
is_empty = not value and not value2
|
183 |
+
if value2 or is_empty:
|
184 |
+
break
|
185 |
+
if value == value2:
|
186 |
+
return result
|
187 |
+
echo(_("Error: The two entered values do not match."), err=err)
|
188 |
+
|
189 |
+
|
190 |
+
def confirm(
|
191 |
+
text: str,
|
192 |
+
default: t.Optional[bool] = False,
|
193 |
+
abort: bool = False,
|
194 |
+
prompt_suffix: str = ": ",
|
195 |
+
show_default: bool = True,
|
196 |
+
err: bool = False,
|
197 |
+
) -> bool:
|
198 |
+
"""Prompts for confirmation (yes/no question).
|
199 |
+
|
200 |
+
If the user aborts the input by sending a interrupt signal this
|
201 |
+
function will catch it and raise a :exc:`Abort` exception.
|
202 |
+
|
203 |
+
:param text: the question to ask.
|
204 |
+
:param default: The default value to use when no input is given. If
|
205 |
+
``None``, repeat until input is given.
|
206 |
+
:param abort: if this is set to `True` a negative answer aborts the
|
207 |
+
exception by raising :exc:`Abort`.
|
208 |
+
:param prompt_suffix: a suffix that should be added to the prompt.
|
209 |
+
:param show_default: shows or hides the default value in the prompt.
|
210 |
+
:param err: if set to true the file defaults to ``stderr`` instead of
|
211 |
+
``stdout``, the same as with echo.
|
212 |
+
|
213 |
+
.. versionchanged:: 8.0
|
214 |
+
Repeat until input is given if ``default`` is ``None``.
|
215 |
+
|
216 |
+
.. versionadded:: 4.0
|
217 |
+
Added the ``err`` parameter.
|
218 |
+
"""
|
219 |
+
prompt = _build_prompt(
|
220 |
+
text,
|
221 |
+
prompt_suffix,
|
222 |
+
show_default,
|
223 |
+
"y/n" if default is None else ("Y/n" if default else "y/N"),
|
224 |
+
)
|
225 |
+
|
226 |
+
while True:
|
227 |
+
try:
|
228 |
+
# Write the prompt separately so that we get nice
|
229 |
+
# coloring through colorama on Windows
|
230 |
+
echo(prompt.rstrip(" "), nl=False, err=err)
|
231 |
+
# Echo a space to stdout to work around an issue where
|
232 |
+
# readline causes backspace to clear the whole line.
|
233 |
+
value = visible_prompt_func(" ").lower().strip()
|
234 |
+
except (KeyboardInterrupt, EOFError):
|
235 |
+
raise Abort() from None
|
236 |
+
if value in ("y", "yes"):
|
237 |
+
rv = True
|
238 |
+
elif value in ("n", "no"):
|
239 |
+
rv = False
|
240 |
+
elif default is not None and value == "":
|
241 |
+
rv = default
|
242 |
+
else:
|
243 |
+
echo(_("Error: invalid input"), err=err)
|
244 |
+
continue
|
245 |
+
break
|
246 |
+
if abort and not rv:
|
247 |
+
raise Abort()
|
248 |
+
return rv
|
249 |
+
|
250 |
+
|
251 |
+
def echo_via_pager(
|
252 |
+
text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str],
|
253 |
+
color: t.Optional[bool] = None,
|
254 |
+
) -> None:
|
255 |
+
"""This function takes a text and shows it via an environment specific
|
256 |
+
pager on stdout.
|
257 |
+
|
258 |
+
.. versionchanged:: 3.0
|
259 |
+
Added the `color` flag.
|
260 |
+
|
261 |
+
:param text_or_generator: the text to page, or alternatively, a
|
262 |
+
generator emitting the text to page.
|
263 |
+
:param color: controls if the pager supports ANSI colors or not. The
|
264 |
+
default is autodetection.
|
265 |
+
"""
|
266 |
+
color = resolve_color_default(color)
|
267 |
+
|
268 |
+
if inspect.isgeneratorfunction(text_or_generator):
|
269 |
+
i = t.cast(t.Callable[[], t.Iterable[str]], text_or_generator)()
|
270 |
+
elif isinstance(text_or_generator, str):
|
271 |
+
i = [text_or_generator]
|
272 |
+
else:
|
273 |
+
i = iter(t.cast(t.Iterable[str], text_or_generator))
|
274 |
+
|
275 |
+
# convert every element of i to a text type if necessary
|
276 |
+
text_generator = (el if isinstance(el, str) else str(el) for el in i)
|
277 |
+
|
278 |
+
from ._termui_impl import pager
|
279 |
+
|
280 |
+
return pager(itertools.chain(text_generator, "\n"), color)
|
281 |
+
|
282 |
+
|
283 |
+
def progressbar(
|
284 |
+
iterable: t.Optional[t.Iterable[V]] = None,
|
285 |
+
length: t.Optional[int] = None,
|
286 |
+
label: t.Optional[str] = None,
|
287 |
+
show_eta: bool = True,
|
288 |
+
show_percent: t.Optional[bool] = None,
|
289 |
+
show_pos: bool = False,
|
290 |
+
item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,
|
291 |
+
fill_char: str = "#",
|
292 |
+
empty_char: str = "-",
|
293 |
+
bar_template: str = "%(label)s [%(bar)s] %(info)s",
|
294 |
+
info_sep: str = " ",
|
295 |
+
width: int = 36,
|
296 |
+
file: t.Optional[t.TextIO] = None,
|
297 |
+
color: t.Optional[bool] = None,
|
298 |
+
update_min_steps: int = 1,
|
299 |
+
) -> "ProgressBar[V]":
|
300 |
+
"""This function creates an iterable context manager that can be used
|
301 |
+
to iterate over something while showing a progress bar. It will
|
302 |
+
either iterate over the `iterable` or `length` items (that are counted
|
303 |
+
up). While iteration happens, this function will print a rendered
|
304 |
+
progress bar to the given `file` (defaults to stdout) and will attempt
|
305 |
+
to calculate remaining time and more. By default, this progress bar
|
306 |
+
will not be rendered if the file is not a terminal.
|
307 |
+
|
308 |
+
The context manager creates the progress bar. When the context
|
309 |
+
manager is entered the progress bar is already created. With every
|
310 |
+
iteration over the progress bar, the iterable passed to the bar is
|
311 |
+
advanced and the bar is updated. When the context manager exits,
|
312 |
+
a newline is printed and the progress bar is finalized on screen.
|
313 |
+
|
314 |
+
Note: The progress bar is currently designed for use cases where the
|
315 |
+
total progress can be expected to take at least several seconds.
|
316 |
+
Because of this, the ProgressBar class object won't display
|
317 |
+
progress that is considered too fast, and progress where the time
|
318 |
+
between steps is less than a second.
|
319 |
+
|
320 |
+
No printing must happen or the progress bar will be unintentionally
|
321 |
+
destroyed.
|
322 |
+
|
323 |
+
Example usage::
|
324 |
+
|
325 |
+
with progressbar(items) as bar:
|
326 |
+
for item in bar:
|
327 |
+
do_something_with(item)
|
328 |
+
|
329 |
+
Alternatively, if no iterable is specified, one can manually update the
|
330 |
+
progress bar through the `update()` method instead of directly
|
331 |
+
iterating over the progress bar. The update method accepts the number
|
332 |
+
of steps to increment the bar with::
|
333 |
+
|
334 |
+
with progressbar(length=chunks.total_bytes) as bar:
|
335 |
+
for chunk in chunks:
|
336 |
+
process_chunk(chunk)
|
337 |
+
bar.update(chunks.bytes)
|
338 |
+
|
339 |
+
The ``update()`` method also takes an optional value specifying the
|
340 |
+
``current_item`` at the new position. This is useful when used
|
341 |
+
together with ``item_show_func`` to customize the output for each
|
342 |
+
manual step::
|
343 |
+
|
344 |
+
with click.progressbar(
|
345 |
+
length=total_size,
|
346 |
+
label='Unzipping archive',
|
347 |
+
item_show_func=lambda a: a.filename
|
348 |
+
) as bar:
|
349 |
+
for archive in zip_file:
|
350 |
+
archive.extract()
|
351 |
+
bar.update(archive.size, archive)
|
352 |
+
|
353 |
+
:param iterable: an iterable to iterate over. If not provided the length
|
354 |
+
is required.
|
355 |
+
:param length: the number of items to iterate over. By default the
|
356 |
+
progressbar will attempt to ask the iterator about its
|
357 |
+
length, which might or might not work. If an iterable is
|
358 |
+
also provided this parameter can be used to override the
|
359 |
+
length. If an iterable is not provided the progress bar
|
360 |
+
will iterate over a range of that length.
|
361 |
+
:param label: the label to show next to the progress bar.
|
362 |
+
:param show_eta: enables or disables the estimated time display. This is
|
363 |
+
automatically disabled if the length cannot be
|
364 |
+
determined.
|
365 |
+
:param show_percent: enables or disables the percentage display. The
|
366 |
+
default is `True` if the iterable has a length or
|
367 |
+
`False` if not.
|
368 |
+
:param show_pos: enables or disables the absolute position display. The
|
369 |
+
default is `False`.
|
370 |
+
:param item_show_func: A function called with the current item which
|
371 |
+
can return a string to show next to the progress bar. If the
|
372 |
+
function returns ``None`` nothing is shown. The current item can
|
373 |
+
be ``None``, such as when entering and exiting the bar.
|
374 |
+
:param fill_char: the character to use to show the filled part of the
|
375 |
+
progress bar.
|
376 |
+
:param empty_char: the character to use to show the non-filled part of
|
377 |
+
the progress bar.
|
378 |
+
:param bar_template: the format string to use as template for the bar.
|
379 |
+
The parameters in it are ``label`` for the label,
|
380 |
+
``bar`` for the progress bar and ``info`` for the
|
381 |
+
info section.
|
382 |
+
:param info_sep: the separator between multiple info items (eta etc.)
|
383 |
+
:param width: the width of the progress bar in characters, 0 means full
|
384 |
+
terminal width
|
385 |
+
:param file: The file to write to. If this is not a terminal then
|
386 |
+
only the label is printed.
|
387 |
+
:param color: controls if the terminal supports ANSI colors or not. The
|
388 |
+
default is autodetection. This is only needed if ANSI
|
389 |
+
codes are included anywhere in the progress bar output
|
390 |
+
which is not the case by default.
|
391 |
+
:param update_min_steps: Render only when this many updates have
|
392 |
+
completed. This allows tuning for very fast iterators.
|
393 |
+
|
394 |
+
.. versionchanged:: 8.0
|
395 |
+
Output is shown even if execution time is less than 0.5 seconds.
|
396 |
+
|
397 |
+
.. versionchanged:: 8.0
|
398 |
+
``item_show_func`` shows the current item, not the previous one.
|
399 |
+
|
400 |
+
.. versionchanged:: 8.0
|
401 |
+
Labels are echoed if the output is not a TTY. Reverts a change
|
402 |
+
in 7.0 that removed all output.
|
403 |
+
|
404 |
+
.. versionadded:: 8.0
|
405 |
+
Added the ``update_min_steps`` parameter.
|
406 |
+
|
407 |
+
.. versionchanged:: 4.0
|
408 |
+
Added the ``color`` parameter. Added the ``update`` method to
|
409 |
+
the object.
|
410 |
+
|
411 |
+
.. versionadded:: 2.0
|
412 |
+
"""
|
413 |
+
from ._termui_impl import ProgressBar
|
414 |
+
|
415 |
+
color = resolve_color_default(color)
|
416 |
+
return ProgressBar(
|
417 |
+
iterable=iterable,
|
418 |
+
length=length,
|
419 |
+
show_eta=show_eta,
|
420 |
+
show_percent=show_percent,
|
421 |
+
show_pos=show_pos,
|
422 |
+
item_show_func=item_show_func,
|
423 |
+
fill_char=fill_char,
|
424 |
+
empty_char=empty_char,
|
425 |
+
bar_template=bar_template,
|
426 |
+
info_sep=info_sep,
|
427 |
+
file=file,
|
428 |
+
label=label,
|
429 |
+
width=width,
|
430 |
+
color=color,
|
431 |
+
update_min_steps=update_min_steps,
|
432 |
+
)
|
433 |
+
|
434 |
+
|
435 |
+
def clear() -> None:
|
436 |
+
"""Clears the terminal screen. This will have the effect of clearing
|
437 |
+
the whole visible space of the terminal and moving the cursor to the
|
438 |
+
top left. This does not do anything if not connected to a terminal.
|
439 |
+
|
440 |
+
.. versionadded:: 2.0
|
441 |
+
"""
|
442 |
+
if not isatty(sys.stdout):
|
443 |
+
return
|
444 |
+
|
445 |
+
# ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
|
446 |
+
echo("\033[2J\033[1;1H", nl=False)
|
447 |
+
|
448 |
+
|
449 |
+
def _interpret_color(
|
450 |
+
color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0
|
451 |
+
) -> str:
|
452 |
+
if isinstance(color, int):
|
453 |
+
return f"{38 + offset};5;{color:d}"
|
454 |
+
|
455 |
+
if isinstance(color, (tuple, list)):
|
456 |
+
r, g, b = color
|
457 |
+
return f"{38 + offset};2;{r:d};{g:d};{b:d}"
|
458 |
+
|
459 |
+
return str(_ansi_colors[color] + offset)
|
460 |
+
|
461 |
+
|
462 |
+
def style(
|
463 |
+
text: t.Any,
|
464 |
+
fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,
|
465 |
+
bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,
|
466 |
+
bold: t.Optional[bool] = None,
|
467 |
+
dim: t.Optional[bool] = None,
|
468 |
+
underline: t.Optional[bool] = None,
|
469 |
+
overline: t.Optional[bool] = None,
|
470 |
+
italic: t.Optional[bool] = None,
|
471 |
+
blink: t.Optional[bool] = None,
|
472 |
+
reverse: t.Optional[bool] = None,
|
473 |
+
strikethrough: t.Optional[bool] = None,
|
474 |
+
reset: bool = True,
|
475 |
+
) -> str:
|
476 |
+
"""Styles a text with ANSI styles and returns the new string. By
|
477 |
+
default the styling is self contained which means that at the end
|
478 |
+
of the string a reset code is issued. This can be prevented by
|
479 |
+
passing ``reset=False``.
|
480 |
+
|
481 |
+
Examples::
|
482 |
+
|
483 |
+
click.echo(click.style('Hello World!', fg='green'))
|
484 |
+
click.echo(click.style('ATTENTION!', blink=True))
|
485 |
+
click.echo(click.style('Some things', reverse=True, fg='cyan'))
|
486 |
+
click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
|
487 |
+
|
488 |
+
Supported color names:
|
489 |
+
|
490 |
+
* ``black`` (might be a gray)
|
491 |
+
* ``red``
|
492 |
+
* ``green``
|
493 |
+
* ``yellow`` (might be an orange)
|
494 |
+
* ``blue``
|
495 |
+
* ``magenta``
|
496 |
+
* ``cyan``
|
497 |
+
* ``white`` (might be light gray)
|
498 |
+
* ``bright_black``
|
499 |
+
* ``bright_red``
|
500 |
+
* ``bright_green``
|
501 |
+
* ``bright_yellow``
|
502 |
+
* ``bright_blue``
|
503 |
+
* ``bright_magenta``
|
504 |
+
* ``bright_cyan``
|
505 |
+
* ``bright_white``
|
506 |
+
* ``reset`` (reset the color code only)
|
507 |
+
|
508 |
+
If the terminal supports it, color may also be specified as:
|
509 |
+
|
510 |
+
- An integer in the interval [0, 255]. The terminal must support
|
511 |
+
8-bit/256-color mode.
|
512 |
+
- An RGB tuple of three integers in [0, 255]. The terminal must
|
513 |
+
support 24-bit/true-color mode.
|
514 |
+
|
515 |
+
See https://en.wikipedia.org/wiki/ANSI_color and
|
516 |
+
https://gist.github.com/XVilka/8346728 for more information.
|
517 |
+
|
518 |
+
:param text: the string to style with ansi codes.
|
519 |
+
:param fg: if provided this will become the foreground color.
|
520 |
+
:param bg: if provided this will become the background color.
|
521 |
+
:param bold: if provided this will enable or disable bold mode.
|
522 |
+
:param dim: if provided this will enable or disable dim mode. This is
|
523 |
+
badly supported.
|
524 |
+
:param underline: if provided this will enable or disable underline.
|
525 |
+
:param overline: if provided this will enable or disable overline.
|
526 |
+
:param italic: if provided this will enable or disable italic.
|
527 |
+
:param blink: if provided this will enable or disable blinking.
|
528 |
+
:param reverse: if provided this will enable or disable inverse
|
529 |
+
rendering (foreground becomes background and the
|
530 |
+
other way round).
|
531 |
+
:param strikethrough: if provided this will enable or disable
|
532 |
+
striking through text.
|
533 |
+
:param reset: by default a reset-all code is added at the end of the
|
534 |
+
string which means that styles do not carry over. This
|
535 |
+
can be disabled to compose styles.
|
536 |
+
|
537 |
+
.. versionchanged:: 8.0
|
538 |
+
A non-string ``message`` is converted to a string.
|
539 |
+
|
540 |
+
.. versionchanged:: 8.0
|
541 |
+
Added support for 256 and RGB color codes.
|
542 |
+
|
543 |
+
.. versionchanged:: 8.0
|
544 |
+
Added the ``strikethrough``, ``italic``, and ``overline``
|
545 |
+
parameters.
|
546 |
+
|
547 |
+
.. versionchanged:: 7.0
|
548 |
+
Added support for bright colors.
|
549 |
+
|
550 |
+
.. versionadded:: 2.0
|
551 |
+
"""
|
552 |
+
if not isinstance(text, str):
|
553 |
+
text = str(text)
|
554 |
+
|
555 |
+
bits = []
|
556 |
+
|
557 |
+
if fg:
|
558 |
+
try:
|
559 |
+
bits.append(f"\033[{_interpret_color(fg)}m")
|
560 |
+
except KeyError:
|
561 |
+
raise TypeError(f"Unknown color {fg!r}") from None
|
562 |
+
|
563 |
+
if bg:
|
564 |
+
try:
|
565 |
+
bits.append(f"\033[{_interpret_color(bg, 10)}m")
|
566 |
+
except KeyError:
|
567 |
+
raise TypeError(f"Unknown color {bg!r}") from None
|
568 |
+
|
569 |
+
if bold is not None:
|
570 |
+
bits.append(f"\033[{1 if bold else 22}m")
|
571 |
+
if dim is not None:
|
572 |
+
bits.append(f"\033[{2 if dim else 22}m")
|
573 |
+
if underline is not None:
|
574 |
+
bits.append(f"\033[{4 if underline else 24}m")
|
575 |
+
if overline is not None:
|
576 |
+
bits.append(f"\033[{53 if overline else 55}m")
|
577 |
+
if italic is not None:
|
578 |
+
bits.append(f"\033[{3 if italic else 23}m")
|
579 |
+
if blink is not None:
|
580 |
+
bits.append(f"\033[{5 if blink else 25}m")
|
581 |
+
if reverse is not None:
|
582 |
+
bits.append(f"\033[{7 if reverse else 27}m")
|
583 |
+
if strikethrough is not None:
|
584 |
+
bits.append(f"\033[{9 if strikethrough else 29}m")
|
585 |
+
bits.append(text)
|
586 |
+
if reset:
|
587 |
+
bits.append(_ansi_reset_all)
|
588 |
+
return "".join(bits)
|
589 |
+
|
590 |
+
|
591 |
+
def unstyle(text: str) -> str:
|
592 |
+
"""Removes ANSI styling information from a string. Usually it's not
|
593 |
+
necessary to use this function as Click's echo function will
|
594 |
+
automatically remove styling if necessary.
|
595 |
+
|
596 |
+
.. versionadded:: 2.0
|
597 |
+
|
598 |
+
:param text: the text to remove style information from.
|
599 |
+
"""
|
600 |
+
return strip_ansi(text)
|
601 |
+
|
602 |
+
|
603 |
+
def secho(
|
604 |
+
message: t.Optional[t.Any] = None,
|
605 |
+
file: t.Optional[t.IO[t.AnyStr]] = None,
|
606 |
+
nl: bool = True,
|
607 |
+
err: bool = False,
|
608 |
+
color: t.Optional[bool] = None,
|
609 |
+
**styles: t.Any,
|
610 |
+
) -> None:
|
611 |
+
"""This function combines :func:`echo` and :func:`style` into one
|
612 |
+
call. As such the following two calls are the same::
|
613 |
+
|
614 |
+
click.secho('Hello World!', fg='green')
|
615 |
+
click.echo(click.style('Hello World!', fg='green'))
|
616 |
+
|
617 |
+
All keyword arguments are forwarded to the underlying functions
|
618 |
+
depending on which one they go with.
|
619 |
+
|
620 |
+
Non-string types will be converted to :class:`str`. However,
|
621 |
+
:class:`bytes` are passed directly to :meth:`echo` without applying
|
622 |
+
style. If you want to style bytes that represent text, call
|
623 |
+
:meth:`bytes.decode` first.
|
624 |
+
|
625 |
+
.. versionchanged:: 8.0
|
626 |
+
A non-string ``message`` is converted to a string. Bytes are
|
627 |
+
passed through without style applied.
|
628 |
+
|
629 |
+
.. versionadded:: 2.0
|
630 |
+
"""
|
631 |
+
if message is not None and not isinstance(message, (bytes, bytearray)):
|
632 |
+
message = style(message, **styles)
|
633 |
+
|
634 |
+
return echo(message, file=file, nl=nl, err=err, color=color)
|
635 |
+
|
636 |
+
|
637 |
+
def edit(
|
638 |
+
text: t.Optional[t.AnyStr] = None,
|
639 |
+
editor: t.Optional[str] = None,
|
640 |
+
env: t.Optional[t.Mapping[str, str]] = None,
|
641 |
+
require_save: bool = True,
|
642 |
+
extension: str = ".txt",
|
643 |
+
filename: t.Optional[str] = None,
|
644 |
+
) -> t.Optional[t.AnyStr]:
|
645 |
+
r"""Edits the given text in the defined editor. If an editor is given
|
646 |
+
(should be the full path to the executable but the regular operating
|
647 |
+
system search path is used for finding the executable) it overrides
|
648 |
+
the detected editor. Optionally, some environment variables can be
|
649 |
+
used. If the editor is closed without changes, `None` is returned. In
|
650 |
+
case a file is edited directly the return value is always `None` and
|
651 |
+
`require_save` and `extension` are ignored.
|
652 |
+
|
653 |
+
If the editor cannot be opened a :exc:`UsageError` is raised.
|
654 |
+
|
655 |
+
Note for Windows: to simplify cross-platform usage, the newlines are
|
656 |
+
automatically converted from POSIX to Windows and vice versa. As such,
|
657 |
+
the message here will have ``\n`` as newline markers.
|
658 |
+
|
659 |
+
:param text: the text to edit.
|
660 |
+
:param editor: optionally the editor to use. Defaults to automatic
|
661 |
+
detection.
|
662 |
+
:param env: environment variables to forward to the editor.
|
663 |
+
:param require_save: if this is true, then not saving in the editor
|
664 |
+
will make the return value become `None`.
|
665 |
+
:param extension: the extension to tell the editor about. This defaults
|
666 |
+
to `.txt` but changing this might change syntax
|
667 |
+
highlighting.
|
668 |
+
:param filename: if provided it will edit this file instead of the
|
669 |
+
provided text contents. It will not use a temporary
|
670 |
+
file as an indirection in that case.
|
671 |
+
"""
|
672 |
+
from ._termui_impl import Editor
|
673 |
+
|
674 |
+
ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
|
675 |
+
|
676 |
+
if filename is None:
|
677 |
+
return ed.edit(text)
|
678 |
+
|
679 |
+
ed.edit_file(filename)
|
680 |
+
return None
|
681 |
+
|
682 |
+
|
683 |
+
def launch(url: str, wait: bool = False, locate: bool = False) -> int:
|
684 |
+
"""This function launches the given URL (or filename) in the default
|
685 |
+
viewer application for this file type. If this is an executable, it
|
686 |
+
might launch the executable in a new session. The return value is
|
687 |
+
the exit code of the launched application. Usually, ``0`` indicates
|
688 |
+
success.
|
689 |
+
|
690 |
+
Examples::
|
691 |
+
|
692 |
+
click.launch('https://click.palletsprojects.com/')
|
693 |
+
click.launch('/my/downloaded/file', locate=True)
|
694 |
+
|
695 |
+
.. versionadded:: 2.0
|
696 |
+
|
697 |
+
:param url: URL or filename of the thing to launch.
|
698 |
+
:param wait: Wait for the program to exit before returning. This
|
699 |
+
only works if the launched program blocks. In particular,
|
700 |
+
``xdg-open`` on Linux does not block.
|
701 |
+
:param locate: if this is set to `True` then instead of launching the
|
702 |
+
application associated with the URL it will attempt to
|
703 |
+
launch a file manager with the file located. This
|
704 |
+
might have weird effects if the URL does not point to
|
705 |
+
the filesystem.
|
706 |
+
"""
|
707 |
+
from ._termui_impl import open_url
|
708 |
+
|
709 |
+
return open_url(url, wait=wait, locate=locate)
|
710 |
+
|
711 |
+
|
712 |
+
# If this is provided, getchar() calls into this instead. This is used
|
713 |
+
# for unittesting purposes.
|
714 |
+
_getchar: t.Optional[t.Callable[[bool], str]] = None
|
715 |
+
|
716 |
+
|
717 |
+
def getchar(echo: bool = False) -> str:
|
718 |
+
"""Fetches a single character from the terminal and returns it. This
|
719 |
+
will always return a unicode character and under certain rare
|
720 |
+
circumstances this might return more than one character. The
|
721 |
+
situations which more than one character is returned is when for
|
722 |
+
whatever reason multiple characters end up in the terminal buffer or
|
723 |
+
standard input was not actually a terminal.
|
724 |
+
|
725 |
+
Note that this will always read from the terminal, even if something
|
726 |
+
is piped into the standard input.
|
727 |
+
|
728 |
+
Note for Windows: in rare cases when typing non-ASCII characters, this
|
729 |
+
function might wait for a second character and then return both at once.
|
730 |
+
This is because certain Unicode characters look like special-key markers.
|
731 |
+
|
732 |
+
.. versionadded:: 2.0
|
733 |
+
|
734 |
+
:param echo: if set to `True`, the character read will also show up on
|
735 |
+
the terminal. The default is to not show it.
|
736 |
+
"""
|
737 |
+
global _getchar
|
738 |
+
|
739 |
+
if _getchar is None:
|
740 |
+
from ._termui_impl import getchar as f
|
741 |
+
|
742 |
+
_getchar = f
|
743 |
+
|
744 |
+
return _getchar(echo)
|
745 |
+
|
746 |
+
|
747 |
+
def raw_terminal() -> t.ContextManager[int]:
|
748 |
+
from ._termui_impl import raw_terminal as f
|
749 |
+
|
750 |
+
return f()
|
751 |
+
|
752 |
+
|
753 |
+
def pause(info: t.Optional[str] = None, err: bool = False) -> None:
|
754 |
+
"""This command stops execution and waits for the user to press any
|
755 |
+
key to continue. This is similar to the Windows batch "pause"
|
756 |
+
command. If the program is not run through a terminal, this command
|
757 |
+
will instead do nothing.
|
758 |
+
|
759 |
+
.. versionadded:: 2.0
|
760 |
+
|
761 |
+
.. versionadded:: 4.0
|
762 |
+
Added the `err` parameter.
|
763 |
+
|
764 |
+
:param info: The message to print before pausing. Defaults to
|
765 |
+
``"Press any key to continue..."``.
|
766 |
+
:param err: if set to message goes to ``stderr`` instead of
|
767 |
+
``stdout``, the same as with echo.
|
768 |
+
"""
|
769 |
+
if not isatty(sys.stdin) or not isatty(sys.stdout):
|
770 |
+
return
|
771 |
+
|
772 |
+
if info is None:
|
773 |
+
info = _("Press any key to continue...")
|
774 |
+
|
775 |
+
try:
|
776 |
+
if info:
|
777 |
+
echo(info, nl=False, err=err)
|
778 |
+
try:
|
779 |
+
getchar()
|
780 |
+
except (KeyboardInterrupt, EOFError):
|
781 |
+
pass
|
782 |
+
finally:
|
783 |
+
if info:
|
784 |
+
echo(err=err)
|
llmeval-env/lib/python3.10/site-packages/click/testing.py
ADDED
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import contextlib
|
2 |
+
import io
|
3 |
+
import os
|
4 |
+
import shlex
|
5 |
+
import shutil
|
6 |
+
import sys
|
7 |
+
import tempfile
|
8 |
+
import typing as t
|
9 |
+
from types import TracebackType
|
10 |
+
|
11 |
+
from . import formatting
|
12 |
+
from . import termui
|
13 |
+
from . import utils
|
14 |
+
from ._compat import _find_binary_reader
|
15 |
+
|
16 |
+
if t.TYPE_CHECKING:
|
17 |
+
from .core import BaseCommand
|
18 |
+
|
19 |
+
|
20 |
+
class EchoingStdin:
|
21 |
+
def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:
|
22 |
+
self._input = input
|
23 |
+
self._output = output
|
24 |
+
self._paused = False
|
25 |
+
|
26 |
+
def __getattr__(self, x: str) -> t.Any:
|
27 |
+
return getattr(self._input, x)
|
28 |
+
|
29 |
+
def _echo(self, rv: bytes) -> bytes:
|
30 |
+
if not self._paused:
|
31 |
+
self._output.write(rv)
|
32 |
+
|
33 |
+
return rv
|
34 |
+
|
35 |
+
def read(self, n: int = -1) -> bytes:
|
36 |
+
return self._echo(self._input.read(n))
|
37 |
+
|
38 |
+
def read1(self, n: int = -1) -> bytes:
|
39 |
+
return self._echo(self._input.read1(n)) # type: ignore
|
40 |
+
|
41 |
+
def readline(self, n: int = -1) -> bytes:
|
42 |
+
return self._echo(self._input.readline(n))
|
43 |
+
|
44 |
+
def readlines(self) -> t.List[bytes]:
|
45 |
+
return [self._echo(x) for x in self._input.readlines()]
|
46 |
+
|
47 |
+
def __iter__(self) -> t.Iterator[bytes]:
|
48 |
+
return iter(self._echo(x) for x in self._input)
|
49 |
+
|
50 |
+
def __repr__(self) -> str:
|
51 |
+
return repr(self._input)
|
52 |
+
|
53 |
+
|
54 |
+
@contextlib.contextmanager
|
55 |
+
def _pause_echo(stream: t.Optional[EchoingStdin]) -> t.Iterator[None]:
|
56 |
+
if stream is None:
|
57 |
+
yield
|
58 |
+
else:
|
59 |
+
stream._paused = True
|
60 |
+
yield
|
61 |
+
stream._paused = False
|
62 |
+
|
63 |
+
|
64 |
+
class _NamedTextIOWrapper(io.TextIOWrapper):
|
65 |
+
def __init__(
|
66 |
+
self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any
|
67 |
+
) -> None:
|
68 |
+
super().__init__(buffer, **kwargs)
|
69 |
+
self._name = name
|
70 |
+
self._mode = mode
|
71 |
+
|
72 |
+
@property
|
73 |
+
def name(self) -> str:
|
74 |
+
return self._name
|
75 |
+
|
76 |
+
@property
|
77 |
+
def mode(self) -> str:
|
78 |
+
return self._mode
|
79 |
+
|
80 |
+
|
81 |
+
def make_input_stream(
|
82 |
+
input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]], charset: str
|
83 |
+
) -> t.BinaryIO:
|
84 |
+
# Is already an input stream.
|
85 |
+
if hasattr(input, "read"):
|
86 |
+
rv = _find_binary_reader(t.cast(t.IO[t.Any], input))
|
87 |
+
|
88 |
+
if rv is not None:
|
89 |
+
return rv
|
90 |
+
|
91 |
+
raise TypeError("Could not find binary reader for input stream.")
|
92 |
+
|
93 |
+
if input is None:
|
94 |
+
input = b""
|
95 |
+
elif isinstance(input, str):
|
96 |
+
input = input.encode(charset)
|
97 |
+
|
98 |
+
return io.BytesIO(input)
|
99 |
+
|
100 |
+
|
101 |
+
class Result:
|
102 |
+
"""Holds the captured result of an invoked CLI script."""
|
103 |
+
|
104 |
+
def __init__(
|
105 |
+
self,
|
106 |
+
runner: "CliRunner",
|
107 |
+
stdout_bytes: bytes,
|
108 |
+
stderr_bytes: t.Optional[bytes],
|
109 |
+
return_value: t.Any,
|
110 |
+
exit_code: int,
|
111 |
+
exception: t.Optional[BaseException],
|
112 |
+
exc_info: t.Optional[
|
113 |
+
t.Tuple[t.Type[BaseException], BaseException, TracebackType]
|
114 |
+
] = None,
|
115 |
+
):
|
116 |
+
#: The runner that created the result
|
117 |
+
self.runner = runner
|
118 |
+
#: The standard output as bytes.
|
119 |
+
self.stdout_bytes = stdout_bytes
|
120 |
+
#: The standard error as bytes, or None if not available
|
121 |
+
self.stderr_bytes = stderr_bytes
|
122 |
+
#: The value returned from the invoked command.
|
123 |
+
#:
|
124 |
+
#: .. versionadded:: 8.0
|
125 |
+
self.return_value = return_value
|
126 |
+
#: The exit code as integer.
|
127 |
+
self.exit_code = exit_code
|
128 |
+
#: The exception that happened if one did.
|
129 |
+
self.exception = exception
|
130 |
+
#: The traceback
|
131 |
+
self.exc_info = exc_info
|
132 |
+
|
133 |
+
@property
|
134 |
+
def output(self) -> str:
|
135 |
+
"""The (standard) output as unicode string."""
|
136 |
+
return self.stdout
|
137 |
+
|
138 |
+
@property
|
139 |
+
def stdout(self) -> str:
|
140 |
+
"""The standard output as unicode string."""
|
141 |
+
return self.stdout_bytes.decode(self.runner.charset, "replace").replace(
|
142 |
+
"\r\n", "\n"
|
143 |
+
)
|
144 |
+
|
145 |
+
@property
|
146 |
+
def stderr(self) -> str:
|
147 |
+
"""The standard error as unicode string."""
|
148 |
+
if self.stderr_bytes is None:
|
149 |
+
raise ValueError("stderr not separately captured")
|
150 |
+
return self.stderr_bytes.decode(self.runner.charset, "replace").replace(
|
151 |
+
"\r\n", "\n"
|
152 |
+
)
|
153 |
+
|
154 |
+
def __repr__(self) -> str:
|
155 |
+
exc_str = repr(self.exception) if self.exception else "okay"
|
156 |
+
return f"<{type(self).__name__} {exc_str}>"
|
157 |
+
|
158 |
+
|
159 |
+
class CliRunner:
|
160 |
+
"""The CLI runner provides functionality to invoke a Click command line
|
161 |
+
script for unittesting purposes in a isolated environment. This only
|
162 |
+
works in single-threaded systems without any concurrency as it changes the
|
163 |
+
global interpreter state.
|
164 |
+
|
165 |
+
:param charset: the character set for the input and output data.
|
166 |
+
:param env: a dictionary with environment variables for overriding.
|
167 |
+
:param echo_stdin: if this is set to `True`, then reading from stdin writes
|
168 |
+
to stdout. This is useful for showing examples in
|
169 |
+
some circumstances. Note that regular prompts
|
170 |
+
will automatically echo the input.
|
171 |
+
:param mix_stderr: if this is set to `False`, then stdout and stderr are
|
172 |
+
preserved as independent streams. This is useful for
|
173 |
+
Unix-philosophy apps that have predictable stdout and
|
174 |
+
noisy stderr, such that each may be measured
|
175 |
+
independently
|
176 |
+
"""
|
177 |
+
|
178 |
+
def __init__(
|
179 |
+
self,
|
180 |
+
charset: str = "utf-8",
|
181 |
+
env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,
|
182 |
+
echo_stdin: bool = False,
|
183 |
+
mix_stderr: bool = True,
|
184 |
+
) -> None:
|
185 |
+
self.charset = charset
|
186 |
+
self.env: t.Mapping[str, t.Optional[str]] = env or {}
|
187 |
+
self.echo_stdin = echo_stdin
|
188 |
+
self.mix_stderr = mix_stderr
|
189 |
+
|
190 |
+
def get_default_prog_name(self, cli: "BaseCommand") -> str:
|
191 |
+
"""Given a command object it will return the default program name
|
192 |
+
for it. The default is the `name` attribute or ``"root"`` if not
|
193 |
+
set.
|
194 |
+
"""
|
195 |
+
return cli.name or "root"
|
196 |
+
|
197 |
+
def make_env(
|
198 |
+
self, overrides: t.Optional[t.Mapping[str, t.Optional[str]]] = None
|
199 |
+
) -> t.Mapping[str, t.Optional[str]]:
|
200 |
+
"""Returns the environment overrides for invoking a script."""
|
201 |
+
rv = dict(self.env)
|
202 |
+
if overrides:
|
203 |
+
rv.update(overrides)
|
204 |
+
return rv
|
205 |
+
|
206 |
+
@contextlib.contextmanager
|
207 |
+
def isolation(
|
208 |
+
self,
|
209 |
+
input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,
|
210 |
+
env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,
|
211 |
+
color: bool = False,
|
212 |
+
) -> t.Iterator[t.Tuple[io.BytesIO, t.Optional[io.BytesIO]]]:
|
213 |
+
"""A context manager that sets up the isolation for invoking of a
|
214 |
+
command line tool. This sets up stdin with the given input data
|
215 |
+
and `os.environ` with the overrides from the given dictionary.
|
216 |
+
This also rebinds some internals in Click to be mocked (like the
|
217 |
+
prompt functionality).
|
218 |
+
|
219 |
+
This is automatically done in the :meth:`invoke` method.
|
220 |
+
|
221 |
+
:param input: the input stream to put into sys.stdin.
|
222 |
+
:param env: the environment overrides as dictionary.
|
223 |
+
:param color: whether the output should contain color codes. The
|
224 |
+
application can still override this explicitly.
|
225 |
+
|
226 |
+
.. versionchanged:: 8.0
|
227 |
+
``stderr`` is opened with ``errors="backslashreplace"``
|
228 |
+
instead of the default ``"strict"``.
|
229 |
+
|
230 |
+
.. versionchanged:: 4.0
|
231 |
+
Added the ``color`` parameter.
|
232 |
+
"""
|
233 |
+
bytes_input = make_input_stream(input, self.charset)
|
234 |
+
echo_input = None
|
235 |
+
|
236 |
+
old_stdin = sys.stdin
|
237 |
+
old_stdout = sys.stdout
|
238 |
+
old_stderr = sys.stderr
|
239 |
+
old_forced_width = formatting.FORCED_WIDTH
|
240 |
+
formatting.FORCED_WIDTH = 80
|
241 |
+
|
242 |
+
env = self.make_env(env)
|
243 |
+
|
244 |
+
bytes_output = io.BytesIO()
|
245 |
+
|
246 |
+
if self.echo_stdin:
|
247 |
+
bytes_input = echo_input = t.cast(
|
248 |
+
t.BinaryIO, EchoingStdin(bytes_input, bytes_output)
|
249 |
+
)
|
250 |
+
|
251 |
+
sys.stdin = text_input = _NamedTextIOWrapper(
|
252 |
+
bytes_input, encoding=self.charset, name="<stdin>", mode="r"
|
253 |
+
)
|
254 |
+
|
255 |
+
if self.echo_stdin:
|
256 |
+
# Force unbuffered reads, otherwise TextIOWrapper reads a
|
257 |
+
# large chunk which is echoed early.
|
258 |
+
text_input._CHUNK_SIZE = 1 # type: ignore
|
259 |
+
|
260 |
+
sys.stdout = _NamedTextIOWrapper(
|
261 |
+
bytes_output, encoding=self.charset, name="<stdout>", mode="w"
|
262 |
+
)
|
263 |
+
|
264 |
+
bytes_error = None
|
265 |
+
if self.mix_stderr:
|
266 |
+
sys.stderr = sys.stdout
|
267 |
+
else:
|
268 |
+
bytes_error = io.BytesIO()
|
269 |
+
sys.stderr = _NamedTextIOWrapper(
|
270 |
+
bytes_error,
|
271 |
+
encoding=self.charset,
|
272 |
+
name="<stderr>",
|
273 |
+
mode="w",
|
274 |
+
errors="backslashreplace",
|
275 |
+
)
|
276 |
+
|
277 |
+
@_pause_echo(echo_input) # type: ignore
|
278 |
+
def visible_input(prompt: t.Optional[str] = None) -> str:
|
279 |
+
sys.stdout.write(prompt or "")
|
280 |
+
val = text_input.readline().rstrip("\r\n")
|
281 |
+
sys.stdout.write(f"{val}\n")
|
282 |
+
sys.stdout.flush()
|
283 |
+
return val
|
284 |
+
|
285 |
+
@_pause_echo(echo_input) # type: ignore
|
286 |
+
def hidden_input(prompt: t.Optional[str] = None) -> str:
|
287 |
+
sys.stdout.write(f"{prompt or ''}\n")
|
288 |
+
sys.stdout.flush()
|
289 |
+
return text_input.readline().rstrip("\r\n")
|
290 |
+
|
291 |
+
@_pause_echo(echo_input) # type: ignore
|
292 |
+
def _getchar(echo: bool) -> str:
|
293 |
+
char = sys.stdin.read(1)
|
294 |
+
|
295 |
+
if echo:
|
296 |
+
sys.stdout.write(char)
|
297 |
+
|
298 |
+
sys.stdout.flush()
|
299 |
+
return char
|
300 |
+
|
301 |
+
default_color = color
|
302 |
+
|
303 |
+
def should_strip_ansi(
|
304 |
+
stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None
|
305 |
+
) -> bool:
|
306 |
+
if color is None:
|
307 |
+
return not default_color
|
308 |
+
return not color
|
309 |
+
|
310 |
+
old_visible_prompt_func = termui.visible_prompt_func
|
311 |
+
old_hidden_prompt_func = termui.hidden_prompt_func
|
312 |
+
old__getchar_func = termui._getchar
|
313 |
+
old_should_strip_ansi = utils.should_strip_ansi # type: ignore
|
314 |
+
termui.visible_prompt_func = visible_input
|
315 |
+
termui.hidden_prompt_func = hidden_input
|
316 |
+
termui._getchar = _getchar
|
317 |
+
utils.should_strip_ansi = should_strip_ansi # type: ignore
|
318 |
+
|
319 |
+
old_env = {}
|
320 |
+
try:
|
321 |
+
for key, value in env.items():
|
322 |
+
old_env[key] = os.environ.get(key)
|
323 |
+
if value is None:
|
324 |
+
try:
|
325 |
+
del os.environ[key]
|
326 |
+
except Exception:
|
327 |
+
pass
|
328 |
+
else:
|
329 |
+
os.environ[key] = value
|
330 |
+
yield (bytes_output, bytes_error)
|
331 |
+
finally:
|
332 |
+
for key, value in old_env.items():
|
333 |
+
if value is None:
|
334 |
+
try:
|
335 |
+
del os.environ[key]
|
336 |
+
except Exception:
|
337 |
+
pass
|
338 |
+
else:
|
339 |
+
os.environ[key] = value
|
340 |
+
sys.stdout = old_stdout
|
341 |
+
sys.stderr = old_stderr
|
342 |
+
sys.stdin = old_stdin
|
343 |
+
termui.visible_prompt_func = old_visible_prompt_func
|
344 |
+
termui.hidden_prompt_func = old_hidden_prompt_func
|
345 |
+
termui._getchar = old__getchar_func
|
346 |
+
utils.should_strip_ansi = old_should_strip_ansi # type: ignore
|
347 |
+
formatting.FORCED_WIDTH = old_forced_width
|
348 |
+
|
349 |
+
def invoke(
|
350 |
+
self,
|
351 |
+
cli: "BaseCommand",
|
352 |
+
args: t.Optional[t.Union[str, t.Sequence[str]]] = None,
|
353 |
+
input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,
|
354 |
+
env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,
|
355 |
+
catch_exceptions: bool = True,
|
356 |
+
color: bool = False,
|
357 |
+
**extra: t.Any,
|
358 |
+
) -> Result:
|
359 |
+
"""Invokes a command in an isolated environment. The arguments are
|
360 |
+
forwarded directly to the command line script, the `extra` keyword
|
361 |
+
arguments are passed to the :meth:`~clickpkg.Command.main` function of
|
362 |
+
the command.
|
363 |
+
|
364 |
+
This returns a :class:`Result` object.
|
365 |
+
|
366 |
+
:param cli: the command to invoke
|
367 |
+
:param args: the arguments to invoke. It may be given as an iterable
|
368 |
+
or a string. When given as string it will be interpreted
|
369 |
+
as a Unix shell command. More details at
|
370 |
+
:func:`shlex.split`.
|
371 |
+
:param input: the input data for `sys.stdin`.
|
372 |
+
:param env: the environment overrides.
|
373 |
+
:param catch_exceptions: Whether to catch any other exceptions than
|
374 |
+
``SystemExit``.
|
375 |
+
:param extra: the keyword arguments to pass to :meth:`main`.
|
376 |
+
:param color: whether the output should contain color codes. The
|
377 |
+
application can still override this explicitly.
|
378 |
+
|
379 |
+
.. versionchanged:: 8.0
|
380 |
+
The result object has the ``return_value`` attribute with
|
381 |
+
the value returned from the invoked command.
|
382 |
+
|
383 |
+
.. versionchanged:: 4.0
|
384 |
+
Added the ``color`` parameter.
|
385 |
+
|
386 |
+
.. versionchanged:: 3.0
|
387 |
+
Added the ``catch_exceptions`` parameter.
|
388 |
+
|
389 |
+
.. versionchanged:: 3.0
|
390 |
+
The result object has the ``exc_info`` attribute with the
|
391 |
+
traceback if available.
|
392 |
+
"""
|
393 |
+
exc_info = None
|
394 |
+
with self.isolation(input=input, env=env, color=color) as outstreams:
|
395 |
+
return_value = None
|
396 |
+
exception: t.Optional[BaseException] = None
|
397 |
+
exit_code = 0
|
398 |
+
|
399 |
+
if isinstance(args, str):
|
400 |
+
args = shlex.split(args)
|
401 |
+
|
402 |
+
try:
|
403 |
+
prog_name = extra.pop("prog_name")
|
404 |
+
except KeyError:
|
405 |
+
prog_name = self.get_default_prog_name(cli)
|
406 |
+
|
407 |
+
try:
|
408 |
+
return_value = cli.main(args=args or (), prog_name=prog_name, **extra)
|
409 |
+
except SystemExit as e:
|
410 |
+
exc_info = sys.exc_info()
|
411 |
+
e_code = t.cast(t.Optional[t.Union[int, t.Any]], e.code)
|
412 |
+
|
413 |
+
if e_code is None:
|
414 |
+
e_code = 0
|
415 |
+
|
416 |
+
if e_code != 0:
|
417 |
+
exception = e
|
418 |
+
|
419 |
+
if not isinstance(e_code, int):
|
420 |
+
sys.stdout.write(str(e_code))
|
421 |
+
sys.stdout.write("\n")
|
422 |
+
e_code = 1
|
423 |
+
|
424 |
+
exit_code = e_code
|
425 |
+
|
426 |
+
except Exception as e:
|
427 |
+
if not catch_exceptions:
|
428 |
+
raise
|
429 |
+
exception = e
|
430 |
+
exit_code = 1
|
431 |
+
exc_info = sys.exc_info()
|
432 |
+
finally:
|
433 |
+
sys.stdout.flush()
|
434 |
+
stdout = outstreams[0].getvalue()
|
435 |
+
if self.mix_stderr:
|
436 |
+
stderr = None
|
437 |
+
else:
|
438 |
+
stderr = outstreams[1].getvalue() # type: ignore
|
439 |
+
|
440 |
+
return Result(
|
441 |
+
runner=self,
|
442 |
+
stdout_bytes=stdout,
|
443 |
+
stderr_bytes=stderr,
|
444 |
+
return_value=return_value,
|
445 |
+
exit_code=exit_code,
|
446 |
+
exception=exception,
|
447 |
+
exc_info=exc_info, # type: ignore
|
448 |
+
)
|
449 |
+
|
450 |
+
@contextlib.contextmanager
|
451 |
+
def isolated_filesystem(
|
452 |
+
self, temp_dir: t.Optional[t.Union[str, "os.PathLike[str]"]] = None
|
453 |
+
) -> t.Iterator[str]:
|
454 |
+
"""A context manager that creates a temporary directory and
|
455 |
+
changes the current working directory to it. This isolates tests
|
456 |
+
that affect the contents of the CWD to prevent them from
|
457 |
+
interfering with each other.
|
458 |
+
|
459 |
+
:param temp_dir: Create the temporary directory under this
|
460 |
+
directory. If given, the created directory is not removed
|
461 |
+
when exiting.
|
462 |
+
|
463 |
+
.. versionchanged:: 8.0
|
464 |
+
Added the ``temp_dir`` parameter.
|
465 |
+
"""
|
466 |
+
cwd = os.getcwd()
|
467 |
+
dt = tempfile.mkdtemp(dir=temp_dir)
|
468 |
+
os.chdir(dt)
|
469 |
+
|
470 |
+
try:
|
471 |
+
yield dt
|
472 |
+
finally:
|
473 |
+
os.chdir(cwd)
|
474 |
+
|
475 |
+
if temp_dir is None:
|
476 |
+
try:
|
477 |
+
shutil.rmtree(dt)
|
478 |
+
except OSError: # noqa: B014
|
479 |
+
pass
|
llmeval-env/lib/python3.10/site-packages/click/utils.py
ADDED
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import sys
|
4 |
+
import typing as t
|
5 |
+
from functools import update_wrapper
|
6 |
+
from types import ModuleType
|
7 |
+
from types import TracebackType
|
8 |
+
|
9 |
+
from ._compat import _default_text_stderr
|
10 |
+
from ._compat import _default_text_stdout
|
11 |
+
from ._compat import _find_binary_writer
|
12 |
+
from ._compat import auto_wrap_for_ansi
|
13 |
+
from ._compat import binary_streams
|
14 |
+
from ._compat import open_stream
|
15 |
+
from ._compat import should_strip_ansi
|
16 |
+
from ._compat import strip_ansi
|
17 |
+
from ._compat import text_streams
|
18 |
+
from ._compat import WIN
|
19 |
+
from .globals import resolve_color_default
|
20 |
+
|
21 |
+
if t.TYPE_CHECKING:
|
22 |
+
import typing_extensions as te
|
23 |
+
|
24 |
+
P = te.ParamSpec("P")
|
25 |
+
|
26 |
+
R = t.TypeVar("R")
|
27 |
+
|
28 |
+
|
29 |
+
def _posixify(name: str) -> str:
|
30 |
+
return "-".join(name.split()).lower()
|
31 |
+
|
32 |
+
|
33 |
+
def safecall(func: "t.Callable[P, R]") -> "t.Callable[P, t.Optional[R]]":
|
34 |
+
"""Wraps a function so that it swallows exceptions."""
|
35 |
+
|
36 |
+
def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Optional[R]:
|
37 |
+
try:
|
38 |
+
return func(*args, **kwargs)
|
39 |
+
except Exception:
|
40 |
+
pass
|
41 |
+
return None
|
42 |
+
|
43 |
+
return update_wrapper(wrapper, func)
|
44 |
+
|
45 |
+
|
46 |
+
def make_str(value: t.Any) -> str:
|
47 |
+
"""Converts a value into a valid string."""
|
48 |
+
if isinstance(value, bytes):
|
49 |
+
try:
|
50 |
+
return value.decode(sys.getfilesystemencoding())
|
51 |
+
except UnicodeError:
|
52 |
+
return value.decode("utf-8", "replace")
|
53 |
+
return str(value)
|
54 |
+
|
55 |
+
|
56 |
+
def make_default_short_help(help: str, max_length: int = 45) -> str:
|
57 |
+
"""Returns a condensed version of help string."""
|
58 |
+
# Consider only the first paragraph.
|
59 |
+
paragraph_end = help.find("\n\n")
|
60 |
+
|
61 |
+
if paragraph_end != -1:
|
62 |
+
help = help[:paragraph_end]
|
63 |
+
|
64 |
+
# Collapse newlines, tabs, and spaces.
|
65 |
+
words = help.split()
|
66 |
+
|
67 |
+
if not words:
|
68 |
+
return ""
|
69 |
+
|
70 |
+
# The first paragraph started with a "no rewrap" marker, ignore it.
|
71 |
+
if words[0] == "\b":
|
72 |
+
words = words[1:]
|
73 |
+
|
74 |
+
total_length = 0
|
75 |
+
last_index = len(words) - 1
|
76 |
+
|
77 |
+
for i, word in enumerate(words):
|
78 |
+
total_length += len(word) + (i > 0)
|
79 |
+
|
80 |
+
if total_length > max_length: # too long, truncate
|
81 |
+
break
|
82 |
+
|
83 |
+
if word[-1] == ".": # sentence end, truncate without "..."
|
84 |
+
return " ".join(words[: i + 1])
|
85 |
+
|
86 |
+
if total_length == max_length and i != last_index:
|
87 |
+
break # not at sentence end, truncate with "..."
|
88 |
+
else:
|
89 |
+
return " ".join(words) # no truncation needed
|
90 |
+
|
91 |
+
# Account for the length of the suffix.
|
92 |
+
total_length += len("...")
|
93 |
+
|
94 |
+
# remove words until the length is short enough
|
95 |
+
while i > 0:
|
96 |
+
total_length -= len(words[i]) + (i > 0)
|
97 |
+
|
98 |
+
if total_length <= max_length:
|
99 |
+
break
|
100 |
+
|
101 |
+
i -= 1
|
102 |
+
|
103 |
+
return " ".join(words[:i]) + "..."
|
104 |
+
|
105 |
+
|
106 |
+
class LazyFile:
|
107 |
+
"""A lazy file works like a regular file but it does not fully open
|
108 |
+
the file but it does perform some basic checks early to see if the
|
109 |
+
filename parameter does make sense. This is useful for safely opening
|
110 |
+
files for writing.
|
111 |
+
"""
|
112 |
+
|
113 |
+
def __init__(
|
114 |
+
self,
|
115 |
+
filename: t.Union[str, "os.PathLike[str]"],
|
116 |
+
mode: str = "r",
|
117 |
+
encoding: t.Optional[str] = None,
|
118 |
+
errors: t.Optional[str] = "strict",
|
119 |
+
atomic: bool = False,
|
120 |
+
):
|
121 |
+
self.name: str = os.fspath(filename)
|
122 |
+
self.mode = mode
|
123 |
+
self.encoding = encoding
|
124 |
+
self.errors = errors
|
125 |
+
self.atomic = atomic
|
126 |
+
self._f: t.Optional[t.IO[t.Any]]
|
127 |
+
self.should_close: bool
|
128 |
+
|
129 |
+
if self.name == "-":
|
130 |
+
self._f, self.should_close = open_stream(filename, mode, encoding, errors)
|
131 |
+
else:
|
132 |
+
if "r" in mode:
|
133 |
+
# Open and close the file in case we're opening it for
|
134 |
+
# reading so that we can catch at least some errors in
|
135 |
+
# some cases early.
|
136 |
+
open(filename, mode).close()
|
137 |
+
self._f = None
|
138 |
+
self.should_close = True
|
139 |
+
|
140 |
+
def __getattr__(self, name: str) -> t.Any:
|
141 |
+
return getattr(self.open(), name)
|
142 |
+
|
143 |
+
def __repr__(self) -> str:
|
144 |
+
if self._f is not None:
|
145 |
+
return repr(self._f)
|
146 |
+
return f"<unopened file '{format_filename(self.name)}' {self.mode}>"
|
147 |
+
|
148 |
+
def open(self) -> t.IO[t.Any]:
|
149 |
+
"""Opens the file if it's not yet open. This call might fail with
|
150 |
+
a :exc:`FileError`. Not handling this error will produce an error
|
151 |
+
that Click shows.
|
152 |
+
"""
|
153 |
+
if self._f is not None:
|
154 |
+
return self._f
|
155 |
+
try:
|
156 |
+
rv, self.should_close = open_stream(
|
157 |
+
self.name, self.mode, self.encoding, self.errors, atomic=self.atomic
|
158 |
+
)
|
159 |
+
except OSError as e: # noqa: E402
|
160 |
+
from .exceptions import FileError
|
161 |
+
|
162 |
+
raise FileError(self.name, hint=e.strerror) from e
|
163 |
+
self._f = rv
|
164 |
+
return rv
|
165 |
+
|
166 |
+
def close(self) -> None:
|
167 |
+
"""Closes the underlying file, no matter what."""
|
168 |
+
if self._f is not None:
|
169 |
+
self._f.close()
|
170 |
+
|
171 |
+
def close_intelligently(self) -> None:
|
172 |
+
"""This function only closes the file if it was opened by the lazy
|
173 |
+
file wrapper. For instance this will never close stdin.
|
174 |
+
"""
|
175 |
+
if self.should_close:
|
176 |
+
self.close()
|
177 |
+
|
178 |
+
def __enter__(self) -> "LazyFile":
|
179 |
+
return self
|
180 |
+
|
181 |
+
def __exit__(
|
182 |
+
self,
|
183 |
+
exc_type: t.Optional[t.Type[BaseException]],
|
184 |
+
exc_value: t.Optional[BaseException],
|
185 |
+
tb: t.Optional[TracebackType],
|
186 |
+
) -> None:
|
187 |
+
self.close_intelligently()
|
188 |
+
|
189 |
+
def __iter__(self) -> t.Iterator[t.AnyStr]:
|
190 |
+
self.open()
|
191 |
+
return iter(self._f) # type: ignore
|
192 |
+
|
193 |
+
|
194 |
+
class KeepOpenFile:
|
195 |
+
def __init__(self, file: t.IO[t.Any]) -> None:
|
196 |
+
self._file: t.IO[t.Any] = file
|
197 |
+
|
198 |
+
def __getattr__(self, name: str) -> t.Any:
|
199 |
+
return getattr(self._file, name)
|
200 |
+
|
201 |
+
def __enter__(self) -> "KeepOpenFile":
|
202 |
+
return self
|
203 |
+
|
204 |
+
def __exit__(
|
205 |
+
self,
|
206 |
+
exc_type: t.Optional[t.Type[BaseException]],
|
207 |
+
exc_value: t.Optional[BaseException],
|
208 |
+
tb: t.Optional[TracebackType],
|
209 |
+
) -> None:
|
210 |
+
pass
|
211 |
+
|
212 |
+
def __repr__(self) -> str:
|
213 |
+
return repr(self._file)
|
214 |
+
|
215 |
+
def __iter__(self) -> t.Iterator[t.AnyStr]:
|
216 |
+
return iter(self._file)
|
217 |
+
|
218 |
+
|
219 |
+
def echo(
|
220 |
+
message: t.Optional[t.Any] = None,
|
221 |
+
file: t.Optional[t.IO[t.Any]] = None,
|
222 |
+
nl: bool = True,
|
223 |
+
err: bool = False,
|
224 |
+
color: t.Optional[bool] = None,
|
225 |
+
) -> None:
|
226 |
+
"""Print a message and newline to stdout or a file. This should be
|
227 |
+
used instead of :func:`print` because it provides better support
|
228 |
+
for different data, files, and environments.
|
229 |
+
|
230 |
+
Compared to :func:`print`, this does the following:
|
231 |
+
|
232 |
+
- Ensures that the output encoding is not misconfigured on Linux.
|
233 |
+
- Supports Unicode in the Windows console.
|
234 |
+
- Supports writing to binary outputs, and supports writing bytes
|
235 |
+
to text outputs.
|
236 |
+
- Supports colors and styles on Windows.
|
237 |
+
- Removes ANSI color and style codes if the output does not look
|
238 |
+
like an interactive terminal.
|
239 |
+
- Always flushes the output.
|
240 |
+
|
241 |
+
:param message: The string or bytes to output. Other objects are
|
242 |
+
converted to strings.
|
243 |
+
:param file: The file to write to. Defaults to ``stdout``.
|
244 |
+
:param err: Write to ``stderr`` instead of ``stdout``.
|
245 |
+
:param nl: Print a newline after the message. Enabled by default.
|
246 |
+
:param color: Force showing or hiding colors and other styles. By
|
247 |
+
default Click will remove color if the output does not look like
|
248 |
+
an interactive terminal.
|
249 |
+
|
250 |
+
.. versionchanged:: 6.0
|
251 |
+
Support Unicode output on the Windows console. Click does not
|
252 |
+
modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``
|
253 |
+
will still not support Unicode.
|
254 |
+
|
255 |
+
.. versionchanged:: 4.0
|
256 |
+
Added the ``color`` parameter.
|
257 |
+
|
258 |
+
.. versionadded:: 3.0
|
259 |
+
Added the ``err`` parameter.
|
260 |
+
|
261 |
+
.. versionchanged:: 2.0
|
262 |
+
Support colors on Windows if colorama is installed.
|
263 |
+
"""
|
264 |
+
if file is None:
|
265 |
+
if err:
|
266 |
+
file = _default_text_stderr()
|
267 |
+
else:
|
268 |
+
file = _default_text_stdout()
|
269 |
+
|
270 |
+
# There are no standard streams attached to write to. For example,
|
271 |
+
# pythonw on Windows.
|
272 |
+
if file is None:
|
273 |
+
return
|
274 |
+
|
275 |
+
# Convert non bytes/text into the native string type.
|
276 |
+
if message is not None and not isinstance(message, (str, bytes, bytearray)):
|
277 |
+
out: t.Optional[t.Union[str, bytes]] = str(message)
|
278 |
+
else:
|
279 |
+
out = message
|
280 |
+
|
281 |
+
if nl:
|
282 |
+
out = out or ""
|
283 |
+
if isinstance(out, str):
|
284 |
+
out += "\n"
|
285 |
+
else:
|
286 |
+
out += b"\n"
|
287 |
+
|
288 |
+
if not out:
|
289 |
+
file.flush()
|
290 |
+
return
|
291 |
+
|
292 |
+
# If there is a message and the value looks like bytes, we manually
|
293 |
+
# need to find the binary stream and write the message in there.
|
294 |
+
# This is done separately so that most stream types will work as you
|
295 |
+
# would expect. Eg: you can write to StringIO for other cases.
|
296 |
+
if isinstance(out, (bytes, bytearray)):
|
297 |
+
binary_file = _find_binary_writer(file)
|
298 |
+
|
299 |
+
if binary_file is not None:
|
300 |
+
file.flush()
|
301 |
+
binary_file.write(out)
|
302 |
+
binary_file.flush()
|
303 |
+
return
|
304 |
+
|
305 |
+
# ANSI style code support. For no message or bytes, nothing happens.
|
306 |
+
# When outputting to a file instead of a terminal, strip codes.
|
307 |
+
else:
|
308 |
+
color = resolve_color_default(color)
|
309 |
+
|
310 |
+
if should_strip_ansi(file, color):
|
311 |
+
out = strip_ansi(out)
|
312 |
+
elif WIN:
|
313 |
+
if auto_wrap_for_ansi is not None:
|
314 |
+
file = auto_wrap_for_ansi(file) # type: ignore
|
315 |
+
elif not color:
|
316 |
+
out = strip_ansi(out)
|
317 |
+
|
318 |
+
file.write(out) # type: ignore
|
319 |
+
file.flush()
|
320 |
+
|
321 |
+
|
322 |
+
def get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> t.BinaryIO:
|
323 |
+
"""Returns a system stream for byte processing.
|
324 |
+
|
325 |
+
:param name: the name of the stream to open. Valid names are ``'stdin'``,
|
326 |
+
``'stdout'`` and ``'stderr'``
|
327 |
+
"""
|
328 |
+
opener = binary_streams.get(name)
|
329 |
+
if opener is None:
|
330 |
+
raise TypeError(f"Unknown standard stream '{name}'")
|
331 |
+
return opener()
|
332 |
+
|
333 |
+
|
334 |
+
def get_text_stream(
|
335 |
+
name: "te.Literal['stdin', 'stdout', 'stderr']",
|
336 |
+
encoding: t.Optional[str] = None,
|
337 |
+
errors: t.Optional[str] = "strict",
|
338 |
+
) -> t.TextIO:
|
339 |
+
"""Returns a system stream for text processing. This usually returns
|
340 |
+
a wrapped stream around a binary stream returned from
|
341 |
+
:func:`get_binary_stream` but it also can take shortcuts for already
|
342 |
+
correctly configured streams.
|
343 |
+
|
344 |
+
:param name: the name of the stream to open. Valid names are ``'stdin'``,
|
345 |
+
``'stdout'`` and ``'stderr'``
|
346 |
+
:param encoding: overrides the detected default encoding.
|
347 |
+
:param errors: overrides the default error mode.
|
348 |
+
"""
|
349 |
+
opener = text_streams.get(name)
|
350 |
+
if opener is None:
|
351 |
+
raise TypeError(f"Unknown standard stream '{name}'")
|
352 |
+
return opener(encoding, errors)
|
353 |
+
|
354 |
+
|
355 |
+
def open_file(
|
356 |
+
filename: str,
|
357 |
+
mode: str = "r",
|
358 |
+
encoding: t.Optional[str] = None,
|
359 |
+
errors: t.Optional[str] = "strict",
|
360 |
+
lazy: bool = False,
|
361 |
+
atomic: bool = False,
|
362 |
+
) -> t.IO[t.Any]:
|
363 |
+
"""Open a file, with extra behavior to handle ``'-'`` to indicate
|
364 |
+
a standard stream, lazy open on write, and atomic write. Similar to
|
365 |
+
the behavior of the :class:`~click.File` param type.
|
366 |
+
|
367 |
+
If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is
|
368 |
+
wrapped so that using it in a context manager will not close it.
|
369 |
+
This makes it possible to use the function without accidentally
|
370 |
+
closing a standard stream:
|
371 |
+
|
372 |
+
.. code-block:: python
|
373 |
+
|
374 |
+
with open_file(filename) as f:
|
375 |
+
...
|
376 |
+
|
377 |
+
:param filename: The name of the file to open, or ``'-'`` for
|
378 |
+
``stdin``/``stdout``.
|
379 |
+
:param mode: The mode in which to open the file.
|
380 |
+
:param encoding: The encoding to decode or encode a file opened in
|
381 |
+
text mode.
|
382 |
+
:param errors: The error handling mode.
|
383 |
+
:param lazy: Wait to open the file until it is accessed. For read
|
384 |
+
mode, the file is temporarily opened to raise access errors
|
385 |
+
early, then closed until it is read again.
|
386 |
+
:param atomic: Write to a temporary file and replace the given file
|
387 |
+
on close.
|
388 |
+
|
389 |
+
.. versionadded:: 3.0
|
390 |
+
"""
|
391 |
+
if lazy:
|
392 |
+
return t.cast(
|
393 |
+
t.IO[t.Any], LazyFile(filename, mode, encoding, errors, atomic=atomic)
|
394 |
+
)
|
395 |
+
|
396 |
+
f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
|
397 |
+
|
398 |
+
if not should_close:
|
399 |
+
f = t.cast(t.IO[t.Any], KeepOpenFile(f))
|
400 |
+
|
401 |
+
return f
|
402 |
+
|
403 |
+
|
404 |
+
def format_filename(
|
405 |
+
filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",
|
406 |
+
shorten: bool = False,
|
407 |
+
) -> str:
|
408 |
+
"""Format a filename as a string for display. Ensures the filename can be
|
409 |
+
displayed by replacing any invalid bytes or surrogate escapes in the name
|
410 |
+
with the replacement character ``�``.
|
411 |
+
|
412 |
+
Invalid bytes or surrogate escapes will raise an error when written to a
|
413 |
+
stream with ``errors="strict". This will typically happen with ``stdout``
|
414 |
+
when the locale is something like ``en_GB.UTF-8``.
|
415 |
+
|
416 |
+
Many scenarios *are* safe to write surrogates though, due to PEP 538 and
|
417 |
+
PEP 540, including:
|
418 |
+
|
419 |
+
- Writing to ``stderr``, which uses ``errors="backslashreplace"``.
|
420 |
+
- The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens
|
421 |
+
stdout and stderr with ``errors="surrogateescape"``.
|
422 |
+
- None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.
|
423 |
+
- Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.
|
424 |
+
Python opens stdout and stderr with ``errors="surrogateescape"``.
|
425 |
+
|
426 |
+
:param filename: formats a filename for UI display. This will also convert
|
427 |
+
the filename into unicode without failing.
|
428 |
+
:param shorten: this optionally shortens the filename to strip of the
|
429 |
+
path that leads up to it.
|
430 |
+
"""
|
431 |
+
if shorten:
|
432 |
+
filename = os.path.basename(filename)
|
433 |
+
else:
|
434 |
+
filename = os.fspath(filename)
|
435 |
+
|
436 |
+
if isinstance(filename, bytes):
|
437 |
+
filename = filename.decode(sys.getfilesystemencoding(), "replace")
|
438 |
+
else:
|
439 |
+
filename = filename.encode("utf-8", "surrogateescape").decode(
|
440 |
+
"utf-8", "replace"
|
441 |
+
)
|
442 |
+
|
443 |
+
return filename
|
444 |
+
|
445 |
+
|
446 |
+
def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
|
447 |
+
r"""Returns the config folder for the application. The default behavior
|
448 |
+
is to return whatever is most appropriate for the operating system.
|
449 |
+
|
450 |
+
To give you an idea, for an app called ``"Foo Bar"``, something like
|
451 |
+
the following folders could be returned:
|
452 |
+
|
453 |
+
Mac OS X:
|
454 |
+
``~/Library/Application Support/Foo Bar``
|
455 |
+
Mac OS X (POSIX):
|
456 |
+
``~/.foo-bar``
|
457 |
+
Unix:
|
458 |
+
``~/.config/foo-bar``
|
459 |
+
Unix (POSIX):
|
460 |
+
``~/.foo-bar``
|
461 |
+
Windows (roaming):
|
462 |
+
``C:\Users\<user>\AppData\Roaming\Foo Bar``
|
463 |
+
Windows (not roaming):
|
464 |
+
``C:\Users\<user>\AppData\Local\Foo Bar``
|
465 |
+
|
466 |
+
.. versionadded:: 2.0
|
467 |
+
|
468 |
+
:param app_name: the application name. This should be properly capitalized
|
469 |
+
and can contain whitespace.
|
470 |
+
:param roaming: controls if the folder should be roaming or not on Windows.
|
471 |
+
Has no effect otherwise.
|
472 |
+
:param force_posix: if this is set to `True` then on any POSIX system the
|
473 |
+
folder will be stored in the home folder with a leading
|
474 |
+
dot instead of the XDG config home or darwin's
|
475 |
+
application support folder.
|
476 |
+
"""
|
477 |
+
if WIN:
|
478 |
+
key = "APPDATA" if roaming else "LOCALAPPDATA"
|
479 |
+
folder = os.environ.get(key)
|
480 |
+
if folder is None:
|
481 |
+
folder = os.path.expanduser("~")
|
482 |
+
return os.path.join(folder, app_name)
|
483 |
+
if force_posix:
|
484 |
+
return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))
|
485 |
+
if sys.platform == "darwin":
|
486 |
+
return os.path.join(
|
487 |
+
os.path.expanduser("~/Library/Application Support"), app_name
|
488 |
+
)
|
489 |
+
return os.path.join(
|
490 |
+
os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),
|
491 |
+
_posixify(app_name),
|
492 |
+
)
|
493 |
+
|
494 |
+
|
495 |
+
class PacifyFlushWrapper:
|
496 |
+
"""This wrapper is used to catch and suppress BrokenPipeErrors resulting
|
497 |
+
from ``.flush()`` being called on broken pipe during the shutdown/final-GC
|
498 |
+
of the Python interpreter. Notably ``.flush()`` is always called on
|
499 |
+
``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any
|
500 |
+
other cleanup code, and the case where the underlying file is not a broken
|
501 |
+
pipe, all calls and attributes are proxied.
|
502 |
+
"""
|
503 |
+
|
504 |
+
def __init__(self, wrapped: t.IO[t.Any]) -> None:
|
505 |
+
self.wrapped = wrapped
|
506 |
+
|
507 |
+
def flush(self) -> None:
|
508 |
+
try:
|
509 |
+
self.wrapped.flush()
|
510 |
+
except OSError as e:
|
511 |
+
import errno
|
512 |
+
|
513 |
+
if e.errno != errno.EPIPE:
|
514 |
+
raise
|
515 |
+
|
516 |
+
def __getattr__(self, attr: str) -> t.Any:
|
517 |
+
return getattr(self.wrapped, attr)
|
518 |
+
|
519 |
+
|
520 |
+
def _detect_program_name(
|
521 |
+
path: t.Optional[str] = None, _main: t.Optional[ModuleType] = None
|
522 |
+
) -> str:
|
523 |
+
"""Determine the command used to run the program, for use in help
|
524 |
+
text. If a file or entry point was executed, the file name is
|
525 |
+
returned. If ``python -m`` was used to execute a module or package,
|
526 |
+
``python -m name`` is returned.
|
527 |
+
|
528 |
+
This doesn't try to be too precise, the goal is to give a concise
|
529 |
+
name for help text. Files are only shown as their name without the
|
530 |
+
path. ``python`` is only shown for modules, and the full path to
|
531 |
+
``sys.executable`` is not shown.
|
532 |
+
|
533 |
+
:param path: The Python file being executed. Python puts this in
|
534 |
+
``sys.argv[0]``, which is used by default.
|
535 |
+
:param _main: The ``__main__`` module. This should only be passed
|
536 |
+
during internal testing.
|
537 |
+
|
538 |
+
.. versionadded:: 8.0
|
539 |
+
Based on command args detection in the Werkzeug reloader.
|
540 |
+
|
541 |
+
:meta private:
|
542 |
+
"""
|
543 |
+
if _main is None:
|
544 |
+
_main = sys.modules["__main__"]
|
545 |
+
|
546 |
+
if not path:
|
547 |
+
path = sys.argv[0]
|
548 |
+
|
549 |
+
# The value of __package__ indicates how Python was called. It may
|
550 |
+
# not exist if a setuptools script is installed as an egg. It may be
|
551 |
+
# set incorrectly for entry points created with pip on Windows.
|
552 |
+
# It is set to "" inside a Shiv or PEX zipapp.
|
553 |
+
if getattr(_main, "__package__", None) in {None, ""} or (
|
554 |
+
os.name == "nt"
|
555 |
+
and _main.__package__ == ""
|
556 |
+
and not os.path.exists(path)
|
557 |
+
and os.path.exists(f"{path}.exe")
|
558 |
+
):
|
559 |
+
# Executed a file, like "python app.py".
|
560 |
+
return os.path.basename(path)
|
561 |
+
|
562 |
+
# Executed a module, like "python -m example".
|
563 |
+
# Rewritten by Python from "-m script" to "/path/to/script.py".
|
564 |
+
# Need to look at main module to determine how it was executed.
|
565 |
+
py_module = t.cast(str, _main.__package__)
|
566 |
+
name = os.path.splitext(os.path.basename(path))[0]
|
567 |
+
|
568 |
+
# A submodule like "example.cli".
|
569 |
+
if name != "__main__":
|
570 |
+
py_module = f"{py_module}.{name}"
|
571 |
+
|
572 |
+
return f"python -m {py_module.lstrip('.')}"
|
573 |
+
|
574 |
+
|
575 |
+
def _expand_args(
|
576 |
+
args: t.Iterable[str],
|
577 |
+
*,
|
578 |
+
user: bool = True,
|
579 |
+
env: bool = True,
|
580 |
+
glob_recursive: bool = True,
|
581 |
+
) -> t.List[str]:
|
582 |
+
"""Simulate Unix shell expansion with Python functions.
|
583 |
+
|
584 |
+
See :func:`glob.glob`, :func:`os.path.expanduser`, and
|
585 |
+
:func:`os.path.expandvars`.
|
586 |
+
|
587 |
+
This is intended for use on Windows, where the shell does not do any
|
588 |
+
expansion. It may not exactly match what a Unix shell would do.
|
589 |
+
|
590 |
+
:param args: List of command line arguments to expand.
|
591 |
+
:param user: Expand user home directory.
|
592 |
+
:param env: Expand environment variables.
|
593 |
+
:param glob_recursive: ``**`` matches directories recursively.
|
594 |
+
|
595 |
+
.. versionchanged:: 8.1
|
596 |
+
Invalid glob patterns are treated as empty expansions rather
|
597 |
+
than raising an error.
|
598 |
+
|
599 |
+
.. versionadded:: 8.0
|
600 |
+
|
601 |
+
:meta private:
|
602 |
+
"""
|
603 |
+
from glob import glob
|
604 |
+
|
605 |
+
out = []
|
606 |
+
|
607 |
+
for arg in args:
|
608 |
+
if user:
|
609 |
+
arg = os.path.expanduser(arg)
|
610 |
+
|
611 |
+
if env:
|
612 |
+
arg = os.path.expandvars(arg)
|
613 |
+
|
614 |
+
try:
|
615 |
+
matches = glob(arg, recursive=glob_recursive)
|
616 |
+
except re.error:
|
617 |
+
matches = []
|
618 |
+
|
619 |
+
if not matches:
|
620 |
+
out.append(arg)
|
621 |
+
else:
|
622 |
+
out.extend(matches)
|
623 |
+
|
624 |
+
return out
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__init__.py
ADDED
@@ -0,0 +1,916 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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__ = "0.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 |
+
"_commit_scheduler": [
|
56 |
+
"CommitScheduler",
|
57 |
+
],
|
58 |
+
"_inference_endpoints": [
|
59 |
+
"InferenceEndpoint",
|
60 |
+
"InferenceEndpointError",
|
61 |
+
"InferenceEndpointStatus",
|
62 |
+
"InferenceEndpointTimeoutError",
|
63 |
+
"InferenceEndpointType",
|
64 |
+
],
|
65 |
+
"_login": [
|
66 |
+
"interpreter_login",
|
67 |
+
"login",
|
68 |
+
"logout",
|
69 |
+
"notebook_login",
|
70 |
+
],
|
71 |
+
"_multi_commits": [
|
72 |
+
"MultiCommitException",
|
73 |
+
"plan_multi_commits",
|
74 |
+
],
|
75 |
+
"_snapshot_download": [
|
76 |
+
"snapshot_download",
|
77 |
+
],
|
78 |
+
"_space_api": [
|
79 |
+
"SpaceHardware",
|
80 |
+
"SpaceRuntime",
|
81 |
+
"SpaceStage",
|
82 |
+
"SpaceStorage",
|
83 |
+
"SpaceVariable",
|
84 |
+
],
|
85 |
+
"_tensorboard_logger": [
|
86 |
+
"HFSummaryWriter",
|
87 |
+
],
|
88 |
+
"_webhooks_payload": [
|
89 |
+
"WebhookPayload",
|
90 |
+
"WebhookPayloadComment",
|
91 |
+
"WebhookPayloadDiscussion",
|
92 |
+
"WebhookPayloadDiscussionChanges",
|
93 |
+
"WebhookPayloadEvent",
|
94 |
+
"WebhookPayloadMovedTo",
|
95 |
+
"WebhookPayloadRepo",
|
96 |
+
"WebhookPayloadUrl",
|
97 |
+
"WebhookPayloadWebhook",
|
98 |
+
],
|
99 |
+
"_webhooks_server": [
|
100 |
+
"WebhooksServer",
|
101 |
+
"webhook_endpoint",
|
102 |
+
],
|
103 |
+
"community": [
|
104 |
+
"Discussion",
|
105 |
+
"DiscussionComment",
|
106 |
+
"DiscussionCommit",
|
107 |
+
"DiscussionEvent",
|
108 |
+
"DiscussionStatusChange",
|
109 |
+
"DiscussionTitleChange",
|
110 |
+
"DiscussionWithDetails",
|
111 |
+
],
|
112 |
+
"constants": [
|
113 |
+
"CONFIG_NAME",
|
114 |
+
"FLAX_WEIGHTS_NAME",
|
115 |
+
"HUGGINGFACE_CO_URL_HOME",
|
116 |
+
"HUGGINGFACE_CO_URL_TEMPLATE",
|
117 |
+
"PYTORCH_WEIGHTS_NAME",
|
118 |
+
"REPO_TYPE_DATASET",
|
119 |
+
"REPO_TYPE_MODEL",
|
120 |
+
"REPO_TYPE_SPACE",
|
121 |
+
"TF2_WEIGHTS_NAME",
|
122 |
+
"TF_WEIGHTS_NAME",
|
123 |
+
],
|
124 |
+
"fastai_utils": [
|
125 |
+
"_save_pretrained_fastai",
|
126 |
+
"from_pretrained_fastai",
|
127 |
+
"push_to_hub_fastai",
|
128 |
+
],
|
129 |
+
"file_download": [
|
130 |
+
"HfFileMetadata",
|
131 |
+
"_CACHED_NO_EXIST",
|
132 |
+
"cached_download",
|
133 |
+
"get_hf_file_metadata",
|
134 |
+
"hf_hub_download",
|
135 |
+
"hf_hub_url",
|
136 |
+
"try_to_load_from_cache",
|
137 |
+
],
|
138 |
+
"hf_api": [
|
139 |
+
"Collection",
|
140 |
+
"CollectionItem",
|
141 |
+
"CommitInfo",
|
142 |
+
"CommitOperation",
|
143 |
+
"CommitOperationAdd",
|
144 |
+
"CommitOperationCopy",
|
145 |
+
"CommitOperationDelete",
|
146 |
+
"GitCommitInfo",
|
147 |
+
"GitRefInfo",
|
148 |
+
"GitRefs",
|
149 |
+
"HfApi",
|
150 |
+
"RepoUrl",
|
151 |
+
"User",
|
152 |
+
"UserLikes",
|
153 |
+
"accept_access_request",
|
154 |
+
"add_collection_item",
|
155 |
+
"add_space_secret",
|
156 |
+
"add_space_variable",
|
157 |
+
"cancel_access_request",
|
158 |
+
"change_discussion_status",
|
159 |
+
"comment_discussion",
|
160 |
+
"create_branch",
|
161 |
+
"create_collection",
|
162 |
+
"create_commit",
|
163 |
+
"create_commits_on_pr",
|
164 |
+
"create_discussion",
|
165 |
+
"create_inference_endpoint",
|
166 |
+
"create_pull_request",
|
167 |
+
"create_repo",
|
168 |
+
"create_tag",
|
169 |
+
"dataset_info",
|
170 |
+
"delete_branch",
|
171 |
+
"delete_collection",
|
172 |
+
"delete_collection_item",
|
173 |
+
"delete_file",
|
174 |
+
"delete_folder",
|
175 |
+
"delete_inference_endpoint",
|
176 |
+
"delete_repo",
|
177 |
+
"delete_space_secret",
|
178 |
+
"delete_space_storage",
|
179 |
+
"delete_space_variable",
|
180 |
+
"delete_tag",
|
181 |
+
"duplicate_space",
|
182 |
+
"edit_discussion_comment",
|
183 |
+
"file_exists",
|
184 |
+
"get_collection",
|
185 |
+
"get_dataset_tags",
|
186 |
+
"get_discussion_details",
|
187 |
+
"get_full_repo_name",
|
188 |
+
"get_inference_endpoint",
|
189 |
+
"get_model_tags",
|
190 |
+
"get_paths_info",
|
191 |
+
"get_repo_discussions",
|
192 |
+
"get_safetensors_metadata",
|
193 |
+
"get_space_runtime",
|
194 |
+
"get_space_variables",
|
195 |
+
"get_token_permission",
|
196 |
+
"grant_access",
|
197 |
+
"like",
|
198 |
+
"list_accepted_access_requests",
|
199 |
+
"list_collections",
|
200 |
+
"list_datasets",
|
201 |
+
"list_inference_endpoints",
|
202 |
+
"list_liked_repos",
|
203 |
+
"list_metrics",
|
204 |
+
"list_models",
|
205 |
+
"list_pending_access_requests",
|
206 |
+
"list_rejected_access_requests",
|
207 |
+
"list_repo_commits",
|
208 |
+
"list_repo_files",
|
209 |
+
"list_repo_likers",
|
210 |
+
"list_repo_refs",
|
211 |
+
"list_repo_tree",
|
212 |
+
"list_spaces",
|
213 |
+
"merge_pull_request",
|
214 |
+
"model_info",
|
215 |
+
"move_repo",
|
216 |
+
"parse_safetensors_file_metadata",
|
217 |
+
"pause_inference_endpoint",
|
218 |
+
"pause_space",
|
219 |
+
"preupload_lfs_files",
|
220 |
+
"reject_access_request",
|
221 |
+
"rename_discussion",
|
222 |
+
"repo_exists",
|
223 |
+
"repo_info",
|
224 |
+
"repo_type_and_id_from_hf_id",
|
225 |
+
"request_space_hardware",
|
226 |
+
"request_space_storage",
|
227 |
+
"restart_space",
|
228 |
+
"resume_inference_endpoint",
|
229 |
+
"revision_exists",
|
230 |
+
"run_as_future",
|
231 |
+
"scale_to_zero_inference_endpoint",
|
232 |
+
"set_space_sleep_time",
|
233 |
+
"space_info",
|
234 |
+
"super_squash_history",
|
235 |
+
"unlike",
|
236 |
+
"update_collection_item",
|
237 |
+
"update_collection_metadata",
|
238 |
+
"update_inference_endpoint",
|
239 |
+
"update_repo_visibility",
|
240 |
+
"upload_file",
|
241 |
+
"upload_folder",
|
242 |
+
"whoami",
|
243 |
+
],
|
244 |
+
"hf_file_system": [
|
245 |
+
"HfFileSystem",
|
246 |
+
"HfFileSystemFile",
|
247 |
+
"HfFileSystemResolvedPath",
|
248 |
+
"HfFileSystemStreamFile",
|
249 |
+
],
|
250 |
+
"hub_mixin": [
|
251 |
+
"ModelHubMixin",
|
252 |
+
"PyTorchModelHubMixin",
|
253 |
+
],
|
254 |
+
"inference._client": [
|
255 |
+
"InferenceClient",
|
256 |
+
"InferenceTimeoutError",
|
257 |
+
],
|
258 |
+
"inference._generated._async_client": [
|
259 |
+
"AsyncInferenceClient",
|
260 |
+
],
|
261 |
+
"inference._generated.types": [
|
262 |
+
"AudioClassificationInput",
|
263 |
+
"AudioClassificationOutputElement",
|
264 |
+
"AudioClassificationParameters",
|
265 |
+
"AudioToAudioInput",
|
266 |
+
"AudioToAudioOutputElement",
|
267 |
+
"AutomaticSpeechRecognitionGenerationParameters",
|
268 |
+
"AutomaticSpeechRecognitionInput",
|
269 |
+
"AutomaticSpeechRecognitionOutput",
|
270 |
+
"AutomaticSpeechRecognitionOutputChunk",
|
271 |
+
"AutomaticSpeechRecognitionParameters",
|
272 |
+
"ChatCompletionInput",
|
273 |
+
"ChatCompletionInputFunctionDefinition",
|
274 |
+
"ChatCompletionInputMessage",
|
275 |
+
"ChatCompletionInputTool",
|
276 |
+
"ChatCompletionInputToolCall",
|
277 |
+
"ChatCompletionInputToolTypeClass",
|
278 |
+
"ChatCompletionOutput",
|
279 |
+
"ChatCompletionOutputComplete",
|
280 |
+
"ChatCompletionOutputFunctionDefinition",
|
281 |
+
"ChatCompletionOutputLogprob",
|
282 |
+
"ChatCompletionOutputLogprobs",
|
283 |
+
"ChatCompletionOutputMessage",
|
284 |
+
"ChatCompletionOutputToolCall",
|
285 |
+
"ChatCompletionOutputTopLogprob",
|
286 |
+
"ChatCompletionOutputUsage",
|
287 |
+
"ChatCompletionStreamOutput",
|
288 |
+
"ChatCompletionStreamOutputChoice",
|
289 |
+
"ChatCompletionStreamOutputDelta",
|
290 |
+
"ChatCompletionStreamOutputDeltaToolCall",
|
291 |
+
"ChatCompletionStreamOutputFunction",
|
292 |
+
"ChatCompletionStreamOutputLogprob",
|
293 |
+
"ChatCompletionStreamOutputLogprobs",
|
294 |
+
"ChatCompletionStreamOutputTopLogprob",
|
295 |
+
"DepthEstimationInput",
|
296 |
+
"DepthEstimationOutput",
|
297 |
+
"DocumentQuestionAnsweringInput",
|
298 |
+
"DocumentQuestionAnsweringInputData",
|
299 |
+
"DocumentQuestionAnsweringOutputElement",
|
300 |
+
"DocumentQuestionAnsweringParameters",
|
301 |
+
"FeatureExtractionInput",
|
302 |
+
"FillMaskInput",
|
303 |
+
"FillMaskOutputElement",
|
304 |
+
"FillMaskParameters",
|
305 |
+
"ImageClassificationInput",
|
306 |
+
"ImageClassificationOutputElement",
|
307 |
+
"ImageClassificationParameters",
|
308 |
+
"ImageSegmentationInput",
|
309 |
+
"ImageSegmentationOutputElement",
|
310 |
+
"ImageSegmentationParameters",
|
311 |
+
"ImageToImageInput",
|
312 |
+
"ImageToImageOutput",
|
313 |
+
"ImageToImageParameters",
|
314 |
+
"ImageToImageTargetSize",
|
315 |
+
"ImageToTextGenerationParameters",
|
316 |
+
"ImageToTextInput",
|
317 |
+
"ImageToTextOutput",
|
318 |
+
"ImageToTextParameters",
|
319 |
+
"ObjectDetectionBoundingBox",
|
320 |
+
"ObjectDetectionInput",
|
321 |
+
"ObjectDetectionOutputElement",
|
322 |
+
"ObjectDetectionParameters",
|
323 |
+
"QuestionAnsweringInput",
|
324 |
+
"QuestionAnsweringInputData",
|
325 |
+
"QuestionAnsweringOutputElement",
|
326 |
+
"QuestionAnsweringParameters",
|
327 |
+
"SentenceSimilarityInput",
|
328 |
+
"SentenceSimilarityInputData",
|
329 |
+
"SummarizationGenerationParameters",
|
330 |
+
"SummarizationInput",
|
331 |
+
"SummarizationOutput",
|
332 |
+
"TableQuestionAnsweringInput",
|
333 |
+
"TableQuestionAnsweringInputData",
|
334 |
+
"TableQuestionAnsweringOutputElement",
|
335 |
+
"Text2TextGenerationInput",
|
336 |
+
"Text2TextGenerationOutput",
|
337 |
+
"Text2TextGenerationParameters",
|
338 |
+
"TextClassificationInput",
|
339 |
+
"TextClassificationOutputElement",
|
340 |
+
"TextClassificationParameters",
|
341 |
+
"TextGenerationInput",
|
342 |
+
"TextGenerationInputGenerateParameters",
|
343 |
+
"TextGenerationInputGrammarType",
|
344 |
+
"TextGenerationOutput",
|
345 |
+
"TextGenerationOutputBestOfSequence",
|
346 |
+
"TextGenerationOutputDetails",
|
347 |
+
"TextGenerationOutputPrefillToken",
|
348 |
+
"TextGenerationOutputToken",
|
349 |
+
"TextGenerationStreamOutput",
|
350 |
+
"TextGenerationStreamOutputStreamDetails",
|
351 |
+
"TextGenerationStreamOutputToken",
|
352 |
+
"TextToAudioGenerationParameters",
|
353 |
+
"TextToAudioInput",
|
354 |
+
"TextToAudioOutput",
|
355 |
+
"TextToAudioParameters",
|
356 |
+
"TextToImageInput",
|
357 |
+
"TextToImageOutput",
|
358 |
+
"TextToImageParameters",
|
359 |
+
"TextToImageTargetSize",
|
360 |
+
"TokenClassificationInput",
|
361 |
+
"TokenClassificationOutputElement",
|
362 |
+
"TokenClassificationParameters",
|
363 |
+
"TranslationGenerationParameters",
|
364 |
+
"TranslationInput",
|
365 |
+
"TranslationOutput",
|
366 |
+
"VideoClassificationInput",
|
367 |
+
"VideoClassificationOutputElement",
|
368 |
+
"VideoClassificationParameters",
|
369 |
+
"VisualQuestionAnsweringInput",
|
370 |
+
"VisualQuestionAnsweringInputData",
|
371 |
+
"VisualQuestionAnsweringOutputElement",
|
372 |
+
"VisualQuestionAnsweringParameters",
|
373 |
+
"ZeroShotClassificationInput",
|
374 |
+
"ZeroShotClassificationInputData",
|
375 |
+
"ZeroShotClassificationOutputElement",
|
376 |
+
"ZeroShotClassificationParameters",
|
377 |
+
"ZeroShotImageClassificationInput",
|
378 |
+
"ZeroShotImageClassificationInputData",
|
379 |
+
"ZeroShotImageClassificationOutputElement",
|
380 |
+
"ZeroShotImageClassificationParameters",
|
381 |
+
"ZeroShotObjectDetectionBoundingBox",
|
382 |
+
"ZeroShotObjectDetectionInput",
|
383 |
+
"ZeroShotObjectDetectionInputData",
|
384 |
+
"ZeroShotObjectDetectionOutputElement",
|
385 |
+
],
|
386 |
+
"inference_api": [
|
387 |
+
"InferenceApi",
|
388 |
+
],
|
389 |
+
"keras_mixin": [
|
390 |
+
"KerasModelHubMixin",
|
391 |
+
"from_pretrained_keras",
|
392 |
+
"push_to_hub_keras",
|
393 |
+
"save_pretrained_keras",
|
394 |
+
],
|
395 |
+
"repocard": [
|
396 |
+
"DatasetCard",
|
397 |
+
"ModelCard",
|
398 |
+
"RepoCard",
|
399 |
+
"SpaceCard",
|
400 |
+
"metadata_eval_result",
|
401 |
+
"metadata_load",
|
402 |
+
"metadata_save",
|
403 |
+
"metadata_update",
|
404 |
+
],
|
405 |
+
"repocard_data": [
|
406 |
+
"CardData",
|
407 |
+
"DatasetCardData",
|
408 |
+
"EvalResult",
|
409 |
+
"ModelCardData",
|
410 |
+
"SpaceCardData",
|
411 |
+
],
|
412 |
+
"repository": [
|
413 |
+
"Repository",
|
414 |
+
],
|
415 |
+
"serialization": [
|
416 |
+
"StateDictSplit",
|
417 |
+
"split_numpy_state_dict_into_shards",
|
418 |
+
"split_state_dict_into_shards_factory",
|
419 |
+
"split_tf_state_dict_into_shards",
|
420 |
+
"split_torch_state_dict_into_shards",
|
421 |
+
],
|
422 |
+
"utils": [
|
423 |
+
"CacheNotFound",
|
424 |
+
"CachedFileInfo",
|
425 |
+
"CachedRepoInfo",
|
426 |
+
"CachedRevisionInfo",
|
427 |
+
"CorruptedCacheException",
|
428 |
+
"DeleteCacheStrategy",
|
429 |
+
"HFCacheInfo",
|
430 |
+
"HfFolder",
|
431 |
+
"cached_assets_path",
|
432 |
+
"configure_http_backend",
|
433 |
+
"dump_environment_info",
|
434 |
+
"get_session",
|
435 |
+
"get_token",
|
436 |
+
"logging",
|
437 |
+
"scan_cache_dir",
|
438 |
+
],
|
439 |
+
"utils.endpoint_helpers": [
|
440 |
+
"DatasetFilter",
|
441 |
+
"ModelFilter",
|
442 |
+
],
|
443 |
+
}
|
444 |
+
|
445 |
+
|
446 |
+
def _attach(package_name, submodules=None, submod_attrs=None):
|
447 |
+
"""Attach lazily loaded submodules, functions, or other attributes.
|
448 |
+
|
449 |
+
Typically, modules import submodules and attributes as follows:
|
450 |
+
|
451 |
+
```py
|
452 |
+
import mysubmodule
|
453 |
+
import anothersubmodule
|
454 |
+
|
455 |
+
from .foo import someattr
|
456 |
+
```
|
457 |
+
|
458 |
+
The idea is to replace a package's `__getattr__`, `__dir__`, and
|
459 |
+
`__all__`, such that all imports work exactly the way they would
|
460 |
+
with normal imports, except that the import occurs upon first use.
|
461 |
+
|
462 |
+
The typical way to call this function, replacing the above imports, is:
|
463 |
+
|
464 |
+
```python
|
465 |
+
__getattr__, __dir__, __all__ = lazy.attach(
|
466 |
+
__name__,
|
467 |
+
['mysubmodule', 'anothersubmodule'],
|
468 |
+
{'foo': ['someattr']}
|
469 |
+
)
|
470 |
+
```
|
471 |
+
This functionality requires Python 3.7 or higher.
|
472 |
+
|
473 |
+
Args:
|
474 |
+
package_name (`str`):
|
475 |
+
Typically use `__name__`.
|
476 |
+
submodules (`set`):
|
477 |
+
List of submodules to attach.
|
478 |
+
submod_attrs (`dict`):
|
479 |
+
Dictionary of submodule -> list of attributes / functions.
|
480 |
+
These attributes are imported as they are used.
|
481 |
+
|
482 |
+
Returns:
|
483 |
+
__getattr__, __dir__, __all__
|
484 |
+
|
485 |
+
"""
|
486 |
+
if submod_attrs is None:
|
487 |
+
submod_attrs = {}
|
488 |
+
|
489 |
+
if submodules is None:
|
490 |
+
submodules = set()
|
491 |
+
else:
|
492 |
+
submodules = set(submodules)
|
493 |
+
|
494 |
+
attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
|
495 |
+
|
496 |
+
__all__ = list(submodules | attr_to_modules.keys())
|
497 |
+
|
498 |
+
def __getattr__(name):
|
499 |
+
if name in submodules:
|
500 |
+
return importlib.import_module(f"{package_name}.{name}")
|
501 |
+
elif name in attr_to_modules:
|
502 |
+
submod_path = f"{package_name}.{attr_to_modules[name]}"
|
503 |
+
submod = importlib.import_module(submod_path)
|
504 |
+
attr = getattr(submod, name)
|
505 |
+
|
506 |
+
# If the attribute lives in a file (module) with the same
|
507 |
+
# name as the attribute, ensure that the attribute and *not*
|
508 |
+
# the module is accessible on the package.
|
509 |
+
if name == attr_to_modules[name]:
|
510 |
+
pkg = sys.modules[package_name]
|
511 |
+
pkg.__dict__[name] = attr
|
512 |
+
|
513 |
+
return attr
|
514 |
+
else:
|
515 |
+
raise AttributeError(f"No {package_name} attribute {name}")
|
516 |
+
|
517 |
+
def __dir__():
|
518 |
+
return __all__
|
519 |
+
|
520 |
+
return __getattr__, __dir__, list(__all__)
|
521 |
+
|
522 |
+
|
523 |
+
__getattr__, __dir__, __all__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
|
524 |
+
|
525 |
+
if os.environ.get("EAGER_IMPORT", ""):
|
526 |
+
for attr in __all__:
|
527 |
+
__getattr__(attr)
|
528 |
+
|
529 |
+
# WARNING: any content below this statement is generated automatically. Any manual edit
|
530 |
+
# will be lost when re-generating this file !
|
531 |
+
#
|
532 |
+
# To update the static imports, please run the following command and commit the changes.
|
533 |
+
# ```
|
534 |
+
# # Use script
|
535 |
+
# python utils/check_static_imports.py --update-file
|
536 |
+
#
|
537 |
+
# # Or run style on codebase
|
538 |
+
# make style
|
539 |
+
# ```
|
540 |
+
if TYPE_CHECKING: # pragma: no cover
|
541 |
+
from ._commit_scheduler import CommitScheduler # noqa: F401
|
542 |
+
from ._inference_endpoints import (
|
543 |
+
InferenceEndpoint, # noqa: F401
|
544 |
+
InferenceEndpointError, # noqa: F401
|
545 |
+
InferenceEndpointStatus, # noqa: F401
|
546 |
+
InferenceEndpointTimeoutError, # noqa: F401
|
547 |
+
InferenceEndpointType, # noqa: F401
|
548 |
+
)
|
549 |
+
from ._login import (
|
550 |
+
interpreter_login, # noqa: F401
|
551 |
+
login, # noqa: F401
|
552 |
+
logout, # noqa: F401
|
553 |
+
notebook_login, # noqa: F401
|
554 |
+
)
|
555 |
+
from ._multi_commits import (
|
556 |
+
MultiCommitException, # noqa: F401
|
557 |
+
plan_multi_commits, # noqa: F401
|
558 |
+
)
|
559 |
+
from ._snapshot_download import snapshot_download # noqa: F401
|
560 |
+
from ._space_api import (
|
561 |
+
SpaceHardware, # noqa: F401
|
562 |
+
SpaceRuntime, # noqa: F401
|
563 |
+
SpaceStage, # noqa: F401
|
564 |
+
SpaceStorage, # noqa: F401
|
565 |
+
SpaceVariable, # noqa: F401
|
566 |
+
)
|
567 |
+
from ._tensorboard_logger import HFSummaryWriter # noqa: F401
|
568 |
+
from ._webhooks_payload import (
|
569 |
+
WebhookPayload, # noqa: F401
|
570 |
+
WebhookPayloadComment, # noqa: F401
|
571 |
+
WebhookPayloadDiscussion, # noqa: F401
|
572 |
+
WebhookPayloadDiscussionChanges, # noqa: F401
|
573 |
+
WebhookPayloadEvent, # noqa: F401
|
574 |
+
WebhookPayloadMovedTo, # noqa: F401
|
575 |
+
WebhookPayloadRepo, # noqa: F401
|
576 |
+
WebhookPayloadUrl, # noqa: F401
|
577 |
+
WebhookPayloadWebhook, # noqa: F401
|
578 |
+
)
|
579 |
+
from ._webhooks_server import (
|
580 |
+
WebhooksServer, # noqa: F401
|
581 |
+
webhook_endpoint, # noqa: F401
|
582 |
+
)
|
583 |
+
from .community import (
|
584 |
+
Discussion, # noqa: F401
|
585 |
+
DiscussionComment, # noqa: F401
|
586 |
+
DiscussionCommit, # noqa: F401
|
587 |
+
DiscussionEvent, # noqa: F401
|
588 |
+
DiscussionStatusChange, # noqa: F401
|
589 |
+
DiscussionTitleChange, # noqa: F401
|
590 |
+
DiscussionWithDetails, # noqa: F401
|
591 |
+
)
|
592 |
+
from .constants import (
|
593 |
+
CONFIG_NAME, # noqa: F401
|
594 |
+
FLAX_WEIGHTS_NAME, # noqa: F401
|
595 |
+
HUGGINGFACE_CO_URL_HOME, # noqa: F401
|
596 |
+
HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401
|
597 |
+
PYTORCH_WEIGHTS_NAME, # noqa: F401
|
598 |
+
REPO_TYPE_DATASET, # noqa: F401
|
599 |
+
REPO_TYPE_MODEL, # noqa: F401
|
600 |
+
REPO_TYPE_SPACE, # noqa: F401
|
601 |
+
TF2_WEIGHTS_NAME, # noqa: F401
|
602 |
+
TF_WEIGHTS_NAME, # noqa: F401
|
603 |
+
)
|
604 |
+
from .fastai_utils import (
|
605 |
+
_save_pretrained_fastai, # noqa: F401
|
606 |
+
from_pretrained_fastai, # noqa: F401
|
607 |
+
push_to_hub_fastai, # noqa: F401
|
608 |
+
)
|
609 |
+
from .file_download import (
|
610 |
+
_CACHED_NO_EXIST, # noqa: F401
|
611 |
+
HfFileMetadata, # noqa: F401
|
612 |
+
cached_download, # noqa: F401
|
613 |
+
get_hf_file_metadata, # noqa: F401
|
614 |
+
hf_hub_download, # noqa: F401
|
615 |
+
hf_hub_url, # noqa: F401
|
616 |
+
try_to_load_from_cache, # noqa: F401
|
617 |
+
)
|
618 |
+
from .hf_api import (
|
619 |
+
Collection, # noqa: F401
|
620 |
+
CollectionItem, # noqa: F401
|
621 |
+
CommitInfo, # noqa: F401
|
622 |
+
CommitOperation, # noqa: F401
|
623 |
+
CommitOperationAdd, # noqa: F401
|
624 |
+
CommitOperationCopy, # noqa: F401
|
625 |
+
CommitOperationDelete, # noqa: F401
|
626 |
+
GitCommitInfo, # noqa: F401
|
627 |
+
GitRefInfo, # noqa: F401
|
628 |
+
GitRefs, # noqa: F401
|
629 |
+
HfApi, # noqa: F401
|
630 |
+
RepoUrl, # noqa: F401
|
631 |
+
User, # noqa: F401
|
632 |
+
UserLikes, # noqa: F401
|
633 |
+
accept_access_request, # noqa: F401
|
634 |
+
add_collection_item, # noqa: F401
|
635 |
+
add_space_secret, # noqa: F401
|
636 |
+
add_space_variable, # noqa: F401
|
637 |
+
cancel_access_request, # noqa: F401
|
638 |
+
change_discussion_status, # noqa: F401
|
639 |
+
comment_discussion, # noqa: F401
|
640 |
+
create_branch, # noqa: F401
|
641 |
+
create_collection, # noqa: F401
|
642 |
+
create_commit, # noqa: F401
|
643 |
+
create_commits_on_pr, # noqa: F401
|
644 |
+
create_discussion, # noqa: F401
|
645 |
+
create_inference_endpoint, # noqa: F401
|
646 |
+
create_pull_request, # noqa: F401
|
647 |
+
create_repo, # noqa: F401
|
648 |
+
create_tag, # noqa: F401
|
649 |
+
dataset_info, # noqa: F401
|
650 |
+
delete_branch, # noqa: F401
|
651 |
+
delete_collection, # noqa: F401
|
652 |
+
delete_collection_item, # noqa: F401
|
653 |
+
delete_file, # noqa: F401
|
654 |
+
delete_folder, # noqa: F401
|
655 |
+
delete_inference_endpoint, # noqa: F401
|
656 |
+
delete_repo, # noqa: F401
|
657 |
+
delete_space_secret, # noqa: F401
|
658 |
+
delete_space_storage, # noqa: F401
|
659 |
+
delete_space_variable, # noqa: F401
|
660 |
+
delete_tag, # noqa: F401
|
661 |
+
duplicate_space, # noqa: F401
|
662 |
+
edit_discussion_comment, # noqa: F401
|
663 |
+
file_exists, # noqa: F401
|
664 |
+
get_collection, # noqa: F401
|
665 |
+
get_dataset_tags, # noqa: F401
|
666 |
+
get_discussion_details, # noqa: F401
|
667 |
+
get_full_repo_name, # noqa: F401
|
668 |
+
get_inference_endpoint, # noqa: F401
|
669 |
+
get_model_tags, # noqa: F401
|
670 |
+
get_paths_info, # noqa: F401
|
671 |
+
get_repo_discussions, # noqa: F401
|
672 |
+
get_safetensors_metadata, # noqa: F401
|
673 |
+
get_space_runtime, # noqa: F401
|
674 |
+
get_space_variables, # noqa: F401
|
675 |
+
get_token_permission, # noqa: F401
|
676 |
+
grant_access, # noqa: F401
|
677 |
+
like, # noqa: F401
|
678 |
+
list_accepted_access_requests, # noqa: F401
|
679 |
+
list_collections, # noqa: F401
|
680 |
+
list_datasets, # noqa: F401
|
681 |
+
list_inference_endpoints, # noqa: F401
|
682 |
+
list_liked_repos, # noqa: F401
|
683 |
+
list_metrics, # noqa: F401
|
684 |
+
list_models, # noqa: F401
|
685 |
+
list_pending_access_requests, # noqa: F401
|
686 |
+
list_rejected_access_requests, # noqa: F401
|
687 |
+
list_repo_commits, # noqa: F401
|
688 |
+
list_repo_files, # noqa: F401
|
689 |
+
list_repo_likers, # noqa: F401
|
690 |
+
list_repo_refs, # noqa: F401
|
691 |
+
list_repo_tree, # noqa: F401
|
692 |
+
list_spaces, # noqa: F401
|
693 |
+
merge_pull_request, # noqa: F401
|
694 |
+
model_info, # noqa: F401
|
695 |
+
move_repo, # noqa: F401
|
696 |
+
parse_safetensors_file_metadata, # noqa: F401
|
697 |
+
pause_inference_endpoint, # noqa: F401
|
698 |
+
pause_space, # noqa: F401
|
699 |
+
preupload_lfs_files, # noqa: F401
|
700 |
+
reject_access_request, # noqa: F401
|
701 |
+
rename_discussion, # noqa: F401
|
702 |
+
repo_exists, # noqa: F401
|
703 |
+
repo_info, # noqa: F401
|
704 |
+
repo_type_and_id_from_hf_id, # noqa: F401
|
705 |
+
request_space_hardware, # noqa: F401
|
706 |
+
request_space_storage, # noqa: F401
|
707 |
+
restart_space, # noqa: F401
|
708 |
+
resume_inference_endpoint, # noqa: F401
|
709 |
+
revision_exists, # noqa: F401
|
710 |
+
run_as_future, # noqa: F401
|
711 |
+
scale_to_zero_inference_endpoint, # noqa: F401
|
712 |
+
set_space_sleep_time, # noqa: F401
|
713 |
+
space_info, # noqa: F401
|
714 |
+
super_squash_history, # noqa: F401
|
715 |
+
unlike, # noqa: F401
|
716 |
+
update_collection_item, # noqa: F401
|
717 |
+
update_collection_metadata, # noqa: F401
|
718 |
+
update_inference_endpoint, # noqa: F401
|
719 |
+
update_repo_visibility, # noqa: F401
|
720 |
+
upload_file, # noqa: F401
|
721 |
+
upload_folder, # noqa: F401
|
722 |
+
whoami, # noqa: F401
|
723 |
+
)
|
724 |
+
from .hf_file_system import (
|
725 |
+
HfFileSystem, # noqa: F401
|
726 |
+
HfFileSystemFile, # noqa: F401
|
727 |
+
HfFileSystemResolvedPath, # noqa: F401
|
728 |
+
HfFileSystemStreamFile, # noqa: F401
|
729 |
+
)
|
730 |
+
from .hub_mixin import (
|
731 |
+
ModelHubMixin, # noqa: F401
|
732 |
+
PyTorchModelHubMixin, # noqa: F401
|
733 |
+
)
|
734 |
+
from .inference._client import (
|
735 |
+
InferenceClient, # noqa: F401
|
736 |
+
InferenceTimeoutError, # noqa: F401
|
737 |
+
)
|
738 |
+
from .inference._generated._async_client import AsyncInferenceClient # noqa: F401
|
739 |
+
from .inference._generated.types import (
|
740 |
+
AudioClassificationInput, # noqa: F401
|
741 |
+
AudioClassificationOutputElement, # noqa: F401
|
742 |
+
AudioClassificationParameters, # noqa: F401
|
743 |
+
AudioToAudioInput, # noqa: F401
|
744 |
+
AudioToAudioOutputElement, # noqa: F401
|
745 |
+
AutomaticSpeechRecognitionGenerationParameters, # noqa: F401
|
746 |
+
AutomaticSpeechRecognitionInput, # noqa: F401
|
747 |
+
AutomaticSpeechRecognitionOutput, # noqa: F401
|
748 |
+
AutomaticSpeechRecognitionOutputChunk, # noqa: F401
|
749 |
+
AutomaticSpeechRecognitionParameters, # noqa: F401
|
750 |
+
ChatCompletionInput, # noqa: F401
|
751 |
+
ChatCompletionInputFunctionDefinition, # noqa: F401
|
752 |
+
ChatCompletionInputMessage, # noqa: F401
|
753 |
+
ChatCompletionInputTool, # noqa: F401
|
754 |
+
ChatCompletionInputToolCall, # noqa: F401
|
755 |
+
ChatCompletionInputToolTypeClass, # noqa: F401
|
756 |
+
ChatCompletionOutput, # noqa: F401
|
757 |
+
ChatCompletionOutputComplete, # noqa: F401
|
758 |
+
ChatCompletionOutputFunctionDefinition, # noqa: F401
|
759 |
+
ChatCompletionOutputLogprob, # noqa: F401
|
760 |
+
ChatCompletionOutputLogprobs, # noqa: F401
|
761 |
+
ChatCompletionOutputMessage, # noqa: F401
|
762 |
+
ChatCompletionOutputToolCall, # noqa: F401
|
763 |
+
ChatCompletionOutputTopLogprob, # noqa: F401
|
764 |
+
ChatCompletionOutputUsage, # noqa: F401
|
765 |
+
ChatCompletionStreamOutput, # noqa: F401
|
766 |
+
ChatCompletionStreamOutputChoice, # noqa: F401
|
767 |
+
ChatCompletionStreamOutputDelta, # noqa: F401
|
768 |
+
ChatCompletionStreamOutputDeltaToolCall, # noqa: F401
|
769 |
+
ChatCompletionStreamOutputFunction, # noqa: F401
|
770 |
+
ChatCompletionStreamOutputLogprob, # noqa: F401
|
771 |
+
ChatCompletionStreamOutputLogprobs, # noqa: F401
|
772 |
+
ChatCompletionStreamOutputTopLogprob, # noqa: F401
|
773 |
+
DepthEstimationInput, # noqa: F401
|
774 |
+
DepthEstimationOutput, # noqa: F401
|
775 |
+
DocumentQuestionAnsweringInput, # noqa: F401
|
776 |
+
DocumentQuestionAnsweringInputData, # noqa: F401
|
777 |
+
DocumentQuestionAnsweringOutputElement, # noqa: F401
|
778 |
+
DocumentQuestionAnsweringParameters, # noqa: F401
|
779 |
+
FeatureExtractionInput, # noqa: F401
|
780 |
+
FillMaskInput, # noqa: F401
|
781 |
+
FillMaskOutputElement, # noqa: F401
|
782 |
+
FillMaskParameters, # noqa: F401
|
783 |
+
ImageClassificationInput, # noqa: F401
|
784 |
+
ImageClassificationOutputElement, # noqa: F401
|
785 |
+
ImageClassificationParameters, # noqa: F401
|
786 |
+
ImageSegmentationInput, # noqa: F401
|
787 |
+
ImageSegmentationOutputElement, # noqa: F401
|
788 |
+
ImageSegmentationParameters, # noqa: F401
|
789 |
+
ImageToImageInput, # noqa: F401
|
790 |
+
ImageToImageOutput, # noqa: F401
|
791 |
+
ImageToImageParameters, # noqa: F401
|
792 |
+
ImageToImageTargetSize, # noqa: F401
|
793 |
+
ImageToTextGenerationParameters, # noqa: F401
|
794 |
+
ImageToTextInput, # noqa: F401
|
795 |
+
ImageToTextOutput, # noqa: F401
|
796 |
+
ImageToTextParameters, # noqa: F401
|
797 |
+
ObjectDetectionBoundingBox, # noqa: F401
|
798 |
+
ObjectDetectionInput, # noqa: F401
|
799 |
+
ObjectDetectionOutputElement, # noqa: F401
|
800 |
+
ObjectDetectionParameters, # noqa: F401
|
801 |
+
QuestionAnsweringInput, # noqa: F401
|
802 |
+
QuestionAnsweringInputData, # noqa: F401
|
803 |
+
QuestionAnsweringOutputElement, # noqa: F401
|
804 |
+
QuestionAnsweringParameters, # noqa: F401
|
805 |
+
SentenceSimilarityInput, # noqa: F401
|
806 |
+
SentenceSimilarityInputData, # noqa: F401
|
807 |
+
SummarizationGenerationParameters, # noqa: F401
|
808 |
+
SummarizationInput, # noqa: F401
|
809 |
+
SummarizationOutput, # noqa: F401
|
810 |
+
TableQuestionAnsweringInput, # noqa: F401
|
811 |
+
TableQuestionAnsweringInputData, # noqa: F401
|
812 |
+
TableQuestionAnsweringOutputElement, # noqa: F401
|
813 |
+
Text2TextGenerationInput, # noqa: F401
|
814 |
+
Text2TextGenerationOutput, # noqa: F401
|
815 |
+
Text2TextGenerationParameters, # noqa: F401
|
816 |
+
TextClassificationInput, # noqa: F401
|
817 |
+
TextClassificationOutputElement, # noqa: F401
|
818 |
+
TextClassificationParameters, # noqa: F401
|
819 |
+
TextGenerationInput, # noqa: F401
|
820 |
+
TextGenerationInputGenerateParameters, # noqa: F401
|
821 |
+
TextGenerationInputGrammarType, # noqa: F401
|
822 |
+
TextGenerationOutput, # noqa: F401
|
823 |
+
TextGenerationOutputBestOfSequence, # noqa: F401
|
824 |
+
TextGenerationOutputDetails, # noqa: F401
|
825 |
+
TextGenerationOutputPrefillToken, # noqa: F401
|
826 |
+
TextGenerationOutputToken, # noqa: F401
|
827 |
+
TextGenerationStreamOutput, # noqa: F401
|
828 |
+
TextGenerationStreamOutputStreamDetails, # noqa: F401
|
829 |
+
TextGenerationStreamOutputToken, # noqa: F401
|
830 |
+
TextToAudioGenerationParameters, # noqa: F401
|
831 |
+
TextToAudioInput, # noqa: F401
|
832 |
+
TextToAudioOutput, # noqa: F401
|
833 |
+
TextToAudioParameters, # noqa: F401
|
834 |
+
TextToImageInput, # noqa: F401
|
835 |
+
TextToImageOutput, # noqa: F401
|
836 |
+
TextToImageParameters, # noqa: F401
|
837 |
+
TextToImageTargetSize, # noqa: F401
|
838 |
+
TokenClassificationInput, # noqa: F401
|
839 |
+
TokenClassificationOutputElement, # noqa: F401
|
840 |
+
TokenClassificationParameters, # noqa: F401
|
841 |
+
TranslationGenerationParameters, # noqa: F401
|
842 |
+
TranslationInput, # noqa: F401
|
843 |
+
TranslationOutput, # noqa: F401
|
844 |
+
VideoClassificationInput, # noqa: F401
|
845 |
+
VideoClassificationOutputElement, # noqa: F401
|
846 |
+
VideoClassificationParameters, # noqa: F401
|
847 |
+
VisualQuestionAnsweringInput, # noqa: F401
|
848 |
+
VisualQuestionAnsweringInputData, # noqa: F401
|
849 |
+
VisualQuestionAnsweringOutputElement, # noqa: F401
|
850 |
+
VisualQuestionAnsweringParameters, # noqa: F401
|
851 |
+
ZeroShotClassificationInput, # noqa: F401
|
852 |
+
ZeroShotClassificationInputData, # noqa: F401
|
853 |
+
ZeroShotClassificationOutputElement, # noqa: F401
|
854 |
+
ZeroShotClassificationParameters, # noqa: F401
|
855 |
+
ZeroShotImageClassificationInput, # noqa: F401
|
856 |
+
ZeroShotImageClassificationInputData, # noqa: F401
|
857 |
+
ZeroShotImageClassificationOutputElement, # noqa: F401
|
858 |
+
ZeroShotImageClassificationParameters, # noqa: F401
|
859 |
+
ZeroShotObjectDetectionBoundingBox, # noqa: F401
|
860 |
+
ZeroShotObjectDetectionInput, # noqa: F401
|
861 |
+
ZeroShotObjectDetectionInputData, # noqa: F401
|
862 |
+
ZeroShotObjectDetectionOutputElement, # noqa: F401
|
863 |
+
)
|
864 |
+
from .inference_api import InferenceApi # noqa: F401
|
865 |
+
from .keras_mixin import (
|
866 |
+
KerasModelHubMixin, # noqa: F401
|
867 |
+
from_pretrained_keras, # noqa: F401
|
868 |
+
push_to_hub_keras, # noqa: F401
|
869 |
+
save_pretrained_keras, # noqa: F401
|
870 |
+
)
|
871 |
+
from .repocard import (
|
872 |
+
DatasetCard, # noqa: F401
|
873 |
+
ModelCard, # noqa: F401
|
874 |
+
RepoCard, # noqa: F401
|
875 |
+
SpaceCard, # noqa: F401
|
876 |
+
metadata_eval_result, # noqa: F401
|
877 |
+
metadata_load, # noqa: F401
|
878 |
+
metadata_save, # noqa: F401
|
879 |
+
metadata_update, # noqa: F401
|
880 |
+
)
|
881 |
+
from .repocard_data import (
|
882 |
+
CardData, # noqa: F401
|
883 |
+
DatasetCardData, # noqa: F401
|
884 |
+
EvalResult, # noqa: F401
|
885 |
+
ModelCardData, # noqa: F401
|
886 |
+
SpaceCardData, # noqa: F401
|
887 |
+
)
|
888 |
+
from .repository import Repository # noqa: F401
|
889 |
+
from .serialization import (
|
890 |
+
StateDictSplit, # noqa: F401
|
891 |
+
split_numpy_state_dict_into_shards, # noqa: F401
|
892 |
+
split_state_dict_into_shards_factory, # noqa: F401
|
893 |
+
split_tf_state_dict_into_shards, # noqa: F401
|
894 |
+
split_torch_state_dict_into_shards, # noqa: F401
|
895 |
+
)
|
896 |
+
from .utils import (
|
897 |
+
CachedFileInfo, # noqa: F401
|
898 |
+
CachedRepoInfo, # noqa: F401
|
899 |
+
CachedRevisionInfo, # noqa: F401
|
900 |
+
CacheNotFound, # noqa: F401
|
901 |
+
CorruptedCacheException, # noqa: F401
|
902 |
+
DeleteCacheStrategy, # noqa: F401
|
903 |
+
HFCacheInfo, # noqa: F401
|
904 |
+
HfFolder, # noqa: F401
|
905 |
+
cached_assets_path, # noqa: F401
|
906 |
+
configure_http_backend, # noqa: F401
|
907 |
+
dump_environment_info, # noqa: F401
|
908 |
+
get_session, # noqa: F401
|
909 |
+
get_token, # noqa: F401
|
910 |
+
logging, # noqa: F401
|
911 |
+
scan_cache_dir, # noqa: F401
|
912 |
+
)
|
913 |
+
from .utils.endpoint_helpers import (
|
914 |
+
DatasetFilter, # noqa: F401
|
915 |
+
ModelFilter, # noqa: F401
|
916 |
+
)
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-310.pyc
ADDED
Binary file (12.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-310.pyc
ADDED
Binary file (14.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_local_folder.cpython-310.pyc
ADDED
Binary file (6.95 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_multi_commits.cpython-310.pyc
ADDED
Binary file (11.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/_space_api.cpython-310.pyc
ADDED
Binary file (5.26 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-310.pyc
ADDED
Binary file (14.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/hf_file_system.cpython-310.pyc
ADDED
Binary file (24 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-310.pyc
ADDED
Binary file (27.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/keras_mixin.cpython-310.pyc
ADDED
Binary file (17 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/lfs.cpython-310.pyc
ADDED
Binary file (16.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/__pycache__/repocard.cpython-310.pyc
ADDED
Binary file (29.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/_commit_api.py
ADDED
@@ -0,0 +1,699 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Type definitions and utilities for the `create_commit` API
|
3 |
+
"""
|
4 |
+
|
5 |
+
import base64
|
6 |
+
import io
|
7 |
+
import os
|
8 |
+
import warnings
|
9 |
+
from collections import defaultdict
|
10 |
+
from contextlib import contextmanager
|
11 |
+
from dataclasses import dataclass, field
|
12 |
+
from itertools import groupby
|
13 |
+
from pathlib import Path, PurePosixPath
|
14 |
+
from typing import TYPE_CHECKING, Any, BinaryIO, Dict, Iterable, Iterator, List, Literal, Optional, Tuple, Union
|
15 |
+
|
16 |
+
from tqdm.contrib.concurrent import thread_map
|
17 |
+
|
18 |
+
from .constants import ENDPOINT, HF_HUB_ENABLE_HF_TRANSFER
|
19 |
+
from .file_download import hf_hub_url
|
20 |
+
from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info
|
21 |
+
from .utils import (
|
22 |
+
FORBIDDEN_FOLDERS,
|
23 |
+
EntryNotFoundError,
|
24 |
+
chunk_iterable,
|
25 |
+
get_session,
|
26 |
+
hf_raise_for_status,
|
27 |
+
logging,
|
28 |
+
tqdm_stream_file,
|
29 |
+
validate_hf_hub_args,
|
30 |
+
)
|
31 |
+
from .utils import tqdm as hf_tqdm
|
32 |
+
|
33 |
+
|
34 |
+
if TYPE_CHECKING:
|
35 |
+
from .hf_api import RepoFile
|
36 |
+
|
37 |
+
|
38 |
+
logger = logging.get_logger(__name__)
|
39 |
+
|
40 |
+
|
41 |
+
UploadMode = Literal["lfs", "regular"]
|
42 |
+
|
43 |
+
# Max is 1,000 per request on the Hub for HfApi.get_paths_info
|
44 |
+
# Otherwise we get:
|
45 |
+
# HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters
|
46 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1503
|
47 |
+
FETCH_LFS_BATCH_SIZE = 500
|
48 |
+
|
49 |
+
|
50 |
+
@dataclass
|
51 |
+
class CommitOperationDelete:
|
52 |
+
"""
|
53 |
+
Data structure holding necessary info to delete a file or a folder from a repository
|
54 |
+
on the Hub.
|
55 |
+
|
56 |
+
Args:
|
57 |
+
path_in_repo (`str`):
|
58 |
+
Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
|
59 |
+
for a file or `"checkpoints/1fec34a/"` for a folder.
|
60 |
+
is_folder (`bool` or `Literal["auto"]`, *optional*)
|
61 |
+
Whether the Delete Operation applies to a folder or not. If "auto", the path
|
62 |
+
type (file or folder) is guessed automatically by looking if path ends with
|
63 |
+
a "/" (folder) or not (file). To explicitly set the path type, you can set
|
64 |
+
`is_folder=True` or `is_folder=False`.
|
65 |
+
"""
|
66 |
+
|
67 |
+
path_in_repo: str
|
68 |
+
is_folder: Union[bool, Literal["auto"]] = "auto"
|
69 |
+
|
70 |
+
def __post_init__(self):
|
71 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
72 |
+
|
73 |
+
if self.is_folder == "auto":
|
74 |
+
self.is_folder = self.path_in_repo.endswith("/")
|
75 |
+
if not isinstance(self.is_folder, bool):
|
76 |
+
raise ValueError(
|
77 |
+
f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'."
|
78 |
+
)
|
79 |
+
|
80 |
+
|
81 |
+
@dataclass
|
82 |
+
class CommitOperationCopy:
|
83 |
+
"""
|
84 |
+
Data structure holding necessary info to copy a file in a repository on the Hub.
|
85 |
+
|
86 |
+
Limitations:
|
87 |
+
- Only LFS files can be copied. To copy a regular file, you need to download it locally and re-upload it
|
88 |
+
- Cross-repository copies are not supported.
|
89 |
+
|
90 |
+
Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
|
91 |
+
|
92 |
+
Args:
|
93 |
+
src_path_in_repo (`str`):
|
94 |
+
Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`.
|
95 |
+
path_in_repo (`str`):
|
96 |
+
Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`.
|
97 |
+
src_revision (`str`, *optional*):
|
98 |
+
The git revision of the file to be copied. Can be any valid git revision.
|
99 |
+
Default to the target commit revision.
|
100 |
+
"""
|
101 |
+
|
102 |
+
src_path_in_repo: str
|
103 |
+
path_in_repo: str
|
104 |
+
src_revision: Optional[str] = None
|
105 |
+
|
106 |
+
def __post_init__(self):
|
107 |
+
self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo)
|
108 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
109 |
+
|
110 |
+
|
111 |
+
@dataclass
|
112 |
+
class CommitOperationAdd:
|
113 |
+
"""
|
114 |
+
Data structure holding necessary info to upload a file to a repository on the Hub.
|
115 |
+
|
116 |
+
Args:
|
117 |
+
path_in_repo (`str`):
|
118 |
+
Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
|
119 |
+
path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`):
|
120 |
+
Either:
|
121 |
+
- a path to a local file (as `str` or `pathlib.Path`) to upload
|
122 |
+
- a buffer of bytes (`bytes`) holding the content of the file to upload
|
123 |
+
- a "file object" (subclass of `io.BufferedIOBase`), typically obtained
|
124 |
+
with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
|
125 |
+
|
126 |
+
Raises:
|
127 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
128 |
+
If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`.
|
129 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
130 |
+
If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file.
|
131 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
132 |
+
If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both
|
133 |
+
`seek()` and `tell()`.
|
134 |
+
"""
|
135 |
+
|
136 |
+
path_in_repo: str
|
137 |
+
path_or_fileobj: Union[str, Path, bytes, BinaryIO]
|
138 |
+
upload_info: UploadInfo = field(init=False, repr=False)
|
139 |
+
|
140 |
+
# Internal attributes
|
141 |
+
|
142 |
+
# set to "lfs" or "regular" once known
|
143 |
+
_upload_mode: Optional[UploadMode] = field(init=False, repr=False, default=None)
|
144 |
+
|
145 |
+
# set to True if .gitignore rules prevent the file from being uploaded as LFS
|
146 |
+
# (server-side check)
|
147 |
+
_should_ignore: Optional[bool] = field(init=False, repr=False, default=None)
|
148 |
+
|
149 |
+
# set to True once the file has been uploaded as LFS
|
150 |
+
_is_uploaded: bool = field(init=False, repr=False, default=False)
|
151 |
+
|
152 |
+
# set to True once the file has been committed
|
153 |
+
_is_committed: bool = field(init=False, repr=False, default=False)
|
154 |
+
|
155 |
+
def __post_init__(self) -> None:
|
156 |
+
"""Validates `path_or_fileobj` and compute `upload_info`."""
|
157 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
158 |
+
|
159 |
+
# Validate `path_or_fileobj` value
|
160 |
+
if isinstance(self.path_or_fileobj, Path):
|
161 |
+
self.path_or_fileobj = str(self.path_or_fileobj)
|
162 |
+
if isinstance(self.path_or_fileobj, str):
|
163 |
+
path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj))
|
164 |
+
if not os.path.isfile(path_or_fileobj):
|
165 |
+
raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system")
|
166 |
+
elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)):
|
167 |
+
# ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode
|
168 |
+
raise ValueError(
|
169 |
+
"path_or_fileobj must be either an instance of str, bytes or"
|
170 |
+
" io.BufferedIOBase. If you passed a file-like object, make sure it is"
|
171 |
+
" in binary mode."
|
172 |
+
)
|
173 |
+
if isinstance(self.path_or_fileobj, io.BufferedIOBase):
|
174 |
+
try:
|
175 |
+
self.path_or_fileobj.tell()
|
176 |
+
self.path_or_fileobj.seek(0, os.SEEK_CUR)
|
177 |
+
except (OSError, AttributeError) as exc:
|
178 |
+
raise ValueError(
|
179 |
+
"path_or_fileobj is a file-like object but does not implement seek() and tell()"
|
180 |
+
) from exc
|
181 |
+
|
182 |
+
# Compute "upload_info" attribute
|
183 |
+
if isinstance(self.path_or_fileobj, str):
|
184 |
+
self.upload_info = UploadInfo.from_path(self.path_or_fileobj)
|
185 |
+
elif isinstance(self.path_or_fileobj, bytes):
|
186 |
+
self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj)
|
187 |
+
else:
|
188 |
+
self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj)
|
189 |
+
|
190 |
+
@contextmanager
|
191 |
+
def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]:
|
192 |
+
"""
|
193 |
+
A context manager that yields a file-like object allowing to read the underlying
|
194 |
+
data behind `path_or_fileobj`.
|
195 |
+
|
196 |
+
Args:
|
197 |
+
with_tqdm (`bool`, *optional*, defaults to `False`):
|
198 |
+
If True, iterating over the file object will display a progress bar. Only
|
199 |
+
works if the file-like object is a path to a file. Pure bytes and buffers
|
200 |
+
are not supported.
|
201 |
+
|
202 |
+
Example:
|
203 |
+
|
204 |
+
```python
|
205 |
+
>>> operation = CommitOperationAdd(
|
206 |
+
... path_in_repo="remote/dir/weights.h5",
|
207 |
+
... path_or_fileobj="./local/weights.h5",
|
208 |
+
... )
|
209 |
+
CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
|
210 |
+
|
211 |
+
>>> with operation.as_file() as file:
|
212 |
+
... content = file.read()
|
213 |
+
|
214 |
+
>>> with operation.as_file(with_tqdm=True) as file:
|
215 |
+
... while True:
|
216 |
+
... data = file.read(1024)
|
217 |
+
... if not data:
|
218 |
+
... break
|
219 |
+
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
220 |
+
|
221 |
+
>>> with operation.as_file(with_tqdm=True) as file:
|
222 |
+
... requests.put(..., data=file)
|
223 |
+
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
224 |
+
```
|
225 |
+
"""
|
226 |
+
if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path):
|
227 |
+
if with_tqdm:
|
228 |
+
with tqdm_stream_file(self.path_or_fileobj) as file:
|
229 |
+
yield file
|
230 |
+
else:
|
231 |
+
with open(self.path_or_fileobj, "rb") as file:
|
232 |
+
yield file
|
233 |
+
elif isinstance(self.path_or_fileobj, bytes):
|
234 |
+
yield io.BytesIO(self.path_or_fileobj)
|
235 |
+
elif isinstance(self.path_or_fileobj, io.BufferedIOBase):
|
236 |
+
prev_pos = self.path_or_fileobj.tell()
|
237 |
+
yield self.path_or_fileobj
|
238 |
+
self.path_or_fileobj.seek(prev_pos, io.SEEK_SET)
|
239 |
+
|
240 |
+
def b64content(self) -> bytes:
|
241 |
+
"""
|
242 |
+
The base64-encoded content of `path_or_fileobj`
|
243 |
+
|
244 |
+
Returns: `bytes`
|
245 |
+
"""
|
246 |
+
with self.as_file() as file:
|
247 |
+
return base64.b64encode(file.read())
|
248 |
+
|
249 |
+
|
250 |
+
def _validate_path_in_repo(path_in_repo: str) -> str:
|
251 |
+
# Validate `path_in_repo` value to prevent a server-side issue
|
252 |
+
if path_in_repo.startswith("/"):
|
253 |
+
path_in_repo = path_in_repo[1:]
|
254 |
+
if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"):
|
255 |
+
raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'")
|
256 |
+
if path_in_repo.startswith("./"):
|
257 |
+
path_in_repo = path_in_repo[2:]
|
258 |
+
for forbidden in FORBIDDEN_FOLDERS:
|
259 |
+
if any(part == forbidden for part in path_in_repo.split("/")):
|
260 |
+
raise ValueError(
|
261 |
+
f"Invalid `path_in_repo` in CommitOperation: cannot update files under a '{forbidden}/' folder (path:"
|
262 |
+
f" '{path_in_repo}')."
|
263 |
+
)
|
264 |
+
return path_in_repo
|
265 |
+
|
266 |
+
|
267 |
+
CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
|
268 |
+
|
269 |
+
|
270 |
+
def _warn_on_overwriting_operations(operations: List[CommitOperation]) -> None:
|
271 |
+
"""
|
272 |
+
Warn user when a list of operations is expected to overwrite itself in a single
|
273 |
+
commit.
|
274 |
+
|
275 |
+
Rules:
|
276 |
+
- If a filepath is updated by multiple `CommitOperationAdd` operations, a warning
|
277 |
+
message is triggered.
|
278 |
+
- If a filepath is updated at least once by a `CommitOperationAdd` and then deleted
|
279 |
+
by a `CommitOperationDelete`, a warning is triggered.
|
280 |
+
- If a `CommitOperationDelete` deletes a filepath that is then updated by a
|
281 |
+
`CommitOperationAdd`, no warning is triggered. This is usually useless (no need to
|
282 |
+
delete before upload) but can happen if a user deletes an entire folder and then
|
283 |
+
add new files to it.
|
284 |
+
"""
|
285 |
+
nb_additions_per_path: Dict[str, int] = defaultdict(int)
|
286 |
+
for operation in operations:
|
287 |
+
path_in_repo = operation.path_in_repo
|
288 |
+
if isinstance(operation, CommitOperationAdd):
|
289 |
+
if nb_additions_per_path[path_in_repo] > 0:
|
290 |
+
warnings.warn(
|
291 |
+
"About to update multiple times the same file in the same commit:"
|
292 |
+
f" '{path_in_repo}'. This can cause undesired inconsistencies in"
|
293 |
+
" your repo."
|
294 |
+
)
|
295 |
+
nb_additions_per_path[path_in_repo] += 1
|
296 |
+
for parent in PurePosixPath(path_in_repo).parents:
|
297 |
+
# Also keep track of number of updated files per folder
|
298 |
+
# => warns if deleting a folder overwrite some contained files
|
299 |
+
nb_additions_per_path[str(parent)] += 1
|
300 |
+
if isinstance(operation, CommitOperationDelete):
|
301 |
+
if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0:
|
302 |
+
if operation.is_folder:
|
303 |
+
warnings.warn(
|
304 |
+
"About to delete a folder containing files that have just been"
|
305 |
+
f" updated within the same commit: '{path_in_repo}'. This can"
|
306 |
+
" cause undesired inconsistencies in your repo."
|
307 |
+
)
|
308 |
+
else:
|
309 |
+
warnings.warn(
|
310 |
+
"About to delete a file that have just been updated within the"
|
311 |
+
f" same commit: '{path_in_repo}'. This can cause undesired"
|
312 |
+
" inconsistencies in your repo."
|
313 |
+
)
|
314 |
+
|
315 |
+
|
316 |
+
@validate_hf_hub_args
|
317 |
+
def _upload_lfs_files(
|
318 |
+
*,
|
319 |
+
additions: List[CommitOperationAdd],
|
320 |
+
repo_type: str,
|
321 |
+
repo_id: str,
|
322 |
+
headers: Dict[str, str],
|
323 |
+
endpoint: Optional[str] = None,
|
324 |
+
num_threads: int = 5,
|
325 |
+
revision: Optional[str] = None,
|
326 |
+
):
|
327 |
+
"""
|
328 |
+
Uploads the content of `additions` to the Hub using the large file storage protocol.
|
329 |
+
|
330 |
+
Relevant external documentation:
|
331 |
+
- LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
|
332 |
+
|
333 |
+
Args:
|
334 |
+
additions (`List` of `CommitOperationAdd`):
|
335 |
+
The files to be uploaded
|
336 |
+
repo_type (`str`):
|
337 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
338 |
+
repo_id (`str`):
|
339 |
+
A namespace (user or an organization) and a repo name separated
|
340 |
+
by a `/`.
|
341 |
+
headers (`Dict[str, str]`):
|
342 |
+
Headers to use for the request, including authorization headers and user agent.
|
343 |
+
num_threads (`int`, *optional*):
|
344 |
+
The number of concurrent threads to use when uploading. Defaults to 5.
|
345 |
+
revision (`str`, *optional*):
|
346 |
+
The git revision to upload to.
|
347 |
+
|
348 |
+
Raises: `RuntimeError` if an upload failed for any reason
|
349 |
+
|
350 |
+
Raises: `ValueError` if the server returns malformed responses
|
351 |
+
|
352 |
+
Raises: `requests.HTTPError` if the LFS batch endpoint returned an HTTP
|
353 |
+
error
|
354 |
+
|
355 |
+
"""
|
356 |
+
# Step 1: retrieve upload instructions from the LFS batch endpoint.
|
357 |
+
# Upload instructions are retrieved by chunk of 256 files to avoid reaching
|
358 |
+
# the payload limit.
|
359 |
+
batch_actions: List[Dict] = []
|
360 |
+
for chunk in chunk_iterable(additions, chunk_size=256):
|
361 |
+
batch_actions_chunk, batch_errors_chunk = post_lfs_batch_info(
|
362 |
+
upload_infos=[op.upload_info for op in chunk],
|
363 |
+
repo_id=repo_id,
|
364 |
+
repo_type=repo_type,
|
365 |
+
revision=revision,
|
366 |
+
endpoint=endpoint,
|
367 |
+
headers=headers,
|
368 |
+
token=None, # already passed in 'headers'
|
369 |
+
)
|
370 |
+
|
371 |
+
# If at least 1 error, we do not retrieve information for other chunks
|
372 |
+
if batch_errors_chunk:
|
373 |
+
message = "\n".join(
|
374 |
+
[
|
375 |
+
f'Encountered error for file with OID {err.get("oid")}: `{err.get("error", {}).get("message")}'
|
376 |
+
for err in batch_errors_chunk
|
377 |
+
]
|
378 |
+
)
|
379 |
+
raise ValueError(f"LFS batch endpoint returned errors:\n{message}")
|
380 |
+
|
381 |
+
batch_actions += batch_actions_chunk
|
382 |
+
oid2addop = {add_op.upload_info.sha256.hex(): add_op for add_op in additions}
|
383 |
+
|
384 |
+
# Step 2: ignore files that have already been uploaded
|
385 |
+
filtered_actions = []
|
386 |
+
for action in batch_actions:
|
387 |
+
if action.get("actions") is None:
|
388 |
+
logger.debug(
|
389 |
+
f"Content of file {oid2addop[action['oid']].path_in_repo} is already"
|
390 |
+
" present upstream - skipping upload."
|
391 |
+
)
|
392 |
+
else:
|
393 |
+
filtered_actions.append(action)
|
394 |
+
|
395 |
+
if len(filtered_actions) == 0:
|
396 |
+
logger.debug("No LFS files to upload.")
|
397 |
+
return
|
398 |
+
|
399 |
+
# Step 3: upload files concurrently according to these instructions
|
400 |
+
def _wrapped_lfs_upload(batch_action) -> None:
|
401 |
+
try:
|
402 |
+
operation = oid2addop[batch_action["oid"]]
|
403 |
+
lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint)
|
404 |
+
except Exception as exc:
|
405 |
+
raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
|
406 |
+
|
407 |
+
if HF_HUB_ENABLE_HF_TRANSFER:
|
408 |
+
logger.debug(f"Uploading {len(filtered_actions)} LFS files to the Hub using `hf_transfer`.")
|
409 |
+
for action in hf_tqdm(filtered_actions, name="huggingface_hub.lfs_upload"):
|
410 |
+
_wrapped_lfs_upload(action)
|
411 |
+
elif len(filtered_actions) == 1:
|
412 |
+
logger.debug("Uploading 1 LFS file to the Hub")
|
413 |
+
_wrapped_lfs_upload(filtered_actions[0])
|
414 |
+
else:
|
415 |
+
logger.debug(
|
416 |
+
f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently"
|
417 |
+
)
|
418 |
+
thread_map(
|
419 |
+
_wrapped_lfs_upload,
|
420 |
+
filtered_actions,
|
421 |
+
desc=f"Upload {len(filtered_actions)} LFS files",
|
422 |
+
max_workers=num_threads,
|
423 |
+
tqdm_class=hf_tqdm,
|
424 |
+
)
|
425 |
+
|
426 |
+
|
427 |
+
def _validate_preupload_info(preupload_info: dict):
|
428 |
+
files = preupload_info.get("files")
|
429 |
+
if not isinstance(files, list):
|
430 |
+
raise ValueError("preupload_info is improperly formatted")
|
431 |
+
for file_info in files:
|
432 |
+
if not (
|
433 |
+
isinstance(file_info, dict)
|
434 |
+
and isinstance(file_info.get("path"), str)
|
435 |
+
and isinstance(file_info.get("uploadMode"), str)
|
436 |
+
and (file_info["uploadMode"] in ("lfs", "regular"))
|
437 |
+
):
|
438 |
+
raise ValueError("preupload_info is improperly formatted:")
|
439 |
+
return preupload_info
|
440 |
+
|
441 |
+
|
442 |
+
@validate_hf_hub_args
|
443 |
+
def _fetch_upload_modes(
|
444 |
+
additions: Iterable[CommitOperationAdd],
|
445 |
+
repo_type: str,
|
446 |
+
repo_id: str,
|
447 |
+
headers: Dict[str, str],
|
448 |
+
revision: str,
|
449 |
+
endpoint: Optional[str] = None,
|
450 |
+
create_pr: bool = False,
|
451 |
+
gitignore_content: Optional[str] = None,
|
452 |
+
) -> None:
|
453 |
+
"""
|
454 |
+
Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob
|
455 |
+
or as git LFS blob. Input `additions` are mutated in-place with the upload mode.
|
456 |
+
|
457 |
+
Args:
|
458 |
+
additions (`Iterable` of :class:`CommitOperationAdd`):
|
459 |
+
Iterable of :class:`CommitOperationAdd` describing the files to
|
460 |
+
upload to the Hub.
|
461 |
+
repo_type (`str`):
|
462 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
463 |
+
repo_id (`str`):
|
464 |
+
A namespace (user or an organization) and a repo name separated
|
465 |
+
by a `/`.
|
466 |
+
headers (`Dict[str, str]`):
|
467 |
+
Headers to use for the request, including authorization headers and user agent.
|
468 |
+
revision (`str`):
|
469 |
+
The git revision to upload the files to. Can be any valid git revision.
|
470 |
+
gitignore_content (`str`, *optional*):
|
471 |
+
The content of the `.gitignore` file to know which files should be ignored. The order of priority
|
472 |
+
is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
|
473 |
+
in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
|
474 |
+
(if any).
|
475 |
+
Raises:
|
476 |
+
[`~utils.HfHubHTTPError`]
|
477 |
+
If the Hub API returned an error.
|
478 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
479 |
+
If the Hub API response is improperly formatted.
|
480 |
+
"""
|
481 |
+
endpoint = endpoint if endpoint is not None else ENDPOINT
|
482 |
+
|
483 |
+
# Fetch upload mode (LFS or regular) chunk by chunk.
|
484 |
+
upload_modes: Dict[str, UploadMode] = {}
|
485 |
+
should_ignore_info: Dict[str, bool] = {}
|
486 |
+
|
487 |
+
for chunk in chunk_iterable(additions, 256):
|
488 |
+
payload: Dict = {
|
489 |
+
"files": [
|
490 |
+
{
|
491 |
+
"path": op.path_in_repo,
|
492 |
+
"sample": base64.b64encode(op.upload_info.sample).decode("ascii"),
|
493 |
+
"size": op.upload_info.size,
|
494 |
+
"sha": op.upload_info.sha256.hex(),
|
495 |
+
}
|
496 |
+
for op in chunk
|
497 |
+
]
|
498 |
+
}
|
499 |
+
if gitignore_content is not None:
|
500 |
+
payload["gitIgnore"] = gitignore_content
|
501 |
+
|
502 |
+
resp = get_session().post(
|
503 |
+
f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}",
|
504 |
+
json=payload,
|
505 |
+
headers=headers,
|
506 |
+
params={"create_pr": "1"} if create_pr else None,
|
507 |
+
)
|
508 |
+
hf_raise_for_status(resp)
|
509 |
+
preupload_info = _validate_preupload_info(resp.json())
|
510 |
+
upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]})
|
511 |
+
should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]})
|
512 |
+
|
513 |
+
# Set upload mode for each addition operation
|
514 |
+
for addition in additions:
|
515 |
+
addition._upload_mode = upload_modes[addition.path_in_repo]
|
516 |
+
addition._should_ignore = should_ignore_info[addition.path_in_repo]
|
517 |
+
|
518 |
+
# Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented)
|
519 |
+
# => empty files are uploaded as "regular" to still allow users to commit them.
|
520 |
+
for addition in additions:
|
521 |
+
if addition.upload_info.size == 0:
|
522 |
+
addition._upload_mode = "regular"
|
523 |
+
|
524 |
+
|
525 |
+
@validate_hf_hub_args
|
526 |
+
def _fetch_files_to_copy(
|
527 |
+
copies: Iterable[CommitOperationCopy],
|
528 |
+
repo_type: str,
|
529 |
+
repo_id: str,
|
530 |
+
headers: Dict[str, str],
|
531 |
+
revision: str,
|
532 |
+
endpoint: Optional[str] = None,
|
533 |
+
) -> Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]]:
|
534 |
+
"""
|
535 |
+
Fetch information about the files to copy.
|
536 |
+
|
537 |
+
For LFS files, we only need their metadata (file size and sha256) while for regular files
|
538 |
+
we need to download the raw content from the Hub.
|
539 |
+
|
540 |
+
Args:
|
541 |
+
copies (`Iterable` of :class:`CommitOperationCopy`):
|
542 |
+
Iterable of :class:`CommitOperationCopy` describing the files to
|
543 |
+
copy on the Hub.
|
544 |
+
repo_type (`str`):
|
545 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
546 |
+
repo_id (`str`):
|
547 |
+
A namespace (user or an organization) and a repo name separated
|
548 |
+
by a `/`.
|
549 |
+
headers (`Dict[str, str]`):
|
550 |
+
Headers to use for the request, including authorization headers and user agent.
|
551 |
+
revision (`str`):
|
552 |
+
The git revision to upload the files to. Can be any valid git revision.
|
553 |
+
|
554 |
+
Returns: `Dict[Tuple[str, Optional[str]], Union[RepoFile, bytes]]]`
|
555 |
+
Key is the file path and revision of the file to copy.
|
556 |
+
Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files).
|
557 |
+
|
558 |
+
Raises:
|
559 |
+
[`~utils.HfHubHTTPError`]
|
560 |
+
If the Hub API returned an error.
|
561 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
562 |
+
If the Hub API response is improperly formatted.
|
563 |
+
"""
|
564 |
+
from .hf_api import HfApi, RepoFolder
|
565 |
+
|
566 |
+
hf_api = HfApi(endpoint=endpoint, headers=headers)
|
567 |
+
files_to_copy: Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]] = {}
|
568 |
+
for src_revision, operations in groupby(copies, key=lambda op: op.src_revision):
|
569 |
+
operations = list(operations) # type: ignore
|
570 |
+
paths = [op.src_path_in_repo for op in operations]
|
571 |
+
for offset in range(0, len(paths), FETCH_LFS_BATCH_SIZE):
|
572 |
+
src_repo_files = hf_api.get_paths_info(
|
573 |
+
repo_id=repo_id,
|
574 |
+
paths=paths[offset : offset + FETCH_LFS_BATCH_SIZE],
|
575 |
+
revision=src_revision or revision,
|
576 |
+
repo_type=repo_type,
|
577 |
+
)
|
578 |
+
for src_repo_file in src_repo_files:
|
579 |
+
if isinstance(src_repo_file, RepoFolder):
|
580 |
+
raise NotImplementedError("Copying a folder is not implemented.")
|
581 |
+
if src_repo_file.lfs:
|
582 |
+
files_to_copy[(src_repo_file.path, src_revision)] = src_repo_file
|
583 |
+
else:
|
584 |
+
# TODO: (optimization) download regular files to copy concurrently
|
585 |
+
url = hf_hub_url(
|
586 |
+
endpoint=endpoint,
|
587 |
+
repo_type=repo_type,
|
588 |
+
repo_id=repo_id,
|
589 |
+
revision=src_revision or revision,
|
590 |
+
filename=src_repo_file.path,
|
591 |
+
)
|
592 |
+
response = get_session().get(url, headers=headers)
|
593 |
+
hf_raise_for_status(response)
|
594 |
+
files_to_copy[(src_repo_file.path, src_revision)] = response.content
|
595 |
+
for operation in operations:
|
596 |
+
if (operation.src_path_in_repo, src_revision) not in files_to_copy:
|
597 |
+
raise EntryNotFoundError(
|
598 |
+
f"Cannot copy {operation.src_path_in_repo} at revision "
|
599 |
+
f"{src_revision or revision}: file is missing on repo."
|
600 |
+
)
|
601 |
+
return files_to_copy
|
602 |
+
|
603 |
+
|
604 |
+
def _prepare_commit_payload(
|
605 |
+
operations: Iterable[CommitOperation],
|
606 |
+
files_to_copy: Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]],
|
607 |
+
commit_message: str,
|
608 |
+
commit_description: Optional[str] = None,
|
609 |
+
parent_commit: Optional[str] = None,
|
610 |
+
) -> Iterable[Dict[str, Any]]:
|
611 |
+
"""
|
612 |
+
Builds the payload to POST to the `/commit` API of the Hub.
|
613 |
+
|
614 |
+
Payload is returned as an iterator so that it can be streamed as a ndjson in the
|
615 |
+
POST request.
|
616 |
+
|
617 |
+
For more information, see:
|
618 |
+
- https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
|
619 |
+
- http://ndjson.org/
|
620 |
+
"""
|
621 |
+
commit_description = commit_description if commit_description is not None else ""
|
622 |
+
|
623 |
+
# 1. Send a header item with the commit metadata
|
624 |
+
header_value = {"summary": commit_message, "description": commit_description}
|
625 |
+
if parent_commit is not None:
|
626 |
+
header_value["parentCommit"] = parent_commit
|
627 |
+
yield {"key": "header", "value": header_value}
|
628 |
+
|
629 |
+
nb_ignored_files = 0
|
630 |
+
|
631 |
+
# 2. Send operations, one per line
|
632 |
+
for operation in operations:
|
633 |
+
# Skip ignored files
|
634 |
+
if isinstance(operation, CommitOperationAdd) and operation._should_ignore:
|
635 |
+
logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).")
|
636 |
+
nb_ignored_files += 1
|
637 |
+
continue
|
638 |
+
|
639 |
+
# 2.a. Case adding a regular file
|
640 |
+
if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular":
|
641 |
+
yield {
|
642 |
+
"key": "file",
|
643 |
+
"value": {
|
644 |
+
"content": operation.b64content().decode(),
|
645 |
+
"path": operation.path_in_repo,
|
646 |
+
"encoding": "base64",
|
647 |
+
},
|
648 |
+
}
|
649 |
+
# 2.b. Case adding an LFS file
|
650 |
+
elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs":
|
651 |
+
yield {
|
652 |
+
"key": "lfsFile",
|
653 |
+
"value": {
|
654 |
+
"path": operation.path_in_repo,
|
655 |
+
"algo": "sha256",
|
656 |
+
"oid": operation.upload_info.sha256.hex(),
|
657 |
+
"size": operation.upload_info.size,
|
658 |
+
},
|
659 |
+
}
|
660 |
+
# 2.c. Case deleting a file or folder
|
661 |
+
elif isinstance(operation, CommitOperationDelete):
|
662 |
+
yield {
|
663 |
+
"key": "deletedFolder" if operation.is_folder else "deletedFile",
|
664 |
+
"value": {"path": operation.path_in_repo},
|
665 |
+
}
|
666 |
+
# 2.d. Case copying a file or folder
|
667 |
+
elif isinstance(operation, CommitOperationCopy):
|
668 |
+
file_to_copy = files_to_copy[(operation.src_path_in_repo, operation.src_revision)]
|
669 |
+
if isinstance(file_to_copy, bytes):
|
670 |
+
yield {
|
671 |
+
"key": "file",
|
672 |
+
"value": {
|
673 |
+
"content": base64.b64encode(file_to_copy).decode(),
|
674 |
+
"path": operation.path_in_repo,
|
675 |
+
"encoding": "base64",
|
676 |
+
},
|
677 |
+
}
|
678 |
+
elif file_to_copy.lfs:
|
679 |
+
yield {
|
680 |
+
"key": "lfsFile",
|
681 |
+
"value": {
|
682 |
+
"path": operation.path_in_repo,
|
683 |
+
"algo": "sha256",
|
684 |
+
"oid": file_to_copy.lfs.sha256,
|
685 |
+
},
|
686 |
+
}
|
687 |
+
else:
|
688 |
+
raise ValueError(
|
689 |
+
"Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info."
|
690 |
+
)
|
691 |
+
# 2.e. Never expected to happen
|
692 |
+
else:
|
693 |
+
raise ValueError(
|
694 |
+
f"Unknown operation to commit. Operation: {operation}. Upload mode:"
|
695 |
+
f" {getattr(operation, '_upload_mode', None)}"
|
696 |
+
)
|
697 |
+
|
698 |
+
if nb_ignored_files > 0:
|
699 |
+
logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).")
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py
ADDED
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 Dict, List, Optional, Union
|
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 scheduler is started when instantiated and run indefinitely. At the end of your script, a last commit is
|
34 |
+
triggered. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
|
35 |
+
to learn more about how to use it.
|
36 |
+
|
37 |
+
Args:
|
38 |
+
repo_id (`str`):
|
39 |
+
The id of the repo to commit to.
|
40 |
+
folder_path (`str` or `Path`):
|
41 |
+
Path to the local folder to upload regularly.
|
42 |
+
every (`int` or `float`, *optional*):
|
43 |
+
The number of minutes between each commit. Defaults to 5 minutes.
|
44 |
+
path_in_repo (`str`, *optional*):
|
45 |
+
Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
|
46 |
+
of the repository.
|
47 |
+
repo_type (`str`, *optional*):
|
48 |
+
The type of the repo to commit to. Defaults to `model`.
|
49 |
+
revision (`str`, *optional*):
|
50 |
+
The revision of the repo to commit to. Defaults to `main`.
|
51 |
+
private (`bool`, *optional*):
|
52 |
+
Whether to make the repo private. Defaults to `False`. This value is ignored if the repo already exist.
|
53 |
+
token (`str`, *optional*):
|
54 |
+
The token to use to commit to the repo. Defaults to the token saved on the machine.
|
55 |
+
allow_patterns (`List[str]` or `str`, *optional*):
|
56 |
+
If provided, only files matching at least one pattern are uploaded.
|
57 |
+
ignore_patterns (`List[str]` or `str`, *optional*):
|
58 |
+
If provided, files matching any of the patterns are not uploaded.
|
59 |
+
squash_history (`bool`, *optional*):
|
60 |
+
Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
|
61 |
+
useful to avoid degraded performances on the repo when it grows too large.
|
62 |
+
hf_api (`HfApi`, *optional*):
|
63 |
+
The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
|
64 |
+
|
65 |
+
Example:
|
66 |
+
```py
|
67 |
+
>>> from pathlib import Path
|
68 |
+
>>> from huggingface_hub import CommitScheduler
|
69 |
+
|
70 |
+
# Scheduler uploads every 10 minutes
|
71 |
+
>>> csv_path = Path("watched_folder/data.csv")
|
72 |
+
>>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
|
73 |
+
|
74 |
+
>>> with csv_path.open("a") as f:
|
75 |
+
... f.write("first line")
|
76 |
+
|
77 |
+
# Some time later (...)
|
78 |
+
>>> with csv_path.open("a") as f:
|
79 |
+
... f.write("second line")
|
80 |
+
```
|
81 |
+
"""
|
82 |
+
|
83 |
+
def __init__(
|
84 |
+
self,
|
85 |
+
*,
|
86 |
+
repo_id: str,
|
87 |
+
folder_path: Union[str, Path],
|
88 |
+
every: Union[int, float] = 5,
|
89 |
+
path_in_repo: Optional[str] = None,
|
90 |
+
repo_type: Optional[str] = None,
|
91 |
+
revision: Optional[str] = None,
|
92 |
+
private: bool = False,
|
93 |
+
token: Optional[str] = None,
|
94 |
+
allow_patterns: Optional[Union[List[str], str]] = None,
|
95 |
+
ignore_patterns: Optional[Union[List[str], str]] = None,
|
96 |
+
squash_history: bool = False,
|
97 |
+
hf_api: Optional["HfApi"] = None,
|
98 |
+
) -> None:
|
99 |
+
self.api = hf_api or HfApi(token=token)
|
100 |
+
|
101 |
+
# Folder
|
102 |
+
self.folder_path = Path(folder_path).expanduser().resolve()
|
103 |
+
self.path_in_repo = path_in_repo or ""
|
104 |
+
self.allow_patterns = allow_patterns
|
105 |
+
|
106 |
+
if ignore_patterns is None:
|
107 |
+
ignore_patterns = []
|
108 |
+
elif isinstance(ignore_patterns, str):
|
109 |
+
ignore_patterns = [ignore_patterns]
|
110 |
+
self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
|
111 |
+
|
112 |
+
if self.folder_path.is_file():
|
113 |
+
raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.")
|
114 |
+
self.folder_path.mkdir(parents=True, exist_ok=True)
|
115 |
+
|
116 |
+
# Repository
|
117 |
+
repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True)
|
118 |
+
self.repo_id = repo_url.repo_id
|
119 |
+
self.repo_type = repo_type
|
120 |
+
self.revision = revision
|
121 |
+
self.token = token
|
122 |
+
|
123 |
+
# Keep track of already uploaded files
|
124 |
+
self.last_uploaded: Dict[Path, float] = {} # key is local path, value is timestamp
|
125 |
+
|
126 |
+
# Scheduler
|
127 |
+
if not every > 0:
|
128 |
+
raise ValueError(f"'every' must be a positive integer, not '{every}'.")
|
129 |
+
self.lock = Lock()
|
130 |
+
self.every = every
|
131 |
+
self.squash_history = squash_history
|
132 |
+
|
133 |
+
logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.")
|
134 |
+
self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
|
135 |
+
self._scheduler_thread.start()
|
136 |
+
atexit.register(self._push_to_hub)
|
137 |
+
|
138 |
+
self.__stopped = False
|
139 |
+
|
140 |
+
def stop(self) -> None:
|
141 |
+
"""Stop the scheduler.
|
142 |
+
|
143 |
+
A stopped scheduler cannot be restarted. Mostly for tests purposes.
|
144 |
+
"""
|
145 |
+
self.__stopped = True
|
146 |
+
|
147 |
+
def _run_scheduler(self) -> None:
|
148 |
+
"""Dumb thread waiting between each scheduled push to Hub."""
|
149 |
+
while True:
|
150 |
+
self.last_future = self.trigger()
|
151 |
+
time.sleep(self.every * 60)
|
152 |
+
if self.__stopped:
|
153 |
+
break
|
154 |
+
|
155 |
+
def trigger(self) -> Future:
|
156 |
+
"""Trigger a `push_to_hub` and return a future.
|
157 |
+
|
158 |
+
This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
|
159 |
+
immediately, without waiting for the next scheduled commit.
|
160 |
+
"""
|
161 |
+
return self.api.run_as_future(self._push_to_hub)
|
162 |
+
|
163 |
+
def _push_to_hub(self) -> Optional[CommitInfo]:
|
164 |
+
if self.__stopped: # If stopped, already scheduled commits are ignored
|
165 |
+
return None
|
166 |
+
|
167 |
+
logger.info("(Background) scheduled commit triggered.")
|
168 |
+
try:
|
169 |
+
value = self.push_to_hub()
|
170 |
+
if self.squash_history:
|
171 |
+
logger.info("(Background) squashing repo history.")
|
172 |
+
self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision)
|
173 |
+
return value
|
174 |
+
except Exception as e:
|
175 |
+
logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced
|
176 |
+
raise
|
177 |
+
|
178 |
+
def push_to_hub(self) -> Optional[CommitInfo]:
|
179 |
+
"""
|
180 |
+
Push folder to the Hub and return the commit info.
|
181 |
+
|
182 |
+
<Tip warning={true}>
|
183 |
+
|
184 |
+
This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
|
185 |
+
queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
|
186 |
+
issues.
|
187 |
+
|
188 |
+
</Tip>
|
189 |
+
|
190 |
+
The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
|
191 |
+
uploads only changed files. If no changes are found, the method returns without committing anything. If you want
|
192 |
+
to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
|
193 |
+
for example to compress data together in a single file before committing. For more details and examples, check
|
194 |
+
out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
|
195 |
+
"""
|
196 |
+
# Check files to upload (with lock)
|
197 |
+
with self.lock:
|
198 |
+
logger.debug("Listing files to upload for scheduled commit.")
|
199 |
+
|
200 |
+
# List files from folder (taken from `_prepare_upload_folder_additions`)
|
201 |
+
relpath_to_abspath = {
|
202 |
+
path.relative_to(self.folder_path).as_posix(): path
|
203 |
+
for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic
|
204 |
+
if path.is_file()
|
205 |
+
}
|
206 |
+
prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
|
207 |
+
|
208 |
+
# Filter with pattern + filter out unchanged files + retrieve current file size
|
209 |
+
files_to_upload: List[_FileToUpload] = []
|
210 |
+
for relpath in filter_repo_objects(
|
211 |
+
relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns
|
212 |
+
):
|
213 |
+
local_path = relpath_to_abspath[relpath]
|
214 |
+
stat = local_path.stat()
|
215 |
+
if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime:
|
216 |
+
files_to_upload.append(
|
217 |
+
_FileToUpload(
|
218 |
+
local_path=local_path,
|
219 |
+
path_in_repo=prefix + relpath,
|
220 |
+
size_limit=stat.st_size,
|
221 |
+
last_modified=stat.st_mtime,
|
222 |
+
)
|
223 |
+
)
|
224 |
+
|
225 |
+
# Return if nothing to upload
|
226 |
+
if len(files_to_upload) == 0:
|
227 |
+
logger.debug("Dropping schedule commit: no changed file to upload.")
|
228 |
+
return None
|
229 |
+
|
230 |
+
# Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
|
231 |
+
logger.debug("Removing unchanged files since previous scheduled commit.")
|
232 |
+
add_operations = [
|
233 |
+
CommitOperationAdd(
|
234 |
+
# Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
|
235 |
+
path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit),
|
236 |
+
path_in_repo=file_to_upload.path_in_repo,
|
237 |
+
)
|
238 |
+
for file_to_upload in files_to_upload
|
239 |
+
]
|
240 |
+
|
241 |
+
# Upload files (append mode expected - no need for lock)
|
242 |
+
logger.debug("Uploading files for scheduled commit.")
|
243 |
+
commit_info = self.api.create_commit(
|
244 |
+
repo_id=self.repo_id,
|
245 |
+
repo_type=self.repo_type,
|
246 |
+
operations=add_operations,
|
247 |
+
commit_message="Scheduled Commit",
|
248 |
+
revision=self.revision,
|
249 |
+
)
|
250 |
+
|
251 |
+
# Successful commit: keep track of the latest "last_modified" for each file
|
252 |
+
for file in files_to_upload:
|
253 |
+
self.last_uploaded[file.local_path] = file.last_modified
|
254 |
+
return commit_info
|
255 |
+
|
256 |
+
|
257 |
+
class PartialFileIO(BytesIO):
|
258 |
+
"""A file-like object that reads only the first part of a file.
|
259 |
+
|
260 |
+
Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the
|
261 |
+
file is uploaded (i.e. the part that was available when the filesystem was first scanned).
|
262 |
+
|
263 |
+
In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal
|
264 |
+
disturbance for the user. The object is passed to `CommitOperationAdd`.
|
265 |
+
|
266 |
+
Only supports `read`, `tell` and `seek` methods.
|
267 |
+
|
268 |
+
Args:
|
269 |
+
file_path (`str` or `Path`):
|
270 |
+
Path to the file to read.
|
271 |
+
size_limit (`int`):
|
272 |
+
The maximum number of bytes to read from the file. If the file is larger than this, only the first part
|
273 |
+
will be read (and uploaded).
|
274 |
+
"""
|
275 |
+
|
276 |
+
def __init__(self, file_path: Union[str, Path], size_limit: int) -> None:
|
277 |
+
self._file_path = Path(file_path)
|
278 |
+
self._file = self._file_path.open("rb")
|
279 |
+
self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
|
280 |
+
|
281 |
+
def __del__(self) -> None:
|
282 |
+
self._file.close()
|
283 |
+
return super().__del__()
|
284 |
+
|
285 |
+
def __repr__(self) -> str:
|
286 |
+
return f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
|
287 |
+
|
288 |
+
def __len__(self) -> int:
|
289 |
+
return self._size_limit
|
290 |
+
|
291 |
+
def __getattribute__(self, name: str):
|
292 |
+
if name.startswith("_") or name in ("read", "tell", "seek"): # only 3 public methods supported
|
293 |
+
return super().__getattribute__(name)
|
294 |
+
raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
|
295 |
+
|
296 |
+
def tell(self) -> int:
|
297 |
+
"""Return the current file position."""
|
298 |
+
return self._file.tell()
|
299 |
+
|
300 |
+
def seek(self, __offset: int, __whence: int = SEEK_SET) -> int:
|
301 |
+
"""Change the stream position to the given offset.
|
302 |
+
|
303 |
+
Behavior is the same as a regular file, except that the position is capped to the size limit.
|
304 |
+
"""
|
305 |
+
if __whence == SEEK_END:
|
306 |
+
# SEEK_END => set from the truncated end
|
307 |
+
__offset = len(self) + __offset
|
308 |
+
__whence = SEEK_SET
|
309 |
+
|
310 |
+
pos = self._file.seek(__offset, __whence)
|
311 |
+
if pos > self._size_limit:
|
312 |
+
return self._file.seek(self._size_limit)
|
313 |
+
return pos
|
314 |
+
|
315 |
+
def read(self, __size: Optional[int] = -1) -> bytes:
|
316 |
+
"""Read at most `__size` bytes from the file.
|
317 |
+
|
318 |
+
Behavior is the same as a regular file, except that it is capped to the size limit.
|
319 |
+
"""
|
320 |
+
current = self._file.tell()
|
321 |
+
if __size is None or __size < 0:
|
322 |
+
# Read until file limit
|
323 |
+
truncated_size = self._size_limit - current
|
324 |
+
else:
|
325 |
+
# Read until file limit or __size
|
326 |
+
truncated_size = min(__size, self._size_limit - current)
|
327 |
+
return self._file.read(truncated_size)
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py
ADDED
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, Dict, Optional, Union
|
6 |
+
|
7 |
+
from huggingface_hub.errors import InferenceEndpointError, InferenceEndpointTimeoutError
|
8 |
+
|
9 |
+
from .inference._client import InferenceClient
|
10 |
+
from .inference._generated._async_client import AsyncInferenceClient
|
11 |
+
from .utils import get_session, logging, parse_datetime
|
12 |
+
|
13 |
+
|
14 |
+
if TYPE_CHECKING:
|
15 |
+
from .hf_api import HfApi
|
16 |
+
|
17 |
+
|
18 |
+
logger = logging.get_logger(__name__)
|
19 |
+
|
20 |
+
|
21 |
+
class InferenceEndpointStatus(str, Enum):
|
22 |
+
PENDING = "pending"
|
23 |
+
INITIALIZING = "initializing"
|
24 |
+
UPDATING = "updating"
|
25 |
+
UPDATE_FAILED = "updateFailed"
|
26 |
+
RUNNING = "running"
|
27 |
+
PAUSED = "paused"
|
28 |
+
FAILED = "failed"
|
29 |
+
SCALED_TO_ZERO = "scaledToZero"
|
30 |
+
|
31 |
+
|
32 |
+
class InferenceEndpointType(str, Enum):
|
33 |
+
PUBlIC = "public"
|
34 |
+
PROTECTED = "protected"
|
35 |
+
PRIVATE = "private"
|
36 |
+
|
37 |
+
|
38 |
+
@dataclass
|
39 |
+
class InferenceEndpoint:
|
40 |
+
"""
|
41 |
+
Contains information about a deployed Inference Endpoint.
|
42 |
+
|
43 |
+
Args:
|
44 |
+
name (`str`):
|
45 |
+
The unique name of the Inference Endpoint.
|
46 |
+
namespace (`str`):
|
47 |
+
The namespace where the Inference Endpoint is located.
|
48 |
+
repository (`str`):
|
49 |
+
The name of the model repository deployed on this Inference Endpoint.
|
50 |
+
status ([`InferenceEndpointStatus`]):
|
51 |
+
The current status of the Inference Endpoint.
|
52 |
+
url (`str`, *optional*):
|
53 |
+
The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL.
|
54 |
+
framework (`str`):
|
55 |
+
The machine learning framework used for the model.
|
56 |
+
revision (`str`):
|
57 |
+
The specific model revision deployed on the Inference Endpoint.
|
58 |
+
task (`str`):
|
59 |
+
The task associated with the deployed model.
|
60 |
+
created_at (`datetime.datetime`):
|
61 |
+
The timestamp when the Inference Endpoint was created.
|
62 |
+
updated_at (`datetime.datetime`):
|
63 |
+
The timestamp of the last update of the Inference Endpoint.
|
64 |
+
type ([`InferenceEndpointType`]):
|
65 |
+
The type of the Inference Endpoint (public, protected, private).
|
66 |
+
raw (`Dict`):
|
67 |
+
The raw dictionary data returned from the API.
|
68 |
+
token (`str` or `bool`, *optional*):
|
69 |
+
Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the
|
70 |
+
locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server.
|
71 |
+
|
72 |
+
Example:
|
73 |
+
```python
|
74 |
+
>>> from huggingface_hub import get_inference_endpoint
|
75 |
+
>>> endpoint = get_inference_endpoint("my-text-to-image")
|
76 |
+
>>> endpoint
|
77 |
+
InferenceEndpoint(name='my-text-to-image', ...)
|
78 |
+
|
79 |
+
# Get status
|
80 |
+
>>> endpoint.status
|
81 |
+
'running'
|
82 |
+
>>> endpoint.url
|
83 |
+
'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
|
84 |
+
|
85 |
+
# Run inference
|
86 |
+
>>> endpoint.client.text_to_image(...)
|
87 |
+
|
88 |
+
# Pause endpoint to save $$$
|
89 |
+
>>> endpoint.pause()
|
90 |
+
|
91 |
+
# ...
|
92 |
+
# Resume and wait for deployment
|
93 |
+
>>> endpoint.resume()
|
94 |
+
>>> endpoint.wait()
|
95 |
+
>>> endpoint.client.text_to_image(...)
|
96 |
+
```
|
97 |
+
"""
|
98 |
+
|
99 |
+
# Field in __repr__
|
100 |
+
name: str = field(init=False)
|
101 |
+
namespace: str
|
102 |
+
repository: str = field(init=False)
|
103 |
+
status: InferenceEndpointStatus = field(init=False)
|
104 |
+
url: Optional[str] = field(init=False)
|
105 |
+
|
106 |
+
# Other fields
|
107 |
+
framework: str = field(repr=False, init=False)
|
108 |
+
revision: str = field(repr=False, init=False)
|
109 |
+
task: str = field(repr=False, init=False)
|
110 |
+
created_at: datetime = field(repr=False, init=False)
|
111 |
+
updated_at: datetime = field(repr=False, init=False)
|
112 |
+
type: InferenceEndpointType = field(repr=False, init=False)
|
113 |
+
|
114 |
+
# Raw dict from the API
|
115 |
+
raw: Dict = field(repr=False)
|
116 |
+
|
117 |
+
# Internal fields
|
118 |
+
_token: Union[str, bool, None] = field(repr=False, compare=False)
|
119 |
+
_api: "HfApi" = field(repr=False, compare=False)
|
120 |
+
|
121 |
+
@classmethod
|
122 |
+
def from_raw(
|
123 |
+
cls, raw: Dict, namespace: str, token: Union[str, bool, None] = None, api: Optional["HfApi"] = None
|
124 |
+
) -> "InferenceEndpoint":
|
125 |
+
"""Initialize object from raw dictionary."""
|
126 |
+
if api is None:
|
127 |
+
from .hf_api import HfApi
|
128 |
+
|
129 |
+
api = HfApi()
|
130 |
+
if token is None:
|
131 |
+
token = api.token
|
132 |
+
|
133 |
+
# All other fields are populated in __post_init__
|
134 |
+
return cls(raw=raw, namespace=namespace, _token=token, _api=api)
|
135 |
+
|
136 |
+
def __post_init__(self) -> None:
|
137 |
+
"""Populate fields from raw dictionary."""
|
138 |
+
self._populate_from_raw()
|
139 |
+
|
140 |
+
@property
|
141 |
+
def client(self) -> InferenceClient:
|
142 |
+
"""Returns a client to make predictions on this Inference Endpoint.
|
143 |
+
|
144 |
+
Returns:
|
145 |
+
[`InferenceClient`]: an inference client pointing to the deployed endpoint.
|
146 |
+
|
147 |
+
Raises:
|
148 |
+
[`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
|
149 |
+
"""
|
150 |
+
if self.url is None:
|
151 |
+
raise InferenceEndpointError(
|
152 |
+
"Cannot create a client for this Inference Endpoint as it is not yet deployed. "
|
153 |
+
"Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
|
154 |
+
)
|
155 |
+
return InferenceClient(model=self.url, token=self._token)
|
156 |
+
|
157 |
+
@property
|
158 |
+
def async_client(self) -> AsyncInferenceClient:
|
159 |
+
"""Returns a client to make predictions on this Inference Endpoint.
|
160 |
+
|
161 |
+
Returns:
|
162 |
+
[`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint.
|
163 |
+
|
164 |
+
Raises:
|
165 |
+
[`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
|
166 |
+
"""
|
167 |
+
if self.url is None:
|
168 |
+
raise InferenceEndpointError(
|
169 |
+
"Cannot create a client for this Inference Endpoint as it is not yet deployed. "
|
170 |
+
"Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
|
171 |
+
)
|
172 |
+
return AsyncInferenceClient(model=self.url, token=self._token)
|
173 |
+
|
174 |
+
def wait(self, timeout: Optional[int] = None, refresh_every: int = 5) -> "InferenceEndpoint":
|
175 |
+
"""Wait for the Inference Endpoint to be deployed.
|
176 |
+
|
177 |
+
Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout`
|
178 |
+
seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest
|
179 |
+
data.
|
180 |
+
|
181 |
+
Args:
|
182 |
+
timeout (`int`, *optional*):
|
183 |
+
The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait
|
184 |
+
indefinitely.
|
185 |
+
refresh_every (`int`, *optional*):
|
186 |
+
The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s.
|
187 |
+
|
188 |
+
Returns:
|
189 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
190 |
+
|
191 |
+
Raises:
|
192 |
+
[`InferenceEndpointError`]
|
193 |
+
If the Inference Endpoint ended up in a failed state.
|
194 |
+
[`InferenceEndpointTimeoutError`]
|
195 |
+
If the Inference Endpoint is not deployed after `timeout` seconds.
|
196 |
+
"""
|
197 |
+
if timeout is not None and timeout < 0:
|
198 |
+
raise ValueError("`timeout` cannot be negative.")
|
199 |
+
if refresh_every <= 0:
|
200 |
+
raise ValueError("`refresh_every` must be positive.")
|
201 |
+
|
202 |
+
start = time.time()
|
203 |
+
while True:
|
204 |
+
if self.url is not None:
|
205 |
+
# Means the URL is provisioned => check if the endpoint is reachable
|
206 |
+
response = get_session().get(self.url, headers=self._api._build_hf_headers(token=self._token))
|
207 |
+
if response.status_code == 200:
|
208 |
+
logger.info("Inference Endpoint is ready to be used.")
|
209 |
+
return self
|
210 |
+
if self.status == InferenceEndpointStatus.FAILED:
|
211 |
+
raise InferenceEndpointError(
|
212 |
+
f"Inference Endpoint {self.name} failed to deploy. Please check the logs for more information."
|
213 |
+
)
|
214 |
+
if timeout is not None:
|
215 |
+
if time.time() - start > timeout:
|
216 |
+
raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.")
|
217 |
+
logger.info(f"Inference Endpoint is not deployed yet ({self.status}). Waiting {refresh_every}s...")
|
218 |
+
time.sleep(refresh_every)
|
219 |
+
self.fetch()
|
220 |
+
|
221 |
+
def fetch(self) -> "InferenceEndpoint":
|
222 |
+
"""Fetch latest information about the Inference Endpoint.
|
223 |
+
|
224 |
+
Returns:
|
225 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
226 |
+
"""
|
227 |
+
obj = self._api.get_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
228 |
+
self.raw = obj.raw
|
229 |
+
self._populate_from_raw()
|
230 |
+
return self
|
231 |
+
|
232 |
+
def update(
|
233 |
+
self,
|
234 |
+
*,
|
235 |
+
# Compute update
|
236 |
+
accelerator: Optional[str] = None,
|
237 |
+
instance_size: Optional[str] = None,
|
238 |
+
instance_type: Optional[str] = None,
|
239 |
+
min_replica: Optional[int] = None,
|
240 |
+
max_replica: Optional[int] = None,
|
241 |
+
# Model update
|
242 |
+
repository: Optional[str] = None,
|
243 |
+
framework: Optional[str] = None,
|
244 |
+
revision: Optional[str] = None,
|
245 |
+
task: Optional[str] = None,
|
246 |
+
) -> "InferenceEndpoint":
|
247 |
+
"""Update the Inference Endpoint.
|
248 |
+
|
249 |
+
This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
|
250 |
+
optional but at least one must be provided.
|
251 |
+
|
252 |
+
This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the
|
253 |
+
latest data from the server.
|
254 |
+
|
255 |
+
Args:
|
256 |
+
accelerator (`str`, *optional*):
|
257 |
+
The hardware accelerator to be used for inference (e.g. `"cpu"`).
|
258 |
+
instance_size (`str`, *optional*):
|
259 |
+
The size or type of the instance to be used for hosting the model (e.g. `"large"`).
|
260 |
+
instance_type (`str`, *optional*):
|
261 |
+
The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`).
|
262 |
+
min_replica (`int`, *optional*):
|
263 |
+
The minimum number of replicas (instances) to keep running for the Inference Endpoint.
|
264 |
+
max_replica (`int`, *optional*):
|
265 |
+
The maximum number of replicas (instances) to scale to for the Inference Endpoint.
|
266 |
+
|
267 |
+
repository (`str`, *optional*):
|
268 |
+
The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
|
269 |
+
framework (`str`, *optional*):
|
270 |
+
The machine learning framework used for the model (e.g. `"custom"`).
|
271 |
+
revision (`str`, *optional*):
|
272 |
+
The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
|
273 |
+
task (`str`, *optional*):
|
274 |
+
The task on which to deploy the model (e.g. `"text-classification"`).
|
275 |
+
|
276 |
+
Returns:
|
277 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
278 |
+
"""
|
279 |
+
# Make API call
|
280 |
+
obj = self._api.update_inference_endpoint(
|
281 |
+
name=self.name,
|
282 |
+
namespace=self.namespace,
|
283 |
+
accelerator=accelerator,
|
284 |
+
instance_size=instance_size,
|
285 |
+
instance_type=instance_type,
|
286 |
+
min_replica=min_replica,
|
287 |
+
max_replica=max_replica,
|
288 |
+
repository=repository,
|
289 |
+
framework=framework,
|
290 |
+
revision=revision,
|
291 |
+
task=task,
|
292 |
+
token=self._token, # type: ignore [arg-type]
|
293 |
+
)
|
294 |
+
|
295 |
+
# Mutate current object
|
296 |
+
self.raw = obj.raw
|
297 |
+
self._populate_from_raw()
|
298 |
+
return self
|
299 |
+
|
300 |
+
def pause(self) -> "InferenceEndpoint":
|
301 |
+
"""Pause the Inference Endpoint.
|
302 |
+
|
303 |
+
A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`].
|
304 |
+
This is different than scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which
|
305 |
+
would be automatically restarted when a request is made to it.
|
306 |
+
|
307 |
+
This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the
|
308 |
+
latest data from the server.
|
309 |
+
|
310 |
+
Returns:
|
311 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
312 |
+
"""
|
313 |
+
obj = self._api.pause_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
314 |
+
self.raw = obj.raw
|
315 |
+
self._populate_from_raw()
|
316 |
+
return self
|
317 |
+
|
318 |
+
def resume(self) -> "InferenceEndpoint":
|
319 |
+
"""Resume the Inference Endpoint.
|
320 |
+
|
321 |
+
This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the
|
322 |
+
latest data from the server.
|
323 |
+
|
324 |
+
Returns:
|
325 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
326 |
+
"""
|
327 |
+
obj = self._api.resume_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
328 |
+
self.raw = obj.raw
|
329 |
+
self._populate_from_raw()
|
330 |
+
return self
|
331 |
+
|
332 |
+
def scale_to_zero(self) -> "InferenceEndpoint":
|
333 |
+
"""Scale Inference Endpoint to zero.
|
334 |
+
|
335 |
+
An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
|
336 |
+
cold start delay. This is different than pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which
|
337 |
+
would require a manual resume with [`InferenceEndpoint.resume`].
|
338 |
+
|
339 |
+
This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the
|
340 |
+
latest data from the server.
|
341 |
+
|
342 |
+
Returns:
|
343 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
344 |
+
"""
|
345 |
+
obj = self._api.scale_to_zero_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
346 |
+
self.raw = obj.raw
|
347 |
+
self._populate_from_raw()
|
348 |
+
return self
|
349 |
+
|
350 |
+
def delete(self) -> None:
|
351 |
+
"""Delete the Inference Endpoint.
|
352 |
+
|
353 |
+
This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
|
354 |
+
to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`].
|
355 |
+
|
356 |
+
This is an alias for [`HfApi.delete_inference_endpoint`].
|
357 |
+
"""
|
358 |
+
self._api.delete_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
359 |
+
|
360 |
+
def _populate_from_raw(self) -> None:
|
361 |
+
"""Populate fields from raw dictionary.
|
362 |
+
|
363 |
+
Called in __post_init__ + each time the Inference Endpoint is updated.
|
364 |
+
"""
|
365 |
+
# Repr fields
|
366 |
+
self.name = self.raw["name"]
|
367 |
+
self.repository = self.raw["model"]["repository"]
|
368 |
+
self.status = self.raw["status"]["state"]
|
369 |
+
self.url = self.raw["status"].get("url")
|
370 |
+
|
371 |
+
# Other fields
|
372 |
+
self.framework = self.raw["model"]["framework"]
|
373 |
+
self.revision = self.raw["model"]["revision"]
|
374 |
+
self.task = self.raw["model"]["task"]
|
375 |
+
self.created_at = parse_datetime(self.raw["status"]["createdAt"])
|
376 |
+
self.updated_at = parse_datetime(self.raw["status"]["updatedAt"])
|
377 |
+
self.type = self.raw["type"]
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/_local_folder.py
ADDED
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024-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 |
+
"""Contains utilities to handle the `../.huggingface` folder in local directories.
|
16 |
+
|
17 |
+
First discussed in https://github.com/huggingface/huggingface_hub/issues/1738 to store
|
18 |
+
download metadata when downloading files from the hub to a local directory (without
|
19 |
+
using the cache).
|
20 |
+
|
21 |
+
./.huggingface folder structure:
|
22 |
+
[4.0K] data
|
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 |
+
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 logging
|
52 |
+
import os
|
53 |
+
import time
|
54 |
+
from dataclasses import dataclass
|
55 |
+
from functools import lru_cache
|
56 |
+
from pathlib import Path
|
57 |
+
from typing import Optional
|
58 |
+
|
59 |
+
from .utils import WeakFileLock
|
60 |
+
|
61 |
+
|
62 |
+
logger = logging.getLogger(__name__)
|
63 |
+
|
64 |
+
|
65 |
+
@dataclass
|
66 |
+
class LocalDownloadFilePaths:
|
67 |
+
"""
|
68 |
+
Paths to the files related to a download process in a local dir.
|
69 |
+
|
70 |
+
Returned by `get_local_download_paths`.
|
71 |
+
|
72 |
+
Attributes:
|
73 |
+
file_path (`Path`):
|
74 |
+
Path where the file will be saved.
|
75 |
+
lock_path (`Path`):
|
76 |
+
Path to the lock file used to ensure atomicity when reading/writing metadata.
|
77 |
+
metadata_path (`Path`):
|
78 |
+
Path to the metadata file.
|
79 |
+
"""
|
80 |
+
|
81 |
+
file_path: Path
|
82 |
+
lock_path: Path
|
83 |
+
metadata_path: Path
|
84 |
+
|
85 |
+
def incomplete_path(self, etag: str) -> Path:
|
86 |
+
"""Return the path where a file will be temporarily downloaded before being moved to `file_path`."""
|
87 |
+
return self.metadata_path.with_suffix(f".{etag}.incomplete")
|
88 |
+
|
89 |
+
|
90 |
+
@dataclass
|
91 |
+
class LocalDownloadFileMetadata:
|
92 |
+
"""
|
93 |
+
Metadata about a file in the local directory related to a download process.
|
94 |
+
|
95 |
+
Attributes:
|
96 |
+
filename (`str`):
|
97 |
+
Path of the file in the repo.
|
98 |
+
commit_hash (`str`):
|
99 |
+
Commit hash of the file in the repo.
|
100 |
+
etag (`str`):
|
101 |
+
ETag of the file in the repo. Used to check if the file has changed.
|
102 |
+
For LFS files, this is the sha256 of the file. For regular files, it corresponds to the git hash.
|
103 |
+
timestamp (`int`):
|
104 |
+
Unix timestamp of when the metadata was saved i.e. when the metadata was accurate.
|
105 |
+
"""
|
106 |
+
|
107 |
+
filename: str
|
108 |
+
commit_hash: str
|
109 |
+
etag: str
|
110 |
+
timestamp: float
|
111 |
+
|
112 |
+
|
113 |
+
@lru_cache(maxsize=128) # ensure singleton
|
114 |
+
def get_local_download_paths(local_dir: Path, filename: str) -> LocalDownloadFilePaths:
|
115 |
+
"""Compute paths to the files related to a download process.
|
116 |
+
|
117 |
+
Folders containing the paths are all guaranteed to exist.
|
118 |
+
|
119 |
+
Args:
|
120 |
+
local_dir (`Path`):
|
121 |
+
Path to the local directory in which files are downloaded.
|
122 |
+
filename (`str`):
|
123 |
+
Path of the file in the repo.
|
124 |
+
|
125 |
+
Return:
|
126 |
+
[`LocalDownloadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path, incomplete_path).
|
127 |
+
"""
|
128 |
+
# filename is the path in the Hub repository (separated by '/')
|
129 |
+
# make sure to have a cross platform transcription
|
130 |
+
sanitized_filename = os.path.join(*filename.split("/"))
|
131 |
+
if os.name == "nt":
|
132 |
+
if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
|
133 |
+
raise ValueError(
|
134 |
+
f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
|
135 |
+
" owner to rename this file."
|
136 |
+
)
|
137 |
+
file_path = local_dir / sanitized_filename
|
138 |
+
metadata_path = _huggingface_dir(local_dir) / "download" / f"{sanitized_filename}.metadata"
|
139 |
+
lock_path = metadata_path.with_suffix(".lock")
|
140 |
+
|
141 |
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
142 |
+
metadata_path.parent.mkdir(parents=True, exist_ok=True)
|
143 |
+
return LocalDownloadFilePaths(file_path=file_path, lock_path=lock_path, metadata_path=metadata_path)
|
144 |
+
|
145 |
+
|
146 |
+
def read_download_metadata(local_dir: Path, filename: str) -> Optional[LocalDownloadFileMetadata]:
|
147 |
+
"""Read metadata about a file in the local directory related to a download process.
|
148 |
+
|
149 |
+
Args:
|
150 |
+
local_dir (`Path`):
|
151 |
+
Path to the local directory in which files are downloaded.
|
152 |
+
filename (`str`):
|
153 |
+
Path of the file in the repo.
|
154 |
+
|
155 |
+
Return:
|
156 |
+
`[LocalDownloadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
|
157 |
+
"""
|
158 |
+
paths = get_local_download_paths(local_dir, filename)
|
159 |
+
# file_path = local_file_path(local_dir, filename)
|
160 |
+
# lock_path, metadata_path = _download_metadata_file_path(local_dir, filename)
|
161 |
+
with WeakFileLock(paths.lock_path):
|
162 |
+
if paths.metadata_path.exists():
|
163 |
+
try:
|
164 |
+
with paths.metadata_path.open() as f:
|
165 |
+
commit_hash = f.readline().strip()
|
166 |
+
etag = f.readline().strip()
|
167 |
+
timestamp = float(f.readline().strip())
|
168 |
+
metadata = LocalDownloadFileMetadata(
|
169 |
+
filename=filename,
|
170 |
+
commit_hash=commit_hash,
|
171 |
+
etag=etag,
|
172 |
+
timestamp=timestamp,
|
173 |
+
)
|
174 |
+
except Exception as e:
|
175 |
+
# remove the metadata file if it is corrupted / not the right format
|
176 |
+
logger.warning(
|
177 |
+
f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
|
178 |
+
)
|
179 |
+
try:
|
180 |
+
paths.metadata_path.unlink()
|
181 |
+
except Exception as e:
|
182 |
+
logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
|
183 |
+
|
184 |
+
try:
|
185 |
+
# check if the file exists and hasn't been modified since the metadata was saved
|
186 |
+
stat = paths.file_path.stat()
|
187 |
+
if (
|
188 |
+
stat.st_mtime - 1 <= metadata.timestamp
|
189 |
+
): # allow 1s difference as stat.st_mtime might not be precise
|
190 |
+
return metadata
|
191 |
+
logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
|
192 |
+
except FileNotFoundError:
|
193 |
+
# file does not exist => metadata is outdated
|
194 |
+
return None
|
195 |
+
return None
|
196 |
+
|
197 |
+
|
198 |
+
def write_download_metadata(local_dir: Path, filename: str, commit_hash: str, etag: str) -> None:
|
199 |
+
"""Write metadata about a file in the local directory related to a download process.
|
200 |
+
|
201 |
+
Args:
|
202 |
+
local_dir (`Path`):
|
203 |
+
Path to the local directory in which files are downloaded.
|
204 |
+
"""
|
205 |
+
paths = get_local_download_paths(local_dir, filename)
|
206 |
+
with WeakFileLock(paths.lock_path):
|
207 |
+
with paths.metadata_path.open("w") as f:
|
208 |
+
f.write(f"{commit_hash}\n{etag}\n{time.time()}\n")
|
209 |
+
|
210 |
+
|
211 |
+
@lru_cache()
|
212 |
+
def _huggingface_dir(local_dir: Path) -> Path:
|
213 |
+
"""Return the path to the `.huggingface` directory in a local directory."""
|
214 |
+
# Wrap in lru_cache to avoid overwriting the .gitignore file if called multiple times
|
215 |
+
path = local_dir / ".huggingface"
|
216 |
+
path.mkdir(exist_ok=True, parents=True)
|
217 |
+
|
218 |
+
# Create a .gitignore file in the .huggingface directory if it doesn't exist
|
219 |
+
# Should be thread-safe enough like this.
|
220 |
+
gitignore = path / ".gitignore"
|
221 |
+
gitignore_lock = path / ".gitignore.lock"
|
222 |
+
if not gitignore.exists():
|
223 |
+
with WeakFileLock(gitignore_lock):
|
224 |
+
gitignore.write_text("*")
|
225 |
+
try:
|
226 |
+
gitignore_lock.unlink()
|
227 |
+
except OSError: # FileNotFoundError, PermissionError, etc.
|
228 |
+
pass
|
229 |
+
return path
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/_login.py
ADDED
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 login to the Hub."""
|
15 |
+
|
16 |
+
import os
|
17 |
+
import subprocess
|
18 |
+
from functools import partial
|
19 |
+
from getpass import getpass
|
20 |
+
from pathlib import Path
|
21 |
+
from typing import Optional
|
22 |
+
|
23 |
+
from . import constants
|
24 |
+
from .commands._cli_utils import ANSI
|
25 |
+
from .utils import (
|
26 |
+
capture_output,
|
27 |
+
get_token,
|
28 |
+
is_google_colab,
|
29 |
+
is_notebook,
|
30 |
+
list_credential_helpers,
|
31 |
+
logging,
|
32 |
+
run_subprocess,
|
33 |
+
set_git_credential,
|
34 |
+
unset_git_credential,
|
35 |
+
)
|
36 |
+
from .utils._token import _get_token_from_environment, _get_token_from_google_colab
|
37 |
+
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
_HF_LOGO_ASCII = """
|
42 |
+
_| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|
|
43 |
+
_| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
|
44 |
+
_|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|
|
45 |
+
_| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
|
46 |
+
_| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|
|
47 |
+
"""
|
48 |
+
|
49 |
+
|
50 |
+
def login(
|
51 |
+
token: Optional[str] = None,
|
52 |
+
add_to_git_credential: bool = False,
|
53 |
+
new_session: bool = True,
|
54 |
+
write_permission: bool = False,
|
55 |
+
) -> None:
|
56 |
+
"""Login the machine to access the Hub.
|
57 |
+
|
58 |
+
The `token` is persisted in cache and set as a git credential. Once done, the machine
|
59 |
+
is logged in and the access token will be available across all `huggingface_hub`
|
60 |
+
components. If `token` is not provided, it will be prompted to the user either with
|
61 |
+
a widget (in a notebook) or via the terminal.
|
62 |
+
|
63 |
+
To login from outside of a script, one can also use `huggingface-cli login` which is
|
64 |
+
a cli command that wraps [`login`].
|
65 |
+
|
66 |
+
<Tip>
|
67 |
+
|
68 |
+
[`login`] is a drop-in replacement method for [`notebook_login`] as it wraps and
|
69 |
+
extends its capabilities.
|
70 |
+
|
71 |
+
</Tip>
|
72 |
+
|
73 |
+
<Tip>
|
74 |
+
|
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 |
+
</Tip>
|
81 |
+
|
82 |
+
Args:
|
83 |
+
token (`str`, *optional*):
|
84 |
+
User access token to generate from https://huggingface.co/settings/token.
|
85 |
+
add_to_git_credential (`bool`, defaults to `False`):
|
86 |
+
If `True`, token will be set as git credential. If no git credential helper
|
87 |
+
is configured, a warning will be displayed to the user. If `token` is `None`,
|
88 |
+
the value of `add_to_git_credential` is ignored and will be prompted again
|
89 |
+
to the end user.
|
90 |
+
new_session (`bool`, defaults to `True`):
|
91 |
+
If `True`, will request a token even if one is already saved on the machine.
|
92 |
+
write_permission (`bool`, defaults to `False`):
|
93 |
+
If `True`, requires a token with write permission.
|
94 |
+
Raises:
|
95 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
96 |
+
If an organization token is passed. Only personal account tokens are valid
|
97 |
+
to login.
|
98 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
99 |
+
If token is invalid.
|
100 |
+
[`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
101 |
+
If running in a notebook but `ipywidgets` is not installed.
|
102 |
+
"""
|
103 |
+
if token is not None:
|
104 |
+
if not add_to_git_credential:
|
105 |
+
print(
|
106 |
+
"The token has not been saved to the git credentials helper. Pass "
|
107 |
+
"`add_to_git_credential=True` in this function directly or "
|
108 |
+
"`--add-to-git-credential` if using via `huggingface-cli` if "
|
109 |
+
"you want to set the git credential as well."
|
110 |
+
)
|
111 |
+
_login(token, add_to_git_credential=add_to_git_credential, write_permission=write_permission)
|
112 |
+
elif is_notebook():
|
113 |
+
notebook_login(new_session=new_session, write_permission=write_permission)
|
114 |
+
else:
|
115 |
+
interpreter_login(new_session=new_session, write_permission=write_permission)
|
116 |
+
|
117 |
+
|
118 |
+
def logout() -> None:
|
119 |
+
"""Logout the machine from the Hub.
|
120 |
+
|
121 |
+
Token is deleted from the machine and removed from git credential.
|
122 |
+
"""
|
123 |
+
if get_token() is None:
|
124 |
+
print("Not logged in!")
|
125 |
+
return
|
126 |
+
|
127 |
+
# Delete token from git credentials
|
128 |
+
unset_git_credential()
|
129 |
+
|
130 |
+
# Delete token file
|
131 |
+
try:
|
132 |
+
Path(constants.HF_TOKEN_PATH).unlink()
|
133 |
+
except FileNotFoundError:
|
134 |
+
pass
|
135 |
+
|
136 |
+
# Check if still logged in
|
137 |
+
if _get_token_from_google_colab() is not None:
|
138 |
+
raise EnvironmentError(
|
139 |
+
"You are automatically logged in using a Google Colab secret.\n"
|
140 |
+
"To log out, you must unset the `HF_TOKEN` secret in your Colab settings."
|
141 |
+
)
|
142 |
+
if _get_token_from_environment() is not None:
|
143 |
+
raise EnvironmentError(
|
144 |
+
"Token has been deleted from your machine but you are still logged in.\n"
|
145 |
+
"To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables."
|
146 |
+
)
|
147 |
+
|
148 |
+
print("Successfully logged out.")
|
149 |
+
|
150 |
+
|
151 |
+
###
|
152 |
+
# Interpreter-based login (text)
|
153 |
+
###
|
154 |
+
|
155 |
+
|
156 |
+
def interpreter_login(new_session: bool = True, write_permission: bool = False) -> None:
|
157 |
+
"""
|
158 |
+
Displays a prompt to login to the HF website and store the token.
|
159 |
+
|
160 |
+
This is equivalent to [`login`] without passing a token when not run in a notebook.
|
161 |
+
[`interpreter_login`] is useful if you want to force the use of the terminal prompt
|
162 |
+
instead of a notebook widget.
|
163 |
+
|
164 |
+
For more details, see [`login`].
|
165 |
+
|
166 |
+
Args:
|
167 |
+
new_session (`bool`, defaults to `True`):
|
168 |
+
If `True`, will request a token even if one is already saved on the machine.
|
169 |
+
write_permission (`bool`, defaults to `False`):
|
170 |
+
If `True`, requires a token with write permission.
|
171 |
+
|
172 |
+
"""
|
173 |
+
if not new_session and _current_token_okay(write_permission=write_permission):
|
174 |
+
print("User is already logged in.")
|
175 |
+
return
|
176 |
+
|
177 |
+
from .commands.delete_cache import _ask_for_confirmation_no_tui
|
178 |
+
|
179 |
+
print(_HF_LOGO_ASCII)
|
180 |
+
if get_token() is not None:
|
181 |
+
print(
|
182 |
+
" A token is already saved on your machine. Run `huggingface-cli"
|
183 |
+
" whoami` to get more information or `huggingface-cli logout` if you want"
|
184 |
+
" to log out."
|
185 |
+
)
|
186 |
+
print(" Setting a new token will erase the existing one.")
|
187 |
+
|
188 |
+
print(" To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .")
|
189 |
+
if os.name == "nt":
|
190 |
+
print("Token can be pasted using 'Right-Click'.")
|
191 |
+
token = getpass("Enter your token (input will not be visible): ")
|
192 |
+
add_to_git_credential = _ask_for_confirmation_no_tui("Add token as git credential?")
|
193 |
+
|
194 |
+
_login(token=token, add_to_git_credential=add_to_git_credential, write_permission=write_permission)
|
195 |
+
|
196 |
+
|
197 |
+
###
|
198 |
+
# Notebook-based login (widget)
|
199 |
+
###
|
200 |
+
|
201 |
+
NOTEBOOK_LOGIN_PASSWORD_HTML = """<center> <img
|
202 |
+
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
|
203 |
+
alt='Hugging Face'> <br> Immediately click login after typing your password or
|
204 |
+
it might be stored in plain text in this notebook file. </center>"""
|
205 |
+
|
206 |
+
|
207 |
+
NOTEBOOK_LOGIN_TOKEN_HTML_START = """<center> <img
|
208 |
+
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
|
209 |
+
alt='Hugging Face'> <br> Copy a token from <a
|
210 |
+
href="https://huggingface.co/settings/tokens" target="_blank">your Hugging Face
|
211 |
+
tokens page</a> and paste it below. <br> Immediately click login after copying
|
212 |
+
your token or it might be stored in plain text in this notebook file. </center>"""
|
213 |
+
|
214 |
+
|
215 |
+
NOTEBOOK_LOGIN_TOKEN_HTML_END = """
|
216 |
+
<b>Pro Tip:</b> If you don't already have one, you can create a dedicated
|
217 |
+
'notebooks' token with 'write' access, that you can then easily reuse for all
|
218 |
+
notebooks. </center>"""
|
219 |
+
|
220 |
+
|
221 |
+
def notebook_login(new_session: bool = True, write_permission: bool = False) -> None:
|
222 |
+
"""
|
223 |
+
Displays a widget to login to the HF website and store the token.
|
224 |
+
|
225 |
+
This is equivalent to [`login`] without passing a token when run in a notebook.
|
226 |
+
[`notebook_login`] is useful if you want to force the use of the notebook widget
|
227 |
+
instead of a prompt in the terminal.
|
228 |
+
|
229 |
+
For more details, see [`login`].
|
230 |
+
|
231 |
+
Args:
|
232 |
+
new_session (`bool`, defaults to `True`):
|
233 |
+
If `True`, will request a token even if one is already saved on the machine.
|
234 |
+
write_permission (`bool`, defaults to `False`):
|
235 |
+
If `True`, requires a token with write permission.
|
236 |
+
"""
|
237 |
+
try:
|
238 |
+
import ipywidgets.widgets as widgets # type: ignore
|
239 |
+
from IPython.display import display # type: ignore
|
240 |
+
except ImportError:
|
241 |
+
raise ImportError(
|
242 |
+
"The `notebook_login` function can only be used in a notebook (Jupyter or"
|
243 |
+
" Colab) and you need the `ipywidgets` module: `pip install ipywidgets`."
|
244 |
+
)
|
245 |
+
if not new_session and _current_token_okay(write_permission=write_permission):
|
246 |
+
print("User is already logged in.")
|
247 |
+
return
|
248 |
+
|
249 |
+
box_layout = widgets.Layout(display="flex", flex_flow="column", align_items="center", width="50%")
|
250 |
+
|
251 |
+
token_widget = widgets.Password(description="Token:")
|
252 |
+
git_checkbox_widget = widgets.Checkbox(value=True, description="Add token as git credential?")
|
253 |
+
token_finish_button = widgets.Button(description="Login")
|
254 |
+
|
255 |
+
login_token_widget = widgets.VBox(
|
256 |
+
[
|
257 |
+
widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_START),
|
258 |
+
token_widget,
|
259 |
+
git_checkbox_widget,
|
260 |
+
token_finish_button,
|
261 |
+
widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_END),
|
262 |
+
],
|
263 |
+
layout=box_layout,
|
264 |
+
)
|
265 |
+
display(login_token_widget)
|
266 |
+
|
267 |
+
# On click events
|
268 |
+
def login_token_event(t, write_permission: bool = False):
|
269 |
+
"""
|
270 |
+
Event handler for the login button.
|
271 |
+
|
272 |
+
Args:
|
273 |
+
write_permission (`bool`, defaults to `False`):
|
274 |
+
If `True`, requires a token with write permission.
|
275 |
+
"""
|
276 |
+
token = token_widget.value
|
277 |
+
add_to_git_credential = git_checkbox_widget.value
|
278 |
+
# Erase token and clear value to make sure it's not saved in the notebook.
|
279 |
+
token_widget.value = ""
|
280 |
+
# Hide inputs
|
281 |
+
login_token_widget.children = [widgets.Label("Connecting...")]
|
282 |
+
try:
|
283 |
+
with capture_output() as captured:
|
284 |
+
_login(token, add_to_git_credential=add_to_git_credential, write_permission=write_permission)
|
285 |
+
message = captured.getvalue()
|
286 |
+
except Exception as error:
|
287 |
+
message = str(error)
|
288 |
+
# Print result (success message or error)
|
289 |
+
login_token_widget.children = [widgets.Label(line) for line in message.split("\n") if line.strip()]
|
290 |
+
|
291 |
+
token_finish_button.on_click(partial(login_token_event, write_permission=write_permission))
|
292 |
+
|
293 |
+
|
294 |
+
###
|
295 |
+
# Login private helpers
|
296 |
+
###
|
297 |
+
|
298 |
+
|
299 |
+
def _login(token: str, add_to_git_credential: bool, write_permission: bool = False) -> None:
|
300 |
+
from .hf_api import get_token_permission # avoid circular import
|
301 |
+
|
302 |
+
if token.startswith("api_org"):
|
303 |
+
raise ValueError("You must use your personal account token, not an organization token.")
|
304 |
+
|
305 |
+
permission = get_token_permission(token)
|
306 |
+
if permission is None:
|
307 |
+
raise ValueError("Invalid token passed!")
|
308 |
+
elif write_permission and permission != "write":
|
309 |
+
raise ValueError(
|
310 |
+
"Token is valid but is 'read-only' and a 'write' token is required.\nPlease provide a new token with"
|
311 |
+
" correct permission."
|
312 |
+
)
|
313 |
+
print(f"Token is valid (permission: {permission}).")
|
314 |
+
|
315 |
+
if add_to_git_credential:
|
316 |
+
if _is_git_credential_helper_configured():
|
317 |
+
set_git_credential(token)
|
318 |
+
print(
|
319 |
+
"Your token has been saved in your configured git credential helpers"
|
320 |
+
+ f" ({','.join(list_credential_helpers())})."
|
321 |
+
)
|
322 |
+
else:
|
323 |
+
print("Token has not been saved to git credential helper.")
|
324 |
+
|
325 |
+
# Save token
|
326 |
+
path = Path(constants.HF_TOKEN_PATH)
|
327 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
328 |
+
path.write_text(token)
|
329 |
+
print(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
|
330 |
+
print("Login successful")
|
331 |
+
|
332 |
+
|
333 |
+
def _current_token_okay(write_permission: bool = False):
|
334 |
+
"""Check if the current token is valid.
|
335 |
+
|
336 |
+
Args:
|
337 |
+
write_permission (`bool`, defaults to `False`):
|
338 |
+
If `True`, requires a token with write permission.
|
339 |
+
|
340 |
+
Returns:
|
341 |
+
`bool`: `True` if the current token is valid, `False` otherwise.
|
342 |
+
"""
|
343 |
+
from .hf_api import get_token_permission # avoid circular import
|
344 |
+
|
345 |
+
permission = get_token_permission()
|
346 |
+
if permission is None or (write_permission and permission != "write"):
|
347 |
+
return False
|
348 |
+
return True
|
349 |
+
|
350 |
+
|
351 |
+
def _is_git_credential_helper_configured() -> bool:
|
352 |
+
"""Check if a git credential helper is configured.
|
353 |
+
|
354 |
+
Warns user if not the case (except for Google Colab where "store" is set by default
|
355 |
+
by `huggingface_hub`).
|
356 |
+
"""
|
357 |
+
helpers = list_credential_helpers()
|
358 |
+
if len(helpers) > 0:
|
359 |
+
return True # Do not warn: at least 1 helper is set
|
360 |
+
|
361 |
+
# Only in Google Colab to avoid the warning message
|
362 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1043#issuecomment-1247010710
|
363 |
+
if is_google_colab():
|
364 |
+
_set_store_as_git_credential_helper_globally()
|
365 |
+
return True # Do not warn: "store" is used by default in Google Colab
|
366 |
+
|
367 |
+
# Otherwise, warn user
|
368 |
+
print(
|
369 |
+
ANSI.red(
|
370 |
+
"Cannot authenticate through git-credential as no helper is defined on your"
|
371 |
+
" machine.\nYou might have to re-authenticate when pushing to the Hugging"
|
372 |
+
" Face Hub.\nRun the following command in your terminal in case you want to"
|
373 |
+
" set the 'store' credential helper as default.\n\ngit config --global"
|
374 |
+
" credential.helper store\n\nRead"
|
375 |
+
" https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more"
|
376 |
+
" details."
|
377 |
+
)
|
378 |
+
)
|
379 |
+
return False
|
380 |
+
|
381 |
+
|
382 |
+
def _set_store_as_git_credential_helper_globally() -> None:
|
383 |
+
"""Set globally the credential.helper to `store`.
|
384 |
+
|
385 |
+
To be used only in Google Colab as we assume the user doesn't care about the git
|
386 |
+
credential config. It is the only particular case where we don't want to display the
|
387 |
+
warning message in [`notebook_login()`].
|
388 |
+
|
389 |
+
Related:
|
390 |
+
- https://github.com/huggingface/huggingface_hub/issues/1043
|
391 |
+
- https://github.com/huggingface/huggingface_hub/issues/1051
|
392 |
+
- https://git-scm.com/docs/git-credential-store
|
393 |
+
"""
|
394 |
+
try:
|
395 |
+
run_subprocess("git config --global credential.helper store")
|
396 |
+
except subprocess.CalledProcessError as exc:
|
397 |
+
raise EnvironmentError(exc.stderr)
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py
ADDED
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023-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 |
+
"""Contains utilities to multi-commits (i.e. push changes iteratively on a PR)."""
|
16 |
+
|
17 |
+
import re
|
18 |
+
from dataclasses import dataclass, field
|
19 |
+
from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Union
|
20 |
+
|
21 |
+
from ._commit_api import CommitOperationAdd, CommitOperationDelete
|
22 |
+
from .community import DiscussionWithDetails
|
23 |
+
from .utils import experimental
|
24 |
+
from .utils._cache_manager import _format_size
|
25 |
+
from .utils.insecure_hashlib import sha256
|
26 |
+
|
27 |
+
|
28 |
+
if TYPE_CHECKING:
|
29 |
+
from .hf_api import HfApi
|
30 |
+
|
31 |
+
|
32 |
+
class MultiCommitException(Exception):
|
33 |
+
"""Base exception for any exception happening while doing a multi-commit."""
|
34 |
+
|
35 |
+
|
36 |
+
MULTI_COMMIT_PR_DESCRIPTION_TEMPLATE = """
|
37 |
+
## {commit_message}
|
38 |
+
|
39 |
+
{commit_description}
|
40 |
+
|
41 |
+
**Multi commit ID:** {multi_commit_id}
|
42 |
+
|
43 |
+
Scheduled commits:
|
44 |
+
|
45 |
+
{multi_commit_strategy}
|
46 |
+
|
47 |
+
_This is a PR opened using the `huggingface_hub` library in the context of a multi-commit. PR can be commented as a usual PR. However, please be aware that manually updating the PR description, changing the PR status, or pushing new commits, is not recommended as it might corrupt the commit process. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
|
48 |
+
"""
|
49 |
+
|
50 |
+
MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATE = """
|
51 |
+
Multi-commit is now completed! You can ping the repo owner to review the changes. This PR can now be commented or modified without risking to corrupt it.
|
52 |
+
|
53 |
+
_This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
|
54 |
+
"""
|
55 |
+
|
56 |
+
MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE = """
|
57 |
+
`create_pr=False` has been passed so PR is automatically merged.
|
58 |
+
|
59 |
+
_This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
|
60 |
+
"""
|
61 |
+
|
62 |
+
MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE = """
|
63 |
+
Cannot merge Pull Requests as no changes are associated. This PR will be closed automatically.
|
64 |
+
|
65 |
+
_This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
|
66 |
+
"""
|
67 |
+
|
68 |
+
MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE = """
|
69 |
+
An error occurred while trying to merge the Pull Request: `{error_message}`.
|
70 |
+
|
71 |
+
_This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
|
72 |
+
"""
|
73 |
+
|
74 |
+
|
75 |
+
STEP_ID_REGEX = re.compile(r"- \[(?P<completed>[ |x])\].*(?P<step_id>[a-fA-F0-9]{64})", flags=re.MULTILINE)
|
76 |
+
|
77 |
+
|
78 |
+
@experimental
|
79 |
+
def plan_multi_commits(
|
80 |
+
operations: Iterable[Union[CommitOperationAdd, CommitOperationDelete]],
|
81 |
+
max_operations_per_commit: int = 50,
|
82 |
+
max_upload_size_per_commit: int = 2 * 1024 * 1024 * 1024,
|
83 |
+
) -> Tuple[List[List[CommitOperationAdd]], List[List[CommitOperationDelete]]]:
|
84 |
+
"""Split a list of operations in a list of commits to perform.
|
85 |
+
|
86 |
+
Implementation follows a sub-optimal (yet simple) algorithm:
|
87 |
+
1. Delete operations are grouped together by commits of maximum `max_operations_per_commits` operations.
|
88 |
+
2. All additions exceeding `max_upload_size_per_commit` are committed 1 by 1.
|
89 |
+
3. All remaining additions are grouped together and split each time the `max_operations_per_commit` or the
|
90 |
+
`max_upload_size_per_commit` limit is reached.
|
91 |
+
|
92 |
+
We do not try to optimize the splitting to get the lowest number of commits as this is a NP-hard problem (see
|
93 |
+
[bin packing problem](https://en.wikipedia.org/wiki/Bin_packing_problem)). For our use case, it is not problematic
|
94 |
+
to use a sub-optimal solution so we favored an easy-to-explain implementation.
|
95 |
+
|
96 |
+
Args:
|
97 |
+
operations (`List` of [`~hf_api.CommitOperation`]):
|
98 |
+
The list of operations to split into commits.
|
99 |
+
max_operations_per_commit (`int`):
|
100 |
+
Maximum number of operations in a single commit. Defaults to 50.
|
101 |
+
max_upload_size_per_commit (`int`):
|
102 |
+
Maximum size to upload (in bytes) in a single commit. Defaults to 2GB. Files bigger than this limit are
|
103 |
+
uploaded, 1 per commit.
|
104 |
+
|
105 |
+
Returns:
|
106 |
+
`Tuple[List[List[CommitOperationAdd]], List[List[CommitOperationDelete]]]`: a tuple. First item is a list of
|
107 |
+
lists of [`CommitOperationAdd`] representing the addition commits to push. The second item is a list of lists
|
108 |
+
of [`CommitOperationDelete`] representing the deletion commits.
|
109 |
+
|
110 |
+
<Tip warning={true}>
|
111 |
+
|
112 |
+
`plan_multi_commits` is experimental. Its API and behavior is subject to change in the future without prior notice.
|
113 |
+
|
114 |
+
</Tip>
|
115 |
+
|
116 |
+
Example:
|
117 |
+
```python
|
118 |
+
>>> from huggingface_hub import HfApi, plan_multi_commits
|
119 |
+
>>> addition_commits, deletion_commits = plan_multi_commits(
|
120 |
+
... operations=[
|
121 |
+
... CommitOperationAdd(...),
|
122 |
+
... CommitOperationAdd(...),
|
123 |
+
... CommitOperationDelete(...),
|
124 |
+
... CommitOperationDelete(...),
|
125 |
+
... CommitOperationAdd(...),
|
126 |
+
... ],
|
127 |
+
... )
|
128 |
+
>>> HfApi().create_commits_on_pr(
|
129 |
+
... repo_id="my-cool-model",
|
130 |
+
... addition_commits=addition_commits,
|
131 |
+
... deletion_commits=deletion_commits,
|
132 |
+
... (...)
|
133 |
+
... verbose=True,
|
134 |
+
... )
|
135 |
+
```
|
136 |
+
|
137 |
+
<Tip warning={true}>
|
138 |
+
|
139 |
+
The initial order of the operations is not guaranteed! All deletions will be performed before additions. If you are
|
140 |
+
not updating multiple times the same file, you are fine.
|
141 |
+
|
142 |
+
</Tip>
|
143 |
+
"""
|
144 |
+
addition_commits: List[List[CommitOperationAdd]] = []
|
145 |
+
deletion_commits: List[List[CommitOperationDelete]] = []
|
146 |
+
|
147 |
+
additions: List[CommitOperationAdd] = []
|
148 |
+
additions_size = 0
|
149 |
+
deletions: List[CommitOperationDelete] = []
|
150 |
+
for op in operations:
|
151 |
+
if isinstance(op, CommitOperationDelete):
|
152 |
+
# Group delete operations together
|
153 |
+
deletions.append(op)
|
154 |
+
if len(deletions) >= max_operations_per_commit:
|
155 |
+
deletion_commits.append(deletions)
|
156 |
+
deletions = []
|
157 |
+
|
158 |
+
elif op.upload_info.size >= max_upload_size_per_commit:
|
159 |
+
# Upload huge files 1 by 1
|
160 |
+
addition_commits.append([op])
|
161 |
+
|
162 |
+
elif additions_size + op.upload_info.size < max_upload_size_per_commit:
|
163 |
+
# Group other additions and split if size limit is reached (either max_nb_files or max_upload_size)
|
164 |
+
additions.append(op)
|
165 |
+
additions_size += op.upload_info.size
|
166 |
+
|
167 |
+
else:
|
168 |
+
addition_commits.append(additions)
|
169 |
+
additions = [op]
|
170 |
+
additions_size = op.upload_info.size
|
171 |
+
|
172 |
+
if len(additions) >= max_operations_per_commit:
|
173 |
+
addition_commits.append(additions)
|
174 |
+
additions = []
|
175 |
+
additions_size = 0
|
176 |
+
|
177 |
+
if len(additions) > 0:
|
178 |
+
addition_commits.append(additions)
|
179 |
+
if len(deletions) > 0:
|
180 |
+
deletion_commits.append(deletions)
|
181 |
+
|
182 |
+
return addition_commits, deletion_commits
|
183 |
+
|
184 |
+
|
185 |
+
@dataclass
|
186 |
+
class MultiCommitStep:
|
187 |
+
"""Dataclass containing a list of CommitOperation to commit at once.
|
188 |
+
|
189 |
+
A [`MultiCommitStep`] is one atomic part of a [`MultiCommitStrategy`]. Each step is identified by its own
|
190 |
+
deterministic ID based on the list of commit operations (hexadecimal sha256). ID is persistent between re-runs if
|
191 |
+
the list of commits is kept the same.
|
192 |
+
"""
|
193 |
+
|
194 |
+
operations: List[Union[CommitOperationAdd, CommitOperationDelete]]
|
195 |
+
|
196 |
+
id: str = field(init=False)
|
197 |
+
completed: bool = False
|
198 |
+
|
199 |
+
def __post_init__(self) -> None:
|
200 |
+
if len(self.operations) == 0:
|
201 |
+
raise ValueError("A MultiCommitStep must have at least 1 commit operation, got 0.")
|
202 |
+
|
203 |
+
# Generate commit id
|
204 |
+
sha = sha256()
|
205 |
+
for op in self.operations:
|
206 |
+
if isinstance(op, CommitOperationAdd):
|
207 |
+
sha.update(b"ADD")
|
208 |
+
sha.update(op.path_in_repo.encode())
|
209 |
+
sha.update(op.upload_info.sha256)
|
210 |
+
elif isinstance(op, CommitOperationDelete):
|
211 |
+
sha.update(b"DELETE")
|
212 |
+
sha.update(op.path_in_repo.encode())
|
213 |
+
sha.update(str(op.is_folder).encode())
|
214 |
+
else:
|
215 |
+
NotImplementedError()
|
216 |
+
self.id = sha.hexdigest()
|
217 |
+
|
218 |
+
def __str__(self) -> str:
|
219 |
+
"""Format a step for PR description.
|
220 |
+
|
221 |
+
Formatting can be changed in the future as long as it is single line, starts with `- [ ]`/`- [x]` and contains
|
222 |
+
`self.id`. Must be able to match `STEP_ID_REGEX`.
|
223 |
+
"""
|
224 |
+
additions = [op for op in self.operations if isinstance(op, CommitOperationAdd)]
|
225 |
+
file_deletions = [op for op in self.operations if isinstance(op, CommitOperationDelete) and not op.is_folder]
|
226 |
+
folder_deletions = [op for op in self.operations if isinstance(op, CommitOperationDelete) and op.is_folder]
|
227 |
+
if len(additions) > 0:
|
228 |
+
return (
|
229 |
+
f"- [{'x' if self.completed else ' '}] Upload {len(additions)} file(s) "
|
230 |
+
f"totalling {_format_size(sum(add.upload_info.size for add in additions))}"
|
231 |
+
f" ({self.id})"
|
232 |
+
)
|
233 |
+
else:
|
234 |
+
return (
|
235 |
+
f"- [{'x' if self.completed else ' '}] Delete {len(file_deletions)} file(s) and"
|
236 |
+
f" {len(folder_deletions)} folder(s) ({self.id})"
|
237 |
+
)
|
238 |
+
|
239 |
+
|
240 |
+
@dataclass
|
241 |
+
class MultiCommitStrategy:
|
242 |
+
"""Dataclass containing a list of [`MultiCommitStep`] to commit iteratively.
|
243 |
+
|
244 |
+
A strategy is identified by its own deterministic ID based on the list of its steps (hexadecimal sha256). ID is
|
245 |
+
persistent between re-runs if the list of commits is kept the same.
|
246 |
+
"""
|
247 |
+
|
248 |
+
addition_commits: List[MultiCommitStep]
|
249 |
+
deletion_commits: List[MultiCommitStep]
|
250 |
+
|
251 |
+
id: str = field(init=False)
|
252 |
+
all_steps: Set[str] = field(init=False)
|
253 |
+
|
254 |
+
def __post_init__(self) -> None:
|
255 |
+
self.all_steps = {step.id for step in self.addition_commits + self.deletion_commits}
|
256 |
+
if len(self.all_steps) < len(self.addition_commits) + len(self.deletion_commits):
|
257 |
+
raise ValueError("Got duplicate commits in MultiCommitStrategy. All commits must be unique.")
|
258 |
+
|
259 |
+
if len(self.all_steps) == 0:
|
260 |
+
raise ValueError("A MultiCommitStrategy must have at least 1 commit, got 0.")
|
261 |
+
|
262 |
+
# Generate strategy id
|
263 |
+
sha = sha256()
|
264 |
+
for step in self.addition_commits + self.deletion_commits:
|
265 |
+
sha.update("new step".encode())
|
266 |
+
sha.update(step.id.encode())
|
267 |
+
self.id = sha.hexdigest()
|
268 |
+
|
269 |
+
|
270 |
+
def multi_commit_create_pull_request(
|
271 |
+
api: "HfApi",
|
272 |
+
repo_id: str,
|
273 |
+
commit_message: str,
|
274 |
+
commit_description: Optional[str],
|
275 |
+
strategy: MultiCommitStrategy,
|
276 |
+
repo_type: Optional[str],
|
277 |
+
token: Union[str, bool, None] = None,
|
278 |
+
) -> DiscussionWithDetails:
|
279 |
+
return api.create_pull_request(
|
280 |
+
repo_id=repo_id,
|
281 |
+
title=f"[WIP] {commit_message} (multi-commit {strategy.id})",
|
282 |
+
description=multi_commit_generate_comment(
|
283 |
+
commit_message=commit_message, commit_description=commit_description, strategy=strategy
|
284 |
+
),
|
285 |
+
token=token,
|
286 |
+
repo_type=repo_type,
|
287 |
+
)
|
288 |
+
|
289 |
+
|
290 |
+
def multi_commit_generate_comment(
|
291 |
+
commit_message: str,
|
292 |
+
commit_description: Optional[str],
|
293 |
+
strategy: MultiCommitStrategy,
|
294 |
+
) -> str:
|
295 |
+
return MULTI_COMMIT_PR_DESCRIPTION_TEMPLATE.format(
|
296 |
+
commit_message=commit_message,
|
297 |
+
commit_description=commit_description or "",
|
298 |
+
multi_commit_id=strategy.id,
|
299 |
+
multi_commit_strategy="\n".join(
|
300 |
+
str(commit) for commit in strategy.deletion_commits + strategy.addition_commits
|
301 |
+
),
|
302 |
+
)
|
303 |
+
|
304 |
+
|
305 |
+
def multi_commit_parse_pr_description(description: str) -> Set[str]:
|
306 |
+
return {match[1] for match in STEP_ID_REGEX.findall(description)}
|
llmeval-env/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py
ADDED
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from pathlib import Path
|
3 |
+
from typing import Dict, List, Literal, Optional, Union
|
4 |
+
|
5 |
+
import requests
|
6 |
+
from tqdm.auto import tqdm as base_tqdm
|
7 |
+
from tqdm.contrib.concurrent import thread_map
|
8 |
+
|
9 |
+
from .constants import (
|
10 |
+
DEFAULT_ETAG_TIMEOUT,
|
11 |
+
DEFAULT_REVISION,
|
12 |
+
HF_HUB_CACHE,
|
13 |
+
HF_HUB_ENABLE_HF_TRANSFER,
|
14 |
+
REPO_TYPES,
|
15 |
+
)
|
16 |
+
from .file_download import REGEX_COMMIT_HASH, hf_hub_download, repo_folder_name
|
17 |
+
from .hf_api import DatasetInfo, HfApi, ModelInfo, SpaceInfo
|
18 |
+
from .utils import (
|
19 |
+
GatedRepoError,
|
20 |
+
LocalEntryNotFoundError,
|
21 |
+
OfflineModeIsEnabled,
|
22 |
+
RepositoryNotFoundError,
|
23 |
+
RevisionNotFoundError,
|
24 |
+
filter_repo_objects,
|
25 |
+
logging,
|
26 |
+
validate_hf_hub_args,
|
27 |
+
)
|
28 |
+
from .utils import tqdm as hf_tqdm
|
29 |
+
|
30 |
+
|
31 |
+
logger = logging.get_logger(__name__)
|
32 |
+
|
33 |
+
|
34 |
+
@validate_hf_hub_args
|
35 |
+
def snapshot_download(
|
36 |
+
repo_id: str,
|
37 |
+
*,
|
38 |
+
repo_type: Optional[str] = None,
|
39 |
+
revision: Optional[str] = None,
|
40 |
+
cache_dir: Union[str, Path, None] = None,
|
41 |
+
local_dir: Union[str, Path, None] = None,
|
42 |
+
library_name: Optional[str] = None,
|
43 |
+
library_version: Optional[str] = None,
|
44 |
+
user_agent: Optional[Union[Dict, str]] = None,
|
45 |
+
proxies: Optional[Dict] = None,
|
46 |
+
etag_timeout: float = DEFAULT_ETAG_TIMEOUT,
|
47 |
+
force_download: bool = False,
|
48 |
+
token: Optional[Union[bool, str]] = None,
|
49 |
+
local_files_only: bool = False,
|
50 |
+
allow_patterns: Optional[Union[List[str], str]] = None,
|
51 |
+
ignore_patterns: Optional[Union[List[str], str]] = None,
|
52 |
+
max_workers: int = 8,
|
53 |
+
tqdm_class: Optional[base_tqdm] = None,
|
54 |
+
headers: Optional[Dict[str, str]] = None,
|
55 |
+
endpoint: Optional[str] = None,
|
56 |
+
# Deprecated args
|
57 |
+
local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
|
58 |
+
resume_download: Optional[bool] = None,
|
59 |
+
) -> str:
|
60 |
+
"""Download repo files.
|
61 |
+
|
62 |
+
Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
|
63 |
+
a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
|
64 |
+
to keep their actual filename relative to that folder. You can also filter which files to download using
|
65 |
+
`allow_patterns` and `ignore_patterns`.
|
66 |
+
|
67 |
+
If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
|
68 |
+
option, the `cache_dir` will not be used and a `.huggingface/` folder will be created at the root of `local_dir`
|
69 |
+
to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
|
70 |
+
cache-system, it's optimized for regularly pulling the latest version of a repository.
|
71 |
+
|
72 |
+
An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
|
73 |
+
configured. It is also not possible to filter which files to download when cloning a repository using git.
|
74 |
+
|
75 |
+
Args:
|
76 |
+
repo_id (`str`):
|
77 |
+
A user or an organization name and a repo name separated by a `/`.
|
78 |
+
repo_type (`str`, *optional*):
|
79 |
+
Set to `"dataset"` or `"space"` if downloading from a dataset or space,
|
80 |
+
`None` or `"model"` if downloading from a model. Default is `None`.
|
81 |
+
revision (`str`, *optional*):
|
82 |
+
An optional Git revision id which can be a branch name, a tag, or a
|
83 |
+
commit hash.
|
84 |
+
cache_dir (`str`, `Path`, *optional*):
|
85 |
+
Path to the folder where cached files are stored.
|
86 |
+
local_dir (`str` or `Path`, *optional*):
|
87 |
+
If provided, the downloaded files will be placed under this directory.
|
88 |
+
library_name (`str`, *optional*):
|
89 |
+
The name of the library to which the object corresponds.
|
90 |
+
library_version (`str`, *optional*):
|
91 |
+
The version of the library.
|
92 |
+
user_agent (`str`, `dict`, *optional*):
|
93 |
+
The user-agent info in the form of a dictionary or a string.
|
94 |
+
proxies (`dict`, *optional*):
|
95 |
+
Dictionary mapping protocol to the URL of the proxy passed to
|
96 |
+
`requests.request`.
|
97 |
+
etag_timeout (`float`, *optional*, defaults to `10`):
|
98 |
+
When fetching ETag, how many seconds to wait for the server to send
|
99 |
+
data before giving up which is passed to `requests.request`.
|
100 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
101 |
+
Whether the file should be downloaded even if it already exists in the local cache.
|
102 |
+
token (`str`, `bool`, *optional*):
|
103 |
+
A token to be used for the download.
|
104 |
+
- If `True`, the token is read from the HuggingFace config
|
105 |
+
folder.
|
106 |
+
- If a string, it's used as the authentication token.
|
107 |
+
headers (`dict`, *optional*):
|
108 |
+
Additional headers to include in the request. Those headers take precedence over the others.
|
109 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
110 |
+
If `True`, avoid downloading the file and return the path to the
|
111 |
+
local cached file if it exists.
|
112 |
+
allow_patterns (`List[str]` or `str`, *optional*):
|
113 |
+
If provided, only files matching at least one pattern are downloaded.
|
114 |
+
ignore_patterns (`List[str]` or `str`, *optional*):
|
115 |
+
If provided, files matching any of the patterns are not downloaded.
|
116 |
+
max_workers (`int`, *optional*):
|
117 |
+
Number of concurrent threads to download files (1 thread = 1 file download).
|
118 |
+
Defaults to 8.
|
119 |
+
tqdm_class (`tqdm`, *optional*):
|
120 |
+
If provided, overwrites the default behavior for the progress bar. Passed
|
121 |
+
argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
|
122 |
+
Note that the `tqdm_class` is not passed to each individual download.
|
123 |
+
Defaults to the custom HF progress bar that can be disabled by setting
|
124 |
+
`HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
|
125 |
+
|
126 |
+
Returns:
|
127 |
+
`str`: folder path of the repo snapshot.
|
128 |
+
|
129 |
+
Raises:
|
130 |
+
- [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
131 |
+
if `token=True` and the token cannot be found.
|
132 |
+
- [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
|
133 |
+
ETag cannot be determined.
|
134 |
+
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
135 |
+
if some parameter value is invalid
|
136 |
+
"""
|
137 |
+
if cache_dir is None:
|
138 |
+
cache_dir = HF_HUB_CACHE
|
139 |
+
if revision is None:
|
140 |
+
revision = DEFAULT_REVISION
|
141 |
+
if isinstance(cache_dir, Path):
|
142 |
+
cache_dir = str(cache_dir)
|
143 |
+
|
144 |
+
if repo_type is None:
|
145 |
+
repo_type = "model"
|
146 |
+
if repo_type not in REPO_TYPES:
|
147 |
+
raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(REPO_TYPES)}")
|
148 |
+
|
149 |
+
storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
|
150 |
+
|
151 |
+
repo_info: Union[ModelInfo, DatasetInfo, SpaceInfo, None] = None
|
152 |
+
api_call_error: Optional[Exception] = None
|
153 |
+
if not local_files_only:
|
154 |
+
# try/except logic to handle different errors => taken from `hf_hub_download`
|
155 |
+
try:
|
156 |
+
# if we have internet connection we want to list files to download
|
157 |
+
api = HfApi(
|
158 |
+
library_name=library_name,
|
159 |
+
library_version=library_version,
|
160 |
+
user_agent=user_agent,
|
161 |
+
endpoint=endpoint,
|
162 |
+
headers=headers,
|
163 |
+
)
|
164 |
+
repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision, token=token)
|
165 |
+
except (requests.exceptions.SSLError, requests.exceptions.ProxyError):
|
166 |
+
# Actually raise for those subclasses of ConnectionError
|
167 |
+
raise
|
168 |
+
except (
|
169 |
+
requests.exceptions.ConnectionError,
|
170 |
+
requests.exceptions.Timeout,
|
171 |
+
OfflineModeIsEnabled,
|
172 |
+
) as error:
|
173 |
+
# Internet connection is down
|
174 |
+
# => will try to use local files only
|
175 |
+
api_call_error = error
|
176 |
+
pass
|
177 |
+
except RevisionNotFoundError:
|
178 |
+
# The repo was found but the revision doesn't exist on the Hub (never existed or got deleted)
|
179 |
+
raise
|
180 |
+
except requests.HTTPError as error:
|
181 |
+
# Multiple reasons for an http error:
|
182 |
+
# - Repository is private and invalid/missing token sent
|
183 |
+
# - Repository is gated and invalid/missing token sent
|
184 |
+
# - Hub is down (error 500 or 504)
|
185 |
+
# => let's switch to 'local_files_only=True' to check if the files are already cached.
|
186 |
+
# (if it's not the case, the error will be re-raised)
|
187 |
+
api_call_error = error
|
188 |
+
pass
|
189 |
+
|
190 |
+
# At this stage, if `repo_info` is None it means either:
|
191 |
+
# - internet connection is down
|
192 |
+
# - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True)
|
193 |
+
# - repo is private/gated and invalid/missing token sent
|
194 |
+
# - Hub is down
|
195 |
+
# => let's look if we can find the appropriate folder in the cache:
|
196 |
+
# - if the specified revision is a commit hash, look inside "snapshots".
|
197 |
+
# - f the specified revision is a branch or tag, look inside "refs".
|
198 |
+
if repo_info is None:
|
199 |
+
# Try to get which commit hash corresponds to the specified revision
|
200 |
+
commit_hash = None
|
201 |
+
if REGEX_COMMIT_HASH.match(revision):
|
202 |
+
commit_hash = revision
|
203 |
+
else:
|
204 |
+
ref_path = os.path.join(storage_folder, "refs", revision)
|
205 |
+
if os.path.exists(ref_path):
|
206 |
+
# retrieve commit_hash from refs file
|
207 |
+
with open(ref_path) as f:
|
208 |
+
commit_hash = f.read()
|
209 |
+
|
210 |
+
# Try to locate snapshot folder for this commit hash
|
211 |
+
if commit_hash is not None:
|
212 |
+
snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
|
213 |
+
if os.path.exists(snapshot_folder):
|
214 |
+
# Snapshot folder exists => let's return it
|
215 |
+
# (but we can't check if all the files are actually there)
|
216 |
+
return snapshot_folder
|
217 |
+
|
218 |
+
# If we couldn't find the appropriate folder on disk, raise an error.
|
219 |
+
if local_files_only:
|
220 |
+
raise LocalEntryNotFoundError(
|
221 |
+
"Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
|
222 |
+
"outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass "
|
223 |
+
"'local_files_only=False' as input."
|
224 |
+
)
|
225 |
+
elif isinstance(api_call_error, OfflineModeIsEnabled):
|
226 |
+
raise LocalEntryNotFoundError(
|
227 |
+
"Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
|
228 |
+
"outgoing traffic has been disabled. To enable repo look-ups and downloads online, set "
|
229 |
+
"'HF_HUB_OFFLINE=0' as environment variable."
|
230 |
+
) from api_call_error
|
231 |
+
elif isinstance(api_call_error, RepositoryNotFoundError) or isinstance(api_call_error, GatedRepoError):
|
232 |
+
# Repo not found => let's raise the actual error
|
233 |
+
raise api_call_error
|
234 |
+
else:
|
235 |
+
# Otherwise: most likely a connection issue or Hub downtime => let's warn the user
|
236 |
+
raise LocalEntryNotFoundError(
|
237 |
+
"An error happened while trying to locate the files on the Hub and we cannot find the appropriate"
|
238 |
+
" snapshot folder for the specified revision on the local disk. Please check your internet connection"
|
239 |
+
" and try again."
|
240 |
+
) from api_call_error
|
241 |
+
|
242 |
+
# At this stage, internet connection is up and running
|
243 |
+
# => let's download the files!
|
244 |
+
assert repo_info.sha is not None, "Repo info returned from server must have a revision sha."
|
245 |
+
assert repo_info.siblings is not None, "Repo info returned from server must have a siblings list."
|
246 |
+
filtered_repo_files = list(
|
247 |
+
filter_repo_objects(
|
248 |
+
items=[f.rfilename for f in repo_info.siblings],
|
249 |
+
allow_patterns=allow_patterns,
|
250 |
+
ignore_patterns=ignore_patterns,
|
251 |
+
)
|
252 |
+
)
|
253 |
+
commit_hash = repo_info.sha
|
254 |
+
snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
|
255 |
+
# if passed revision is not identical to commit_hash
|
256 |
+
# then revision has to be a branch name or tag name.
|
257 |
+
# In that case store a ref.
|
258 |
+
if revision != commit_hash:
|
259 |
+
ref_path = os.path.join(storage_folder, "refs", revision)
|
260 |
+
os.makedirs(os.path.dirname(ref_path), exist_ok=True)
|
261 |
+
with open(ref_path, "w") as f:
|
262 |
+
f.write(commit_hash)
|
263 |
+
|
264 |
+
# we pass the commit_hash to hf_hub_download
|
265 |
+
# so no network call happens if we already
|
266 |
+
# have the file locally.
|
267 |
+
def _inner_hf_hub_download(repo_file: str):
|
268 |
+
return hf_hub_download(
|
269 |
+
repo_id,
|
270 |
+
filename=repo_file,
|
271 |
+
repo_type=repo_type,
|
272 |
+
revision=commit_hash,
|
273 |
+
endpoint=endpoint,
|
274 |
+
cache_dir=cache_dir,
|
275 |
+
local_dir=local_dir,
|
276 |
+
local_dir_use_symlinks=local_dir_use_symlinks,
|
277 |
+
library_name=library_name,
|
278 |
+
library_version=library_version,
|
279 |
+
user_agent=user_agent,
|
280 |
+
proxies=proxies,
|
281 |
+
etag_timeout=etag_timeout,
|
282 |
+
resume_download=resume_download,
|
283 |
+
force_download=force_download,
|
284 |
+
token=token,
|
285 |
+
headers=headers,
|
286 |
+
)
|
287 |
+
|
288 |
+
if HF_HUB_ENABLE_HF_TRANSFER:
|
289 |
+
# when using hf_transfer we don't want extra parallelism
|
290 |
+
# from the one hf_transfer provides
|
291 |
+
for file in filtered_repo_files:
|
292 |
+
_inner_hf_hub_download(file)
|
293 |
+
else:
|
294 |
+
thread_map(
|
295 |
+
_inner_hf_hub_download,
|
296 |
+
filtered_repo_files,
|
297 |
+
desc=f"Fetching {len(filtered_repo_files)} files",
|
298 |
+
max_workers=max_workers,
|
299 |
+
# User can use its own tqdm class or the default one from `huggingface_hub.utils`
|
300 |
+
tqdm_class=tqdm_class or hf_tqdm,
|
301 |
+
)
|
302 |
+
|
303 |
+
if local_dir is not None:
|
304 |
+
return str(os.path.realpath(local_dir))
|
305 |
+
return snapshot_folder
|