applied-ai-018 commited on
Commit
ea2504d
·
verified ·
1 Parent(s): d3c0637

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/METADATA +245 -0
  2. env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/RECORD +119 -0
  3. env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/WHEEL +6 -0
  4. env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/top_level.txt +1 -0
  5. env-llmeval/lib/python3.10/site-packages/huggingface_hub/__init__.py +884 -0
  6. env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_api.py +698 -0
  7. env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py +327 -0
  8. env-llmeval/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py +384 -0
  9. env-llmeval/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py +306 -0
  10. env-llmeval/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py +327 -0
  11. env-llmeval/lib/python3.10/site-packages/huggingface_hub/_space_api.py +155 -0
  12. env-llmeval/lib/python3.10/site-packages/huggingface_hub/_webhooks_payload.py +116 -0
  13. env-llmeval/lib/python3.10/site-packages/huggingface_hub/community.py +355 -0
  14. env-llmeval/lib/python3.10/site-packages/huggingface_hub/constants.py +215 -0
  15. env-llmeval/lib/python3.10/site-packages/huggingface_hub/errors.py +38 -0
  16. env-llmeval/lib/python3.10/site-packages/huggingface_hub/file_download.py +1770 -0
  17. env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_api.py +0 -0
  18. env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_file_system.py +867 -0
  19. env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference_api.py +217 -0
  20. env-llmeval/lib/python3.10/site-packages/huggingface_hub/lfs.py +541 -0
  21. env-llmeval/lib/python3.10/site-packages/huggingface_hub/repocard.py +828 -0
  22. env-llmeval/lib/python3.10/site-packages/huggingface_hub/repository.py +1476 -0
  23. env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/datasetcard_template.md +143 -0
  24. env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/modelcard_template.md +200 -0
  25. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py +122 -0
  26. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_assets.py +135 -0
  30. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_manager.py +813 -0
  31. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_chunk_utils.py +65 -0
  32. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_datetime.py +62 -0
  33. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_deprecation.py +136 -0
  34. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py +397 -0
  35. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py +66 -0
  36. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_fixes.py +93 -0
  37. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_git_credential.py +121 -0
  38. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py +241 -0
  39. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_hf_folder.py +96 -0
  40. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_http.py +321 -0
  41. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py +52 -0
  42. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_paths.py +118 -0
  43. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_runtime.py +372 -0
  44. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_safetensors.py +124 -0
  45. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_subprocess.py +143 -0
  46. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py +118 -0
  47. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_token.py +130 -0
  48. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_typing.py +50 -0
  49. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py +231 -0
  50. env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/endpoint_helpers.py +250 -0
env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/METADATA ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: aiohttp
3
+ Version: 3.9.4
4
+ Summary: Async http client/server framework (asyncio)
5
+ Home-page: https://github.com/aio-libs/aiohttp
6
+ Maintainer: aiohttp team <[email protected]>
7
+ Maintainer-email: [email protected]
8
+ License: Apache 2
9
+ Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org
10
+ Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org
11
+ Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
12
+ Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp
13
+ Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html
14
+ Project-URL: Docs: RTD, https://docs.aiohttp.org
15
+ Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues
16
+ Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp
17
+ Classifier: Development Status :: 5 - Production/Stable
18
+ Classifier: Framework :: AsyncIO
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: License :: OSI Approved :: Apache Software License
21
+ Classifier: Operating System :: POSIX
22
+ Classifier: Operating System :: MacOS :: MacOS X
23
+ Classifier: Operating System :: Microsoft :: Windows
24
+ Classifier: Programming Language :: Python
25
+ Classifier: Programming Language :: Python :: 3
26
+ Classifier: Programming Language :: Python :: 3.8
27
+ Classifier: Programming Language :: Python :: 3.9
28
+ Classifier: Programming Language :: Python :: 3.10
29
+ Classifier: Programming Language :: Python :: 3.11
30
+ Classifier: Programming Language :: Python :: 3.12
31
+ Classifier: Topic :: Internet :: WWW/HTTP
32
+ Requires-Python: >=3.8
33
+ Description-Content-Type: text/x-rst
34
+ License-File: LICENSE.txt
35
+ Requires-Dist: aiosignal >=1.1.2
36
+ Requires-Dist: attrs >=17.3.0
37
+ Requires-Dist: frozenlist >=1.1.1
38
+ Requires-Dist: multidict <7.0,>=4.5
39
+ Requires-Dist: yarl <2.0,>=1.0
40
+ Requires-Dist: async-timeout <5.0,>=4.0 ; python_version < "3.11"
41
+ Provides-Extra: speedups
42
+ Requires-Dist: brotlicffi ; (platform_python_implementation != "CPython") and extra == 'speedups'
43
+ Requires-Dist: Brotli ; (platform_python_implementation == "CPython") and extra == 'speedups'
44
+ Requires-Dist: aiodns ; (sys_platform == "linux" or sys_platform == "darwin") and extra == 'speedups'
45
+
46
+ ==================================
47
+ Async http client/server framework
48
+ ==================================
49
+
50
+ .. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg
51
+ :height: 64px
52
+ :width: 64px
53
+ :alt: aiohttp logo
54
+
55
+ |
56
+
57
+ .. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg
58
+ :target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
59
+ :alt: GitHub Actions status for master branch
60
+
61
+ .. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg
62
+ :target: https://codecov.io/gh/aio-libs/aiohttp
63
+ :alt: codecov.io status for master branch
64
+
65
+ .. image:: https://badge.fury.io/py/aiohttp.svg
66
+ :target: https://pypi.org/project/aiohttp
67
+ :alt: Latest PyPI package version
68
+
69
+ .. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest
70
+ :target: https://docs.aiohttp.org/
71
+ :alt: Latest Read The Docs
72
+
73
+ .. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
74
+ :target: https://matrix.to/#/%23aio-libs:matrix.org
75
+ :alt: Matrix Room — #aio-libs:matrix.org
76
+
77
+ .. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
78
+ :target: https://matrix.to/#/%23aio-libs-space:matrix.org
79
+ :alt: Matrix Space — #aio-libs-space:matrix.org
80
+
81
+
82
+ Key Features
83
+ ============
84
+
85
+ - Supports both client and server side of HTTP protocol.
86
+ - Supports both client and server Web-Sockets out-of-the-box and avoids
87
+ Callback Hell.
88
+ - Provides Web-server with middleware and pluggable routing.
89
+
90
+
91
+ Getting started
92
+ ===============
93
+
94
+ Client
95
+ ------
96
+
97
+ To get something from the web:
98
+
99
+ .. code-block:: python
100
+
101
+ import aiohttp
102
+ import asyncio
103
+
104
+ async def main():
105
+
106
+ async with aiohttp.ClientSession() as session:
107
+ async with session.get('http://python.org') as response:
108
+
109
+ print("Status:", response.status)
110
+ print("Content-type:", response.headers['content-type'])
111
+
112
+ html = await response.text()
113
+ print("Body:", html[:15], "...")
114
+
115
+ asyncio.run(main())
116
+
117
+ This prints:
118
+
119
+ .. code-block::
120
+
121
+ Status: 200
122
+ Content-type: text/html; charset=utf-8
123
+ Body: <!doctype html> ...
124
+
125
+ Coming from `requests <https://requests.readthedocs.io/>`_ ? Read `why we need so many lines <https://aiohttp.readthedocs.io/en/latest/http_request_lifecycle.html>`_.
126
+
127
+ Server
128
+ ------
129
+
130
+ An example using a simple server:
131
+
132
+ .. code-block:: python
133
+
134
+ # examples/server_simple.py
135
+ from aiohttp import web
136
+
137
+ async def handle(request):
138
+ name = request.match_info.get('name', "Anonymous")
139
+ text = "Hello, " + name
140
+ return web.Response(text=text)
141
+
142
+ async def wshandle(request):
143
+ ws = web.WebSocketResponse()
144
+ await ws.prepare(request)
145
+
146
+ async for msg in ws:
147
+ if msg.type == web.WSMsgType.text:
148
+ await ws.send_str("Hello, {}".format(msg.data))
149
+ elif msg.type == web.WSMsgType.binary:
150
+ await ws.send_bytes(msg.data)
151
+ elif msg.type == web.WSMsgType.close:
152
+ break
153
+
154
+ return ws
155
+
156
+
157
+ app = web.Application()
158
+ app.add_routes([web.get('/', handle),
159
+ web.get('/echo', wshandle),
160
+ web.get('/{name}', handle)])
161
+
162
+ if __name__ == '__main__':
163
+ web.run_app(app)
164
+
165
+
166
+ Documentation
167
+ =============
168
+
169
+ https://aiohttp.readthedocs.io/
170
+
171
+
172
+ Demos
173
+ =====
174
+
175
+ https://github.com/aio-libs/aiohttp-demos
176
+
177
+
178
+ External links
179
+ ==============
180
+
181
+ * `Third party libraries
182
+ <http://aiohttp.readthedocs.io/en/latest/third_party.html>`_
183
+ * `Built with aiohttp
184
+ <http://aiohttp.readthedocs.io/en/latest/built_with.html>`_
185
+ * `Powered by aiohttp
186
+ <http://aiohttp.readthedocs.io/en/latest/powered_by.html>`_
187
+
188
+ Feel free to make a Pull Request for adding your link to these pages!
189
+
190
+
191
+ Communication channels
192
+ ======================
193
+
194
+ *aio-libs Discussions*: https://github.com/aio-libs/aiohttp/discussions
195
+
196
+ *gitter chat* https://gitter.im/aio-libs/Lobby
197
+
198
+ We support `Stack Overflow
199
+ <https://stackoverflow.com/questions/tagged/aiohttp>`_.
200
+ Please add *aiohttp* tag to your question there.
201
+
202
+ Requirements
203
+ ============
204
+
205
+ - async-timeout_
206
+ - attrs_
207
+ - multidict_
208
+ - yarl_
209
+ - frozenlist_
210
+
211
+ Optionally you may install the aiodns_ library (highly recommended for sake of speed).
212
+
213
+ .. _aiodns: https://pypi.python.org/pypi/aiodns
214
+ .. _attrs: https://github.com/python-attrs/attrs
215
+ .. _multidict: https://pypi.python.org/pypi/multidict
216
+ .. _frozenlist: https://pypi.org/project/frozenlist/
217
+ .. _yarl: https://pypi.python.org/pypi/yarl
218
+ .. _async-timeout: https://pypi.python.org/pypi/async_timeout
219
+
220
+ License
221
+ =======
222
+
223
+ ``aiohttp`` is offered under the Apache 2 license.
224
+
225
+
226
+ Keepsafe
227
+ ========
228
+
229
+ The aiohttp community would like to thank Keepsafe
230
+ (https://www.getkeepsafe.com) for its support in the early days of
231
+ the project.
232
+
233
+
234
+ Source code
235
+ ===========
236
+
237
+ The latest developer version is available in a GitHub repository:
238
+ https://github.com/aio-libs/aiohttp
239
+
240
+ Benchmarks
241
+ ==========
242
+
243
+ If you are interested in efficiency, the AsyncIO community maintains a
244
+ list of benchmarks on the official wiki:
245
+ https://github.com/python/asyncio/wiki/Benchmarks
env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/RECORD ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiohttp-3.9.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ aiohttp-3.9.4.dist-info/LICENSE.txt,sha256=n4DQ2311WpQdtFchcsJw7L2PCCuiFd3QlZhZQu2Uqes,588
3
+ aiohttp-3.9.4.dist-info/METADATA,sha256=64vtragOO4Zw4yBCfFzvia09h_Aqyc1LskXnwmRVedo,7459
4
+ aiohttp-3.9.4.dist-info/RECORD,,
5
+ aiohttp-3.9.4.dist-info/WHEEL,sha256=CzQQWV-lNyM92gr3iaBk8dvO35YDHRxgzkZ-dxumUIM,152
6
+ aiohttp-3.9.4.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8
7
+ aiohttp/.hash/_cparser.pxd.hash,sha256=hYa9Vje-oMs2eh_7MfCPOh2QW_1x1yCjcZuc7AmwLd0,121
8
+ aiohttp/.hash/_find_header.pxd.hash,sha256=_mbpD6vM-CVCKq3ulUvsOAz5Wdo88wrDzfpOsMQaMNA,125
9
+ aiohttp/.hash/_helpers.pyi.hash,sha256=Ew4BZDc2LqFwszgZZUHHrJvw5P8HBhJ700n1Ntg52hE,121
10
+ aiohttp/.hash/_helpers.pyx.hash,sha256=5JQ6BlMBE4HnRaCGdkK9_wpL3ZSWpU1gyLYva0Wwx2c,121
11
+ aiohttp/.hash/_http_parser.pyx.hash,sha256=4RMfISkoa9dJKvYXpa_Qe7b_32v4k7HXpaGhgXcNK4k,125
12
+ aiohttp/.hash/_http_writer.pyx.hash,sha256=3Qg3T3D-Ud73elzPHBufK0yEu9tP5jsu6g-aPKQY9gE,125
13
+ aiohttp/.hash/_websocket.pyx.hash,sha256=M97f-Yti-4vnE4GNTD1s_DzKs-fG_ww3jle6EUvixnE,123
14
+ aiohttp/.hash/hdrs.py.hash,sha256=2oEszMWjYFTHoF2w4OcFCoM7osv4vY9KLLJCu9HP0xI,116
15
+ aiohttp/__init__.py,sha256=jHB59t8RTTFUAhgySoHSKtCmKtDv7kcerMGKPavU1Wk,7762
16
+ aiohttp/__pycache__/__init__.cpython-310.pyc,,
17
+ aiohttp/__pycache__/abc.cpython-310.pyc,,
18
+ aiohttp/__pycache__/base_protocol.cpython-310.pyc,,
19
+ aiohttp/__pycache__/client.cpython-310.pyc,,
20
+ aiohttp/__pycache__/client_exceptions.cpython-310.pyc,,
21
+ aiohttp/__pycache__/client_proto.cpython-310.pyc,,
22
+ aiohttp/__pycache__/client_reqrep.cpython-310.pyc,,
23
+ aiohttp/__pycache__/client_ws.cpython-310.pyc,,
24
+ aiohttp/__pycache__/compression_utils.cpython-310.pyc,,
25
+ aiohttp/__pycache__/connector.cpython-310.pyc,,
26
+ aiohttp/__pycache__/cookiejar.cpython-310.pyc,,
27
+ aiohttp/__pycache__/formdata.cpython-310.pyc,,
28
+ aiohttp/__pycache__/hdrs.cpython-310.pyc,,
29
+ aiohttp/__pycache__/helpers.cpython-310.pyc,,
30
+ aiohttp/__pycache__/http.cpython-310.pyc,,
31
+ aiohttp/__pycache__/http_exceptions.cpython-310.pyc,,
32
+ aiohttp/__pycache__/http_parser.cpython-310.pyc,,
33
+ aiohttp/__pycache__/http_websocket.cpython-310.pyc,,
34
+ aiohttp/__pycache__/http_writer.cpython-310.pyc,,
35
+ aiohttp/__pycache__/locks.cpython-310.pyc,,
36
+ aiohttp/__pycache__/log.cpython-310.pyc,,
37
+ aiohttp/__pycache__/multipart.cpython-310.pyc,,
38
+ aiohttp/__pycache__/payload.cpython-310.pyc,,
39
+ aiohttp/__pycache__/payload_streamer.cpython-310.pyc,,
40
+ aiohttp/__pycache__/pytest_plugin.cpython-310.pyc,,
41
+ aiohttp/__pycache__/resolver.cpython-310.pyc,,
42
+ aiohttp/__pycache__/streams.cpython-310.pyc,,
43
+ aiohttp/__pycache__/tcp_helpers.cpython-310.pyc,,
44
+ aiohttp/__pycache__/test_utils.cpython-310.pyc,,
45
+ aiohttp/__pycache__/tracing.cpython-310.pyc,,
46
+ aiohttp/__pycache__/typedefs.cpython-310.pyc,,
47
+ aiohttp/__pycache__/web.cpython-310.pyc,,
48
+ aiohttp/__pycache__/web_app.cpython-310.pyc,,
49
+ aiohttp/__pycache__/web_exceptions.cpython-310.pyc,,
50
+ aiohttp/__pycache__/web_fileresponse.cpython-310.pyc,,
51
+ aiohttp/__pycache__/web_log.cpython-310.pyc,,
52
+ aiohttp/__pycache__/web_middlewares.cpython-310.pyc,,
53
+ aiohttp/__pycache__/web_protocol.cpython-310.pyc,,
54
+ aiohttp/__pycache__/web_request.cpython-310.pyc,,
55
+ aiohttp/__pycache__/web_response.cpython-310.pyc,,
56
+ aiohttp/__pycache__/web_routedef.cpython-310.pyc,,
57
+ aiohttp/__pycache__/web_runner.cpython-310.pyc,,
58
+ aiohttp/__pycache__/web_server.cpython-310.pyc,,
59
+ aiohttp/__pycache__/web_urldispatcher.cpython-310.pyc,,
60
+ aiohttp/__pycache__/web_ws.cpython-310.pyc,,
61
+ aiohttp/__pycache__/worker.cpython-310.pyc,,
62
+ aiohttp/_cparser.pxd,sha256=8jGIg-VJ9p3llwCakUYDsPGxA4HiZe9dmK9Jmtlz-5g,4318
63
+ aiohttp/_find_header.pxd,sha256=0GfwFCPN2zxEKTO1_MA5sYq2UfzsG8kcV3aTqvwlz3g,68
64
+ aiohttp/_headers.pxi,sha256=n701k28dVPjwRnx5j6LpJhLTfj7dqu2vJt7f0O60Oyg,2007
65
+ aiohttp/_helpers.cpython-310-x86_64-linux-gnu.so,sha256=KZA_we6lVYYLcxtV5fNq7f72xOwd6kqp5YzJEJT9wMI,508784
66
+ aiohttp/_helpers.pyi,sha256=ZoKiJSS51PxELhI2cmIr5737YjjZcJt7FbIRO3ym1Ss,202
67
+ aiohttp/_helpers.pyx,sha256=XeLbNft5X_4ifi8QB8i6TyrRuayijMSO3IDHeSA89uM,1049
68
+ aiohttp/_http_parser.cpython-310-x86_64-linux-gnu.so,sha256=6BvwDWVHOAaETC4YAOd8I9YqEYJVq3yEjGYZtETeSm4,2586576
69
+ aiohttp/_http_parser.pyx,sha256=q68Rq06MpW-QwLxriE3hIJmWIKc4lVFaWHU3clsHd4Y,28125
70
+ aiohttp/_http_writer.cpython-310-x86_64-linux-gnu.so,sha256=llvQZrZI6yQIHp0lP-dgdlOWnLIIPLLWNhgEi9RsDI0,459368
71
+ aiohttp/_http_writer.pyx,sha256=aIHAp8g4ZV5kbGRdmZce-vXjELw2M6fGKyJuOdgYQqw,4575
72
+ aiohttp/_websocket.cpython-310-x86_64-linux-gnu.so,sha256=xO73eZVpxho_Omoz3Bh9muMnRL-7qPGEL5BTAyOTEeQ,234032
73
+ aiohttp/_websocket.pyx,sha256=1XuOSNDCbyDrzF5uMA2isqausSs8l2jWTLDlNDLM9Io,1561
74
+ aiohttp/abc.py,sha256=WGZ5HH0hoCH77qaISTb689ygpS9CxfKkgUCOcgjU2lo,5500
75
+ aiohttp/base_protocol.py,sha256=HJ5SxzbzYewj-sjoKMbD6i5rDYEv9Zo7Q_cyV3Wvn6o,2876
76
+ aiohttp/client.py,sha256=2EKZE0lcIMLjjaMZChAu_2GaSNj8TumqhhwgEEmpN6Q,47276
77
+ aiohttp/client_exceptions.py,sha256=7lx_YWAauUQVOxg_RehW9HZE344ak3lGmVJHfCrmb-A,9411
78
+ aiohttp/client_proto.py,sha256=kCRlCOYxiuUv83cHz-gDYF0bK4Ye_KgkhYibjqTpN_M,9910
79
+ aiohttp/client_reqrep.py,sha256=bt5woKRdhImzsEqg39a-O0yqswY8adguODtE-ui2RxE,40075
80
+ aiohttp/client_ws.py,sha256=nNrwu1wA0U3B0cNsVr61QfV2S60bbKfaZXHfW7klFl4,11010
81
+ aiohttp/compression_utils.py,sha256=GCkBNJqrybMhiTQGwqqhORnaTLpRFZD_-UvRtnZ5lEQ,5015
82
+ aiohttp/connector.py,sha256=meq8urjMWelJnG26VgkA3ibrIioaEWqujg3jjNAKG28,53796
83
+ aiohttp/cookiejar.py,sha256=PdvsOiDasDYYUOPaaAfuuFJzR4CJyHHjut02YiZ_N8M,14015
84
+ aiohttp/formdata.py,sha256=WjHA1mieKlWwI5O3hi3-siqN0dWz_X04oXNNZje2z7Q,6521
85
+ aiohttp/hdrs.py,sha256=uzn5agn_jXid2h-ky6Y0ZAQ8BrPeTGLDGr-weiMctso,4613
86
+ aiohttp/helpers.py,sha256=EAZ1V0pGfv2xRiWfhjubBqgLBI0aK-CXlUlYss3EYzo,30988
87
+ aiohttp/http.py,sha256=8o8j8xH70OWjnfTWA9V44NR785QPxEPrUtzMXiAVpwc,1842
88
+ aiohttp/http_exceptions.py,sha256=7LOFFUwq04fZsnZA-NP5nukd6c2i8daM8-ejj3ndbSQ,2716
89
+ aiohttp/http_parser.py,sha256=zuG3C-WOUVjoNTqgsrdCorzCGoXbR0gHhma3G___zOA,36507
90
+ aiohttp/http_websocket.py,sha256=9Kfp5e4TU1JJfEvJ7l1Kt6Cr2HZX3z_RIojN8BAriPI,26732
91
+ aiohttp/http_writer.py,sha256=fxpyRj_S3WcBl9fxxF05t8YYAUA-0jW5b_PjVSluT3Y,5933
92
+ aiohttp/locks.py,sha256=wRYFo1U82LwBBdqwU24JEPaoTAlKaaJd2FtfDKhkTb4,1136
93
+ aiohttp/log.py,sha256=BbNKx9e3VMIm0xYjZI0IcBBoS7wjdeIeSaiJE7-qK2g,325
94
+ aiohttp/multipart.py,sha256=UV6IYPZWgiwhK-DzDtvXd_FDdAL1yMv9xjkm52FR3R8,34561
95
+ aiohttp/payload.py,sha256=xK04Z-TSao-qiYVMnphKG9-6yOvoqGsZBM7egUS4n9A,13542
96
+ aiohttp/payload_streamer.py,sha256=eAS8S-UWfLkEMavRjP2Uu9amC3PnbV79wHTNDoRmYn8,2087
97
+ aiohttp/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
98
+ aiohttp/pytest_plugin.py,sha256=3IwpuxtFiUVFGS_ZitWuqvECSGgXQWvCW312B2TaVLY,11605
99
+ aiohttp/resolver.py,sha256=8peXjB482v0hg1ESn87op6f-UeLXk_fAMxQo_23Ek6M,5070
100
+ aiohttp/streams.py,sha256=LWlr0gE44cjKzBU9I15vWwlorPW8ZAU-M2Sgz_UdjWM,21128
101
+ aiohttp/tcp_helpers.py,sha256=BSadqVWaBpMFDRWnhaaR941N9MiDZ7bdTrxgCb0CW-M,961
102
+ aiohttp/test_utils.py,sha256=8-McpBCAzFbA17yeEW9UYVKBypu-Hm_407ppQy76XWU,20475
103
+ aiohttp/tracing.py,sha256=W94gFgxFtXSBWMU4ajbrOH61mJ4mElRmfyxNUw6FwIA,15132
104
+ aiohttp/typedefs.py,sha256=f-EzBBgQAxNLiTUtkjgMAL5LQt81HloYTesxnhNM03U,1471
105
+ aiohttp/web.py,sha256=HFTQaoYVK5pM3YmxNJtZl9fGrRIdFs_Nhloxe7_lJj0,19263
106
+ aiohttp/web_app.py,sha256=4cXDqZV-KR0xMnUhQ471bsEACIsoI4_BkDJ3haXyG_I,18311
107
+ aiohttp/web_exceptions.py,sha256=7nIuiwhZ39vJJ9KrWqArA5QcWbUdqkz2CLwEpJapeN8,10360
108
+ aiohttp/web_fileresponse.py,sha256=33VS-6CQd4ZiezNBVZaVxWBCLuOUK_vPMNTU1ojiV80,11569
109
+ aiohttp/web_log.py,sha256=DOfOxGyh2U7K5K_w6O7ILdfGcs4qOdzHxOwj2-k3c6c,7801
110
+ aiohttp/web_middlewares.py,sha256=q6i0GGiVvUlpGtsbZmp88-zFIKQHwYtDd5SpBvKFdEY,4032
111
+ aiohttp/web_protocol.py,sha256=8kAxmDpRYczyCFtUS4vDEIORgbD4WV0CTjVi-fZVykE,23060
112
+ aiohttp/web_request.py,sha256=UyDR4JQwogyX12FS8PpMl-1d6ZG-TE02Bt2nPOEk0HI,28986
113
+ aiohttp/web_response.py,sha256=3jfYnRpsNnxGRUAm-VNGu18Ekw5XyuYp7c7fzbOwbqY,27858
114
+ aiohttp/web_routedef.py,sha256=Y5DPVa7D1uJp37HP6YXrO8Cd1BrEtDyS-fljOUdPk30,6132
115
+ aiohttp/web_runner.py,sha256=rGI6zeIXZNDepvJajc8ZXue9hn0O2wSmh8S7CuXhkUI,11951
116
+ aiohttp/web_server.py,sha256=5P-9uPCoPEDkK9ILbvEXmkkJWPhnTxBzdwAXwveyyDk,2587
117
+ aiohttp/web_urldispatcher.py,sha256=e9QueGUecnOZq44CpfKJCjWi_IXHqHADUmIh_mzli18,40132
118
+ aiohttp/web_ws.py,sha256=eiLuPZnB6HFXagcdZzU9jD9aKXP3K6YNDXDIoOpN8co,18960
119
+ aiohttp/worker.py,sha256=bkozEd2rAzQS0qs4knnnplOmaZ4TNdYtqWXSXx9djEc,7965
env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.43.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_17_x86_64
5
+ Tag: cp310-cp310-manylinux2014_x86_64
6
+
env-llmeval/lib/python3.10/site-packages/aiohttp-3.9.4.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ aiohttp
env-llmeval/lib/python3.10/site-packages/huggingface_hub/__init__.py ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.22.2"
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_files_info",
202
+ "list_inference_endpoints",
203
+ "list_liked_repos",
204
+ "list_metrics",
205
+ "list_models",
206
+ "list_pending_access_requests",
207
+ "list_rejected_access_requests",
208
+ "list_repo_commits",
209
+ "list_repo_files",
210
+ "list_repo_likers",
211
+ "list_repo_refs",
212
+ "list_repo_tree",
213
+ "list_spaces",
214
+ "merge_pull_request",
215
+ "model_info",
216
+ "move_repo",
217
+ "parse_safetensors_file_metadata",
218
+ "pause_inference_endpoint",
219
+ "pause_space",
220
+ "preupload_lfs_files",
221
+ "reject_access_request",
222
+ "rename_discussion",
223
+ "repo_exists",
224
+ "repo_info",
225
+ "repo_type_and_id_from_hf_id",
226
+ "request_space_hardware",
227
+ "request_space_storage",
228
+ "restart_space",
229
+ "resume_inference_endpoint",
230
+ "revision_exists",
231
+ "run_as_future",
232
+ "scale_to_zero_inference_endpoint",
233
+ "set_space_sleep_time",
234
+ "space_info",
235
+ "super_squash_history",
236
+ "unlike",
237
+ "update_collection_item",
238
+ "update_collection_metadata",
239
+ "update_inference_endpoint",
240
+ "update_repo_visibility",
241
+ "upload_file",
242
+ "upload_folder",
243
+ "whoami",
244
+ ],
245
+ "hf_file_system": [
246
+ "HfFileSystem",
247
+ "HfFileSystemFile",
248
+ "HfFileSystemResolvedPath",
249
+ "HfFileSystemStreamFile",
250
+ ],
251
+ "hub_mixin": [
252
+ "ModelHubMixin",
253
+ "PyTorchModelHubMixin",
254
+ ],
255
+ "inference._client": [
256
+ "InferenceClient",
257
+ "InferenceTimeoutError",
258
+ ],
259
+ "inference._generated._async_client": [
260
+ "AsyncInferenceClient",
261
+ ],
262
+ "inference._generated.types": [
263
+ "AudioClassificationInput",
264
+ "AudioClassificationOutputElement",
265
+ "AudioClassificationParameters",
266
+ "AudioToAudioInput",
267
+ "AudioToAudioOutputElement",
268
+ "AutomaticSpeechRecognitionGenerationParameters",
269
+ "AutomaticSpeechRecognitionInput",
270
+ "AutomaticSpeechRecognitionOutput",
271
+ "AutomaticSpeechRecognitionOutputChunk",
272
+ "AutomaticSpeechRecognitionParameters",
273
+ "ChatCompletionInput",
274
+ "ChatCompletionInputMessage",
275
+ "ChatCompletionOutput",
276
+ "ChatCompletionOutputChoice",
277
+ "ChatCompletionOutputChoiceMessage",
278
+ "ChatCompletionStreamOutput",
279
+ "ChatCompletionStreamOutputChoice",
280
+ "ChatCompletionStreamOutputDelta",
281
+ "DepthEstimationInput",
282
+ "DepthEstimationOutput",
283
+ "DocumentQuestionAnsweringInput",
284
+ "DocumentQuestionAnsweringInputData",
285
+ "DocumentQuestionAnsweringOutputElement",
286
+ "DocumentQuestionAnsweringParameters",
287
+ "FeatureExtractionInput",
288
+ "FillMaskInput",
289
+ "FillMaskOutputElement",
290
+ "FillMaskParameters",
291
+ "ImageClassificationInput",
292
+ "ImageClassificationOutputElement",
293
+ "ImageClassificationParameters",
294
+ "ImageSegmentationInput",
295
+ "ImageSegmentationOutputElement",
296
+ "ImageSegmentationParameters",
297
+ "ImageToImageInput",
298
+ "ImageToImageOutput",
299
+ "ImageToImageParameters",
300
+ "ImageToImageTargetSize",
301
+ "ImageToTextGenerationParameters",
302
+ "ImageToTextInput",
303
+ "ImageToTextOutput",
304
+ "ImageToTextParameters",
305
+ "ObjectDetectionBoundingBox",
306
+ "ObjectDetectionInput",
307
+ "ObjectDetectionOutputElement",
308
+ "ObjectDetectionParameters",
309
+ "QuestionAnsweringInput",
310
+ "QuestionAnsweringInputData",
311
+ "QuestionAnsweringOutputElement",
312
+ "QuestionAnsweringParameters",
313
+ "SentenceSimilarityInput",
314
+ "SentenceSimilarityInputData",
315
+ "SummarizationGenerationParameters",
316
+ "SummarizationInput",
317
+ "SummarizationOutput",
318
+ "TableQuestionAnsweringInput",
319
+ "TableQuestionAnsweringInputData",
320
+ "TableQuestionAnsweringOutputElement",
321
+ "Text2TextGenerationInput",
322
+ "Text2TextGenerationOutput",
323
+ "Text2TextGenerationParameters",
324
+ "TextClassificationInput",
325
+ "TextClassificationOutputElement",
326
+ "TextClassificationParameters",
327
+ "TextGenerationInput",
328
+ "TextGenerationOutput",
329
+ "TextGenerationOutputDetails",
330
+ "TextGenerationOutputSequenceDetails",
331
+ "TextGenerationOutputToken",
332
+ "TextGenerationParameters",
333
+ "TextGenerationPrefillToken",
334
+ "TextGenerationStreamDetails",
335
+ "TextGenerationStreamOutput",
336
+ "TextToAudioGenerationParameters",
337
+ "TextToAudioInput",
338
+ "TextToAudioOutput",
339
+ "TextToAudioParameters",
340
+ "TextToImageInput",
341
+ "TextToImageOutput",
342
+ "TextToImageParameters",
343
+ "TextToImageTargetSize",
344
+ "TokenClassificationInput",
345
+ "TokenClassificationOutputElement",
346
+ "TokenClassificationParameters",
347
+ "TranslationGenerationParameters",
348
+ "TranslationInput",
349
+ "TranslationOutput",
350
+ "VideoClassificationInput",
351
+ "VideoClassificationOutputElement",
352
+ "VideoClassificationParameters",
353
+ "VisualQuestionAnsweringInput",
354
+ "VisualQuestionAnsweringInputData",
355
+ "VisualQuestionAnsweringOutputElement",
356
+ "VisualQuestionAnsweringParameters",
357
+ "ZeroShotClassificationInput",
358
+ "ZeroShotClassificationInputData",
359
+ "ZeroShotClassificationOutputElement",
360
+ "ZeroShotClassificationParameters",
361
+ "ZeroShotImageClassificationInput",
362
+ "ZeroShotImageClassificationInputData",
363
+ "ZeroShotImageClassificationOutputElement",
364
+ "ZeroShotImageClassificationParameters",
365
+ "ZeroShotObjectDetectionBoundingBox",
366
+ "ZeroShotObjectDetectionInput",
367
+ "ZeroShotObjectDetectionInputData",
368
+ "ZeroShotObjectDetectionOutputElement",
369
+ ],
370
+ "inference_api": [
371
+ "InferenceApi",
372
+ ],
373
+ "keras_mixin": [
374
+ "KerasModelHubMixin",
375
+ "from_pretrained_keras",
376
+ "push_to_hub_keras",
377
+ "save_pretrained_keras",
378
+ ],
379
+ "repocard": [
380
+ "DatasetCard",
381
+ "ModelCard",
382
+ "RepoCard",
383
+ "SpaceCard",
384
+ "metadata_eval_result",
385
+ "metadata_load",
386
+ "metadata_save",
387
+ "metadata_update",
388
+ ],
389
+ "repocard_data": [
390
+ "CardData",
391
+ "DatasetCardData",
392
+ "EvalResult",
393
+ "ModelCardData",
394
+ "SpaceCardData",
395
+ ],
396
+ "repository": [
397
+ "Repository",
398
+ ],
399
+ "serialization": [
400
+ "StateDictSplit",
401
+ "split_numpy_state_dict_into_shards",
402
+ "split_state_dict_into_shards_factory",
403
+ "split_tf_state_dict_into_shards",
404
+ "split_torch_state_dict_into_shards",
405
+ ],
406
+ "utils": [
407
+ "CacheNotFound",
408
+ "CachedFileInfo",
409
+ "CachedRepoInfo",
410
+ "CachedRevisionInfo",
411
+ "CorruptedCacheException",
412
+ "DeleteCacheStrategy",
413
+ "HFCacheInfo",
414
+ "HfFolder",
415
+ "cached_assets_path",
416
+ "configure_http_backend",
417
+ "dump_environment_info",
418
+ "get_session",
419
+ "get_token",
420
+ "logging",
421
+ "scan_cache_dir",
422
+ ],
423
+ "utils.endpoint_helpers": [
424
+ "DatasetFilter",
425
+ "ModelFilter",
426
+ ],
427
+ }
428
+
429
+
430
+ def _attach(package_name, submodules=None, submod_attrs=None):
431
+ """Attach lazily loaded submodules, functions, or other attributes.
432
+
433
+ Typically, modules import submodules and attributes as follows:
434
+
435
+ ```py
436
+ import mysubmodule
437
+ import anothersubmodule
438
+
439
+ from .foo import someattr
440
+ ```
441
+
442
+ The idea is to replace a package's `__getattr__`, `__dir__`, and
443
+ `__all__`, such that all imports work exactly the way they would
444
+ with normal imports, except that the import occurs upon first use.
445
+
446
+ The typical way to call this function, replacing the above imports, is:
447
+
448
+ ```python
449
+ __getattr__, __dir__, __all__ = lazy.attach(
450
+ __name__,
451
+ ['mysubmodule', 'anothersubmodule'],
452
+ {'foo': ['someattr']}
453
+ )
454
+ ```
455
+ This functionality requires Python 3.7 or higher.
456
+
457
+ Args:
458
+ package_name (`str`):
459
+ Typically use `__name__`.
460
+ submodules (`set`):
461
+ List of submodules to attach.
462
+ submod_attrs (`dict`):
463
+ Dictionary of submodule -> list of attributes / functions.
464
+ These attributes are imported as they are used.
465
+
466
+ Returns:
467
+ __getattr__, __dir__, __all__
468
+
469
+ """
470
+ if submod_attrs is None:
471
+ submod_attrs = {}
472
+
473
+ if submodules is None:
474
+ submodules = set()
475
+ else:
476
+ submodules = set(submodules)
477
+
478
+ attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
479
+
480
+ __all__ = list(submodules | attr_to_modules.keys())
481
+
482
+ def __getattr__(name):
483
+ if name in submodules:
484
+ return importlib.import_module(f"{package_name}.{name}")
485
+ elif name in attr_to_modules:
486
+ submod_path = f"{package_name}.{attr_to_modules[name]}"
487
+ submod = importlib.import_module(submod_path)
488
+ attr = getattr(submod, name)
489
+
490
+ # If the attribute lives in a file (module) with the same
491
+ # name as the attribute, ensure that the attribute and *not*
492
+ # the module is accessible on the package.
493
+ if name == attr_to_modules[name]:
494
+ pkg = sys.modules[package_name]
495
+ pkg.__dict__[name] = attr
496
+
497
+ return attr
498
+ else:
499
+ raise AttributeError(f"No {package_name} attribute {name}")
500
+
501
+ def __dir__():
502
+ return __all__
503
+
504
+ if os.environ.get("EAGER_IMPORT", ""):
505
+ for attr in set(attr_to_modules.keys()) | submodules:
506
+ __getattr__(attr)
507
+
508
+ return __getattr__, __dir__, list(__all__)
509
+
510
+
511
+ __getattr__, __dir__, __all__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
512
+
513
+ # WARNING: any content below this statement is generated automatically. Any manual edit
514
+ # will be lost when re-generating this file !
515
+ #
516
+ # To update the static imports, please run the following command and commit the changes.
517
+ # ```
518
+ # # Use script
519
+ # python utils/check_static_imports.py --update-file
520
+ #
521
+ # # Or run style on codebase
522
+ # make style
523
+ # ```
524
+ if TYPE_CHECKING: # pragma: no cover
525
+ from ._commit_scheduler import CommitScheduler # noqa: F401
526
+ from ._inference_endpoints import (
527
+ InferenceEndpoint, # noqa: F401
528
+ InferenceEndpointError, # noqa: F401
529
+ InferenceEndpointStatus, # noqa: F401
530
+ InferenceEndpointTimeoutError, # noqa: F401
531
+ InferenceEndpointType, # noqa: F401
532
+ )
533
+ from ._login import (
534
+ interpreter_login, # noqa: F401
535
+ login, # noqa: F401
536
+ logout, # noqa: F401
537
+ notebook_login, # noqa: F401
538
+ )
539
+ from ._multi_commits import (
540
+ MultiCommitException, # noqa: F401
541
+ plan_multi_commits, # noqa: F401
542
+ )
543
+ from ._snapshot_download import snapshot_download # noqa: F401
544
+ from ._space_api import (
545
+ SpaceHardware, # noqa: F401
546
+ SpaceRuntime, # noqa: F401
547
+ SpaceStage, # noqa: F401
548
+ SpaceStorage, # noqa: F401
549
+ SpaceVariable, # noqa: F401
550
+ )
551
+ from ._tensorboard_logger import HFSummaryWriter # noqa: F401
552
+ from ._webhooks_payload import (
553
+ WebhookPayload, # noqa: F401
554
+ WebhookPayloadComment, # noqa: F401
555
+ WebhookPayloadDiscussion, # noqa: F401
556
+ WebhookPayloadDiscussionChanges, # noqa: F401
557
+ WebhookPayloadEvent, # noqa: F401
558
+ WebhookPayloadMovedTo, # noqa: F401
559
+ WebhookPayloadRepo, # noqa: F401
560
+ WebhookPayloadUrl, # noqa: F401
561
+ WebhookPayloadWebhook, # noqa: F401
562
+ )
563
+ from ._webhooks_server import (
564
+ WebhooksServer, # noqa: F401
565
+ webhook_endpoint, # noqa: F401
566
+ )
567
+ from .community import (
568
+ Discussion, # noqa: F401
569
+ DiscussionComment, # noqa: F401
570
+ DiscussionCommit, # noqa: F401
571
+ DiscussionEvent, # noqa: F401
572
+ DiscussionStatusChange, # noqa: F401
573
+ DiscussionTitleChange, # noqa: F401
574
+ DiscussionWithDetails, # noqa: F401
575
+ )
576
+ from .constants import (
577
+ CONFIG_NAME, # noqa: F401
578
+ FLAX_WEIGHTS_NAME, # noqa: F401
579
+ HUGGINGFACE_CO_URL_HOME, # noqa: F401
580
+ HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401
581
+ PYTORCH_WEIGHTS_NAME, # noqa: F401
582
+ REPO_TYPE_DATASET, # noqa: F401
583
+ REPO_TYPE_MODEL, # noqa: F401
584
+ REPO_TYPE_SPACE, # noqa: F401
585
+ TF2_WEIGHTS_NAME, # noqa: F401
586
+ TF_WEIGHTS_NAME, # noqa: F401
587
+ )
588
+ from .fastai_utils import (
589
+ _save_pretrained_fastai, # noqa: F401
590
+ from_pretrained_fastai, # noqa: F401
591
+ push_to_hub_fastai, # noqa: F401
592
+ )
593
+ from .file_download import (
594
+ _CACHED_NO_EXIST, # noqa: F401
595
+ HfFileMetadata, # noqa: F401
596
+ cached_download, # noqa: F401
597
+ get_hf_file_metadata, # noqa: F401
598
+ hf_hub_download, # noqa: F401
599
+ hf_hub_url, # noqa: F401
600
+ try_to_load_from_cache, # noqa: F401
601
+ )
602
+ from .hf_api import (
603
+ Collection, # noqa: F401
604
+ CollectionItem, # noqa: F401
605
+ CommitInfo, # noqa: F401
606
+ CommitOperation, # noqa: F401
607
+ CommitOperationAdd, # noqa: F401
608
+ CommitOperationCopy, # noqa: F401
609
+ CommitOperationDelete, # noqa: F401
610
+ GitCommitInfo, # noqa: F401
611
+ GitRefInfo, # noqa: F401
612
+ GitRefs, # noqa: F401
613
+ HfApi, # noqa: F401
614
+ RepoUrl, # noqa: F401
615
+ User, # noqa: F401
616
+ UserLikes, # noqa: F401
617
+ accept_access_request, # noqa: F401
618
+ add_collection_item, # noqa: F401
619
+ add_space_secret, # noqa: F401
620
+ add_space_variable, # noqa: F401
621
+ cancel_access_request, # noqa: F401
622
+ change_discussion_status, # noqa: F401
623
+ comment_discussion, # noqa: F401
624
+ create_branch, # noqa: F401
625
+ create_collection, # noqa: F401
626
+ create_commit, # noqa: F401
627
+ create_commits_on_pr, # noqa: F401
628
+ create_discussion, # noqa: F401
629
+ create_inference_endpoint, # noqa: F401
630
+ create_pull_request, # noqa: F401
631
+ create_repo, # noqa: F401
632
+ create_tag, # noqa: F401
633
+ dataset_info, # noqa: F401
634
+ delete_branch, # noqa: F401
635
+ delete_collection, # noqa: F401
636
+ delete_collection_item, # noqa: F401
637
+ delete_file, # noqa: F401
638
+ delete_folder, # noqa: F401
639
+ delete_inference_endpoint, # noqa: F401
640
+ delete_repo, # noqa: F401
641
+ delete_space_secret, # noqa: F401
642
+ delete_space_storage, # noqa: F401
643
+ delete_space_variable, # noqa: F401
644
+ delete_tag, # noqa: F401
645
+ duplicate_space, # noqa: F401
646
+ edit_discussion_comment, # noqa: F401
647
+ file_exists, # noqa: F401
648
+ get_collection, # noqa: F401
649
+ get_dataset_tags, # noqa: F401
650
+ get_discussion_details, # noqa: F401
651
+ get_full_repo_name, # noqa: F401
652
+ get_inference_endpoint, # noqa: F401
653
+ get_model_tags, # noqa: F401
654
+ get_paths_info, # noqa: F401
655
+ get_repo_discussions, # noqa: F401
656
+ get_safetensors_metadata, # noqa: F401
657
+ get_space_runtime, # noqa: F401
658
+ get_space_variables, # noqa: F401
659
+ get_token_permission, # noqa: F401
660
+ grant_access, # noqa: F401
661
+ like, # noqa: F401
662
+ list_accepted_access_requests, # noqa: F401
663
+ list_collections, # noqa: F401
664
+ list_datasets, # noqa: F401
665
+ list_files_info, # noqa: F401
666
+ list_inference_endpoints, # noqa: F401
667
+ list_liked_repos, # noqa: F401
668
+ list_metrics, # noqa: F401
669
+ list_models, # noqa: F401
670
+ list_pending_access_requests, # noqa: F401
671
+ list_rejected_access_requests, # noqa: F401
672
+ list_repo_commits, # noqa: F401
673
+ list_repo_files, # noqa: F401
674
+ list_repo_likers, # noqa: F401
675
+ list_repo_refs, # noqa: F401
676
+ list_repo_tree, # noqa: F401
677
+ list_spaces, # noqa: F401
678
+ merge_pull_request, # noqa: F401
679
+ model_info, # noqa: F401
680
+ move_repo, # noqa: F401
681
+ parse_safetensors_file_metadata, # noqa: F401
682
+ pause_inference_endpoint, # noqa: F401
683
+ pause_space, # noqa: F401
684
+ preupload_lfs_files, # noqa: F401
685
+ reject_access_request, # noqa: F401
686
+ rename_discussion, # noqa: F401
687
+ repo_exists, # noqa: F401
688
+ repo_info, # noqa: F401
689
+ repo_type_and_id_from_hf_id, # noqa: F401
690
+ request_space_hardware, # noqa: F401
691
+ request_space_storage, # noqa: F401
692
+ restart_space, # noqa: F401
693
+ resume_inference_endpoint, # noqa: F401
694
+ revision_exists, # noqa: F401
695
+ run_as_future, # noqa: F401
696
+ scale_to_zero_inference_endpoint, # noqa: F401
697
+ set_space_sleep_time, # noqa: F401
698
+ space_info, # noqa: F401
699
+ super_squash_history, # noqa: F401
700
+ unlike, # noqa: F401
701
+ update_collection_item, # noqa: F401
702
+ update_collection_metadata, # noqa: F401
703
+ update_inference_endpoint, # noqa: F401
704
+ update_repo_visibility, # noqa: F401
705
+ upload_file, # noqa: F401
706
+ upload_folder, # noqa: F401
707
+ whoami, # noqa: F401
708
+ )
709
+ from .hf_file_system import (
710
+ HfFileSystem, # noqa: F401
711
+ HfFileSystemFile, # noqa: F401
712
+ HfFileSystemResolvedPath, # noqa: F401
713
+ HfFileSystemStreamFile, # noqa: F401
714
+ )
715
+ from .hub_mixin import (
716
+ ModelHubMixin, # noqa: F401
717
+ PyTorchModelHubMixin, # noqa: F401
718
+ )
719
+ from .inference._client import (
720
+ InferenceClient, # noqa: F401
721
+ InferenceTimeoutError, # noqa: F401
722
+ )
723
+ from .inference._generated._async_client import AsyncInferenceClient # noqa: F401
724
+ from .inference._generated.types import (
725
+ AudioClassificationInput, # noqa: F401
726
+ AudioClassificationOutputElement, # noqa: F401
727
+ AudioClassificationParameters, # noqa: F401
728
+ AudioToAudioInput, # noqa: F401
729
+ AudioToAudioOutputElement, # noqa: F401
730
+ AutomaticSpeechRecognitionGenerationParameters, # noqa: F401
731
+ AutomaticSpeechRecognitionInput, # noqa: F401
732
+ AutomaticSpeechRecognitionOutput, # noqa: F401
733
+ AutomaticSpeechRecognitionOutputChunk, # noqa: F401
734
+ AutomaticSpeechRecognitionParameters, # noqa: F401
735
+ ChatCompletionInput, # noqa: F401
736
+ ChatCompletionInputMessage, # noqa: F401
737
+ ChatCompletionOutput, # noqa: F401
738
+ ChatCompletionOutputChoice, # noqa: F401
739
+ ChatCompletionOutputChoiceMessage, # noqa: F401
740
+ ChatCompletionStreamOutput, # noqa: F401
741
+ ChatCompletionStreamOutputChoice, # noqa: F401
742
+ ChatCompletionStreamOutputDelta, # noqa: F401
743
+ DepthEstimationInput, # noqa: F401
744
+ DepthEstimationOutput, # noqa: F401
745
+ DocumentQuestionAnsweringInput, # noqa: F401
746
+ DocumentQuestionAnsweringInputData, # noqa: F401
747
+ DocumentQuestionAnsweringOutputElement, # noqa: F401
748
+ DocumentQuestionAnsweringParameters, # noqa: F401
749
+ FeatureExtractionInput, # noqa: F401
750
+ FillMaskInput, # noqa: F401
751
+ FillMaskOutputElement, # noqa: F401
752
+ FillMaskParameters, # noqa: F401
753
+ ImageClassificationInput, # noqa: F401
754
+ ImageClassificationOutputElement, # noqa: F401
755
+ ImageClassificationParameters, # noqa: F401
756
+ ImageSegmentationInput, # noqa: F401
757
+ ImageSegmentationOutputElement, # noqa: F401
758
+ ImageSegmentationParameters, # noqa: F401
759
+ ImageToImageInput, # noqa: F401
760
+ ImageToImageOutput, # noqa: F401
761
+ ImageToImageParameters, # noqa: F401
762
+ ImageToImageTargetSize, # noqa: F401
763
+ ImageToTextGenerationParameters, # noqa: F401
764
+ ImageToTextInput, # noqa: F401
765
+ ImageToTextOutput, # noqa: F401
766
+ ImageToTextParameters, # noqa: F401
767
+ ObjectDetectionBoundingBox, # noqa: F401
768
+ ObjectDetectionInput, # noqa: F401
769
+ ObjectDetectionOutputElement, # noqa: F401
770
+ ObjectDetectionParameters, # noqa: F401
771
+ QuestionAnsweringInput, # noqa: F401
772
+ QuestionAnsweringInputData, # noqa: F401
773
+ QuestionAnsweringOutputElement, # noqa: F401
774
+ QuestionAnsweringParameters, # noqa: F401
775
+ SentenceSimilarityInput, # noqa: F401
776
+ SentenceSimilarityInputData, # noqa: F401
777
+ SummarizationGenerationParameters, # noqa: F401
778
+ SummarizationInput, # noqa: F401
779
+ SummarizationOutput, # noqa: F401
780
+ TableQuestionAnsweringInput, # noqa: F401
781
+ TableQuestionAnsweringInputData, # noqa: F401
782
+ TableQuestionAnsweringOutputElement, # noqa: F401
783
+ Text2TextGenerationInput, # noqa: F401
784
+ Text2TextGenerationOutput, # noqa: F401
785
+ Text2TextGenerationParameters, # noqa: F401
786
+ TextClassificationInput, # noqa: F401
787
+ TextClassificationOutputElement, # noqa: F401
788
+ TextClassificationParameters, # noqa: F401
789
+ TextGenerationInput, # noqa: F401
790
+ TextGenerationOutput, # noqa: F401
791
+ TextGenerationOutputDetails, # noqa: F401
792
+ TextGenerationOutputSequenceDetails, # noqa: F401
793
+ TextGenerationOutputToken, # noqa: F401
794
+ TextGenerationParameters, # noqa: F401
795
+ TextGenerationPrefillToken, # noqa: F401
796
+ TextGenerationStreamDetails, # noqa: F401
797
+ TextGenerationStreamOutput, # noqa: F401
798
+ TextToAudioGenerationParameters, # noqa: F401
799
+ TextToAudioInput, # noqa: F401
800
+ TextToAudioOutput, # noqa: F401
801
+ TextToAudioParameters, # noqa: F401
802
+ TextToImageInput, # noqa: F401
803
+ TextToImageOutput, # noqa: F401
804
+ TextToImageParameters, # noqa: F401
805
+ TextToImageTargetSize, # noqa: F401
806
+ TokenClassificationInput, # noqa: F401
807
+ TokenClassificationOutputElement, # noqa: F401
808
+ TokenClassificationParameters, # noqa: F401
809
+ TranslationGenerationParameters, # noqa: F401
810
+ TranslationInput, # noqa: F401
811
+ TranslationOutput, # noqa: F401
812
+ VideoClassificationInput, # noqa: F401
813
+ VideoClassificationOutputElement, # noqa: F401
814
+ VideoClassificationParameters, # noqa: F401
815
+ VisualQuestionAnsweringInput, # noqa: F401
816
+ VisualQuestionAnsweringInputData, # noqa: F401
817
+ VisualQuestionAnsweringOutputElement, # noqa: F401
818
+ VisualQuestionAnsweringParameters, # noqa: F401
819
+ ZeroShotClassificationInput, # noqa: F401
820
+ ZeroShotClassificationInputData, # noqa: F401
821
+ ZeroShotClassificationOutputElement, # noqa: F401
822
+ ZeroShotClassificationParameters, # noqa: F401
823
+ ZeroShotImageClassificationInput, # noqa: F401
824
+ ZeroShotImageClassificationInputData, # noqa: F401
825
+ ZeroShotImageClassificationOutputElement, # noqa: F401
826
+ ZeroShotImageClassificationParameters, # noqa: F401
827
+ ZeroShotObjectDetectionBoundingBox, # noqa: F401
828
+ ZeroShotObjectDetectionInput, # noqa: F401
829
+ ZeroShotObjectDetectionInputData, # noqa: F401
830
+ ZeroShotObjectDetectionOutputElement, # noqa: F401
831
+ )
832
+ from .inference_api import InferenceApi # noqa: F401
833
+ from .keras_mixin import (
834
+ KerasModelHubMixin, # noqa: F401
835
+ from_pretrained_keras, # noqa: F401
836
+ push_to_hub_keras, # noqa: F401
837
+ save_pretrained_keras, # noqa: F401
838
+ )
839
+ from .repocard import (
840
+ DatasetCard, # noqa: F401
841
+ ModelCard, # noqa: F401
842
+ RepoCard, # noqa: F401
843
+ SpaceCard, # noqa: F401
844
+ metadata_eval_result, # noqa: F401
845
+ metadata_load, # noqa: F401
846
+ metadata_save, # noqa: F401
847
+ metadata_update, # noqa: F401
848
+ )
849
+ from .repocard_data import (
850
+ CardData, # noqa: F401
851
+ DatasetCardData, # noqa: F401
852
+ EvalResult, # noqa: F401
853
+ ModelCardData, # noqa: F401
854
+ SpaceCardData, # noqa: F401
855
+ )
856
+ from .repository import Repository # noqa: F401
857
+ from .serialization import (
858
+ StateDictSplit, # noqa: F401
859
+ split_numpy_state_dict_into_shards, # noqa: F401
860
+ split_state_dict_into_shards_factory, # noqa: F401
861
+ split_tf_state_dict_into_shards, # noqa: F401
862
+ split_torch_state_dict_into_shards, # noqa: F401
863
+ )
864
+ from .utils import (
865
+ CachedFileInfo, # noqa: F401
866
+ CachedRepoInfo, # noqa: F401
867
+ CachedRevisionInfo, # noqa: F401
868
+ CacheNotFound, # noqa: F401
869
+ CorruptedCacheException, # noqa: F401
870
+ DeleteCacheStrategy, # noqa: F401
871
+ HFCacheInfo, # noqa: F401
872
+ HfFolder, # noqa: F401
873
+ cached_assets_path, # noqa: F401
874
+ configure_http_backend, # noqa: F401
875
+ dump_environment_info, # noqa: F401
876
+ get_session, # noqa: F401
877
+ get_token, # noqa: F401
878
+ logging, # noqa: F401
879
+ scan_cache_dir, # noqa: F401
880
+ )
881
+ from .utils.endpoint_helpers import (
882
+ DatasetFilter, # noqa: F401
883
+ ModelFilter, # noqa: F401
884
+ )
env-llmeval/lib/python3.10/site-packages/huggingface_hub/_commit_api.py ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 huggingface_hub import get_session
19
+
20
+ from .constants import ENDPOINT, HF_HUB_ENABLE_HF_TRANSFER
21
+ from .file_download import hf_hub_url
22
+ from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info
23
+ from .utils import (
24
+ EntryNotFoundError,
25
+ chunk_iterable,
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
+ if any(part == ".git" for part in path_in_repo.split("/")):
259
+ raise ValueError(
260
+ "Invalid `path_in_repo` in CommitOperation: cannot update files under a '.git/' folder (path:"
261
+ f" '{path_in_repo}')."
262
+ )
263
+ return path_in_repo
264
+
265
+
266
+ CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
267
+
268
+
269
+ def _warn_on_overwriting_operations(operations: List[CommitOperation]) -> None:
270
+ """
271
+ Warn user when a list of operations is expected to overwrite itself in a single
272
+ commit.
273
+
274
+ Rules:
275
+ - If a filepath is updated by multiple `CommitOperationAdd` operations, a warning
276
+ message is triggered.
277
+ - If a filepath is updated at least once by a `CommitOperationAdd` and then deleted
278
+ by a `CommitOperationDelete`, a warning is triggered.
279
+ - If a `CommitOperationDelete` deletes a filepath that is then updated by a
280
+ `CommitOperationAdd`, no warning is triggered. This is usually useless (no need to
281
+ delete before upload) but can happen if a user deletes an entire folder and then
282
+ add new files to it.
283
+ """
284
+ nb_additions_per_path: Dict[str, int] = defaultdict(int)
285
+ for operation in operations:
286
+ path_in_repo = operation.path_in_repo
287
+ if isinstance(operation, CommitOperationAdd):
288
+ if nb_additions_per_path[path_in_repo] > 0:
289
+ warnings.warn(
290
+ "About to update multiple times the same file in the same commit:"
291
+ f" '{path_in_repo}'. This can cause undesired inconsistencies in"
292
+ " your repo."
293
+ )
294
+ nb_additions_per_path[path_in_repo] += 1
295
+ for parent in PurePosixPath(path_in_repo).parents:
296
+ # Also keep track of number of updated files per folder
297
+ # => warns if deleting a folder overwrite some contained files
298
+ nb_additions_per_path[str(parent)] += 1
299
+ if isinstance(operation, CommitOperationDelete):
300
+ if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0:
301
+ if operation.is_folder:
302
+ warnings.warn(
303
+ "About to delete a folder containing files that have just been"
304
+ f" updated within the same commit: '{path_in_repo}'. This can"
305
+ " cause undesired inconsistencies in your repo."
306
+ )
307
+ else:
308
+ warnings.warn(
309
+ "About to delete a file that have just been updated within the"
310
+ f" same commit: '{path_in_repo}'. This can cause undesired"
311
+ " inconsistencies in your repo."
312
+ )
313
+
314
+
315
+ @validate_hf_hub_args
316
+ def _upload_lfs_files(
317
+ *,
318
+ additions: List[CommitOperationAdd],
319
+ repo_type: str,
320
+ repo_id: str,
321
+ headers: Dict[str, str],
322
+ endpoint: Optional[str] = None,
323
+ num_threads: int = 5,
324
+ revision: Optional[str] = None,
325
+ ):
326
+ """
327
+ Uploads the content of `additions` to the Hub using the large file storage protocol.
328
+
329
+ Relevant external documentation:
330
+ - LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
331
+
332
+ Args:
333
+ additions (`List` of `CommitOperationAdd`):
334
+ The files to be uploaded
335
+ repo_type (`str`):
336
+ Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
337
+ repo_id (`str`):
338
+ A namespace (user or an organization) and a repo name separated
339
+ by a `/`.
340
+ headers (`Dict[str, str]`):
341
+ Headers to use for the request, including authorization headers and user agent.
342
+ num_threads (`int`, *optional*):
343
+ The number of concurrent threads to use when uploading. Defaults to 5.
344
+ revision (`str`, *optional*):
345
+ The git revision to upload to.
346
+
347
+ Raises: `RuntimeError` if an upload failed for any reason
348
+
349
+ Raises: `ValueError` if the server returns malformed responses
350
+
351
+ Raises: `requests.HTTPError` if the LFS batch endpoint returned an HTTP
352
+ error
353
+
354
+ """
355
+ # Step 1: retrieve upload instructions from the LFS batch endpoint.
356
+ # Upload instructions are retrieved by chunk of 256 files to avoid reaching
357
+ # the payload limit.
358
+ batch_actions: List[Dict] = []
359
+ for chunk in chunk_iterable(additions, chunk_size=256):
360
+ batch_actions_chunk, batch_errors_chunk = post_lfs_batch_info(
361
+ upload_infos=[op.upload_info for op in chunk],
362
+ repo_id=repo_id,
363
+ repo_type=repo_type,
364
+ revision=revision,
365
+ endpoint=endpoint,
366
+ headers=headers,
367
+ token=None, # already passed in 'headers'
368
+ )
369
+
370
+ # If at least 1 error, we do not retrieve information for other chunks
371
+ if batch_errors_chunk:
372
+ message = "\n".join(
373
+ [
374
+ f'Encountered error for file with OID {err.get("oid")}: `{err.get("error", {}).get("message")}'
375
+ for err in batch_errors_chunk
376
+ ]
377
+ )
378
+ raise ValueError(f"LFS batch endpoint returned errors:\n{message}")
379
+
380
+ batch_actions += batch_actions_chunk
381
+ oid2addop = {add_op.upload_info.sha256.hex(): add_op for add_op in additions}
382
+
383
+ # Step 2: ignore files that have already been uploaded
384
+ filtered_actions = []
385
+ for action in batch_actions:
386
+ if action.get("actions") is None:
387
+ logger.debug(
388
+ f"Content of file {oid2addop[action['oid']].path_in_repo} is already"
389
+ " present upstream - skipping upload."
390
+ )
391
+ else:
392
+ filtered_actions.append(action)
393
+
394
+ if len(filtered_actions) == 0:
395
+ logger.debug("No LFS files to upload.")
396
+ return
397
+
398
+ # Step 3: upload files concurrently according to these instructions
399
+ def _wrapped_lfs_upload(batch_action) -> None:
400
+ try:
401
+ operation = oid2addop[batch_action["oid"]]
402
+ lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint)
403
+ except Exception as exc:
404
+ raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
405
+
406
+ if HF_HUB_ENABLE_HF_TRANSFER:
407
+ logger.debug(f"Uploading {len(filtered_actions)} LFS files to the Hub using `hf_transfer`.")
408
+ for action in hf_tqdm(filtered_actions):
409
+ _wrapped_lfs_upload(action)
410
+ elif len(filtered_actions) == 1:
411
+ logger.debug("Uploading 1 LFS file to the Hub")
412
+ _wrapped_lfs_upload(filtered_actions[0])
413
+ else:
414
+ logger.debug(
415
+ f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently"
416
+ )
417
+ thread_map(
418
+ _wrapped_lfs_upload,
419
+ filtered_actions,
420
+ desc=f"Upload {len(filtered_actions)} LFS files",
421
+ max_workers=num_threads,
422
+ tqdm_class=hf_tqdm,
423
+ )
424
+
425
+
426
+ def _validate_preupload_info(preupload_info: dict):
427
+ files = preupload_info.get("files")
428
+ if not isinstance(files, list):
429
+ raise ValueError("preupload_info is improperly formatted")
430
+ for file_info in files:
431
+ if not (
432
+ isinstance(file_info, dict)
433
+ and isinstance(file_info.get("path"), str)
434
+ and isinstance(file_info.get("uploadMode"), str)
435
+ and (file_info["uploadMode"] in ("lfs", "regular"))
436
+ ):
437
+ raise ValueError("preupload_info is improperly formatted:")
438
+ return preupload_info
439
+
440
+
441
+ @validate_hf_hub_args
442
+ def _fetch_upload_modes(
443
+ additions: Iterable[CommitOperationAdd],
444
+ repo_type: str,
445
+ repo_id: str,
446
+ headers: Dict[str, str],
447
+ revision: str,
448
+ endpoint: Optional[str] = None,
449
+ create_pr: bool = False,
450
+ gitignore_content: Optional[str] = None,
451
+ ) -> None:
452
+ """
453
+ Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob
454
+ or as git LFS blob. Input `additions` are mutated in-place with the upload mode.
455
+
456
+ Args:
457
+ additions (`Iterable` of :class:`CommitOperationAdd`):
458
+ Iterable of :class:`CommitOperationAdd` describing the files to
459
+ upload to the Hub.
460
+ repo_type (`str`):
461
+ Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
462
+ repo_id (`str`):
463
+ A namespace (user or an organization) and a repo name separated
464
+ by a `/`.
465
+ headers (`Dict[str, str]`):
466
+ Headers to use for the request, including authorization headers and user agent.
467
+ revision (`str`):
468
+ The git revision to upload the files to. Can be any valid git revision.
469
+ gitignore_content (`str`, *optional*):
470
+ The content of the `.gitignore` file to know which files should be ignored. The order of priority
471
+ is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
472
+ in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
473
+ (if any).
474
+ Raises:
475
+ [`~utils.HfHubHTTPError`]
476
+ If the Hub API returned an error.
477
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
478
+ If the Hub API response is improperly formatted.
479
+ """
480
+ endpoint = endpoint if endpoint is not None else ENDPOINT
481
+
482
+ # Fetch upload mode (LFS or regular) chunk by chunk.
483
+ upload_modes: Dict[str, UploadMode] = {}
484
+ should_ignore_info: Dict[str, bool] = {}
485
+
486
+ for chunk in chunk_iterable(additions, 256):
487
+ payload: Dict = {
488
+ "files": [
489
+ {
490
+ "path": op.path_in_repo,
491
+ "sample": base64.b64encode(op.upload_info.sample).decode("ascii"),
492
+ "size": op.upload_info.size,
493
+ "sha": op.upload_info.sha256.hex(),
494
+ }
495
+ for op in chunk
496
+ ]
497
+ }
498
+ if gitignore_content is not None:
499
+ payload["gitIgnore"] = gitignore_content
500
+
501
+ resp = get_session().post(
502
+ f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}",
503
+ json=payload,
504
+ headers=headers,
505
+ params={"create_pr": "1"} if create_pr else None,
506
+ )
507
+ hf_raise_for_status(resp)
508
+ preupload_info = _validate_preupload_info(resp.json())
509
+ upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]})
510
+ should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]})
511
+
512
+ # Set upload mode for each addition operation
513
+ for addition in additions:
514
+ addition._upload_mode = upload_modes[addition.path_in_repo]
515
+ addition._should_ignore = should_ignore_info[addition.path_in_repo]
516
+
517
+ # Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented)
518
+ # => empty files are uploaded as "regular" to still allow users to commit them.
519
+ for addition in additions:
520
+ if addition.upload_info.size == 0:
521
+ addition._upload_mode = "regular"
522
+
523
+
524
+ @validate_hf_hub_args
525
+ def _fetch_files_to_copy(
526
+ copies: Iterable[CommitOperationCopy],
527
+ repo_type: str,
528
+ repo_id: str,
529
+ headers: Dict[str, str],
530
+ revision: str,
531
+ endpoint: Optional[str] = None,
532
+ ) -> Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]]:
533
+ """
534
+ Fetch information about the files to copy.
535
+
536
+ For LFS files, we only need their metadata (file size and sha256) while for regular files
537
+ we need to download the raw content from the Hub.
538
+
539
+ Args:
540
+ copies (`Iterable` of :class:`CommitOperationCopy`):
541
+ Iterable of :class:`CommitOperationCopy` describing the files to
542
+ copy on the Hub.
543
+ repo_type (`str`):
544
+ Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
545
+ repo_id (`str`):
546
+ A namespace (user or an organization) and a repo name separated
547
+ by a `/`.
548
+ headers (`Dict[str, str]`):
549
+ Headers to use for the request, including authorization headers and user agent.
550
+ revision (`str`):
551
+ The git revision to upload the files to. Can be any valid git revision.
552
+
553
+ Returns: `Dict[Tuple[str, Optional[str]], Union[RepoFile, bytes]]]`
554
+ Key is the file path and revision of the file to copy.
555
+ Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files).
556
+
557
+ Raises:
558
+ [`~utils.HfHubHTTPError`]
559
+ If the Hub API returned an error.
560
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
561
+ If the Hub API response is improperly formatted.
562
+ """
563
+ from .hf_api import HfApi, RepoFolder
564
+
565
+ hf_api = HfApi(endpoint=endpoint, headers=headers)
566
+ files_to_copy: Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]] = {}
567
+ for src_revision, operations in groupby(copies, key=lambda op: op.src_revision):
568
+ operations = list(operations) # type: ignore
569
+ paths = [op.src_path_in_repo for op in operations]
570
+ for offset in range(0, len(paths), FETCH_LFS_BATCH_SIZE):
571
+ src_repo_files = hf_api.get_paths_info(
572
+ repo_id=repo_id,
573
+ paths=paths[offset : offset + FETCH_LFS_BATCH_SIZE],
574
+ revision=src_revision or revision,
575
+ repo_type=repo_type,
576
+ )
577
+ for src_repo_file in src_repo_files:
578
+ if isinstance(src_repo_file, RepoFolder):
579
+ raise NotImplementedError("Copying a folder is not implemented.")
580
+ if src_repo_file.lfs:
581
+ files_to_copy[(src_repo_file.path, src_revision)] = src_repo_file
582
+ else:
583
+ # TODO: (optimization) download regular files to copy concurrently
584
+ url = hf_hub_url(
585
+ endpoint=endpoint,
586
+ repo_type=repo_type,
587
+ repo_id=repo_id,
588
+ revision=src_revision or revision,
589
+ filename=src_repo_file.path,
590
+ )
591
+ response = get_session().get(url, headers=headers)
592
+ hf_raise_for_status(response)
593
+ files_to_copy[(src_repo_file.path, src_revision)] = response.content
594
+ for operation in operations:
595
+ if (operation.src_path_in_repo, src_revision) not in files_to_copy:
596
+ raise EntryNotFoundError(
597
+ f"Cannot copy {operation.src_path_in_repo} at revision "
598
+ f"{src_revision or revision}: file is missing on repo."
599
+ )
600
+ return files_to_copy
601
+
602
+
603
+ def _prepare_commit_payload(
604
+ operations: Iterable[CommitOperation],
605
+ files_to_copy: Dict[Tuple[str, Optional[str]], Union["RepoFile", bytes]],
606
+ commit_message: str,
607
+ commit_description: Optional[str] = None,
608
+ parent_commit: Optional[str] = None,
609
+ ) -> Iterable[Dict[str, Any]]:
610
+ """
611
+ Builds the payload to POST to the `/commit` API of the Hub.
612
+
613
+ Payload is returned as an iterator so that it can be streamed as a ndjson in the
614
+ POST request.
615
+
616
+ For more information, see:
617
+ - https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
618
+ - http://ndjson.org/
619
+ """
620
+ commit_description = commit_description if commit_description is not None else ""
621
+
622
+ # 1. Send a header item with the commit metadata
623
+ header_value = {"summary": commit_message, "description": commit_description}
624
+ if parent_commit is not None:
625
+ header_value["parentCommit"] = parent_commit
626
+ yield {"key": "header", "value": header_value}
627
+
628
+ nb_ignored_files = 0
629
+
630
+ # 2. Send operations, one per line
631
+ for operation in operations:
632
+ # Skip ignored files
633
+ if isinstance(operation, CommitOperationAdd) and operation._should_ignore:
634
+ logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).")
635
+ nb_ignored_files += 1
636
+ continue
637
+
638
+ # 2.a. Case adding a regular file
639
+ if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular":
640
+ yield {
641
+ "key": "file",
642
+ "value": {
643
+ "content": operation.b64content().decode(),
644
+ "path": operation.path_in_repo,
645
+ "encoding": "base64",
646
+ },
647
+ }
648
+ # 2.b. Case adding an LFS file
649
+ elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs":
650
+ yield {
651
+ "key": "lfsFile",
652
+ "value": {
653
+ "path": operation.path_in_repo,
654
+ "algo": "sha256",
655
+ "oid": operation.upload_info.sha256.hex(),
656
+ "size": operation.upload_info.size,
657
+ },
658
+ }
659
+ # 2.c. Case deleting a file or folder
660
+ elif isinstance(operation, CommitOperationDelete):
661
+ yield {
662
+ "key": "deletedFolder" if operation.is_folder else "deletedFile",
663
+ "value": {"path": operation.path_in_repo},
664
+ }
665
+ # 2.d. Case copying a file or folder
666
+ elif isinstance(operation, CommitOperationCopy):
667
+ file_to_copy = files_to_copy[(operation.src_path_in_repo, operation.src_revision)]
668
+ if isinstance(file_to_copy, bytes):
669
+ yield {
670
+ "key": "file",
671
+ "value": {
672
+ "content": base64.b64encode(file_to_copy).decode(),
673
+ "path": operation.path_in_repo,
674
+ "encoding": "base64",
675
+ },
676
+ }
677
+ elif file_to_copy.lfs:
678
+ yield {
679
+ "key": "lfsFile",
680
+ "value": {
681
+ "path": operation.path_in_repo,
682
+ "algo": "sha256",
683
+ "oid": file_to_copy.lfs.sha256,
684
+ },
685
+ }
686
+ else:
687
+ raise ValueError(
688
+ "Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info."
689
+ )
690
+ # 2.e. Never expected to happen
691
+ else:
692
+ raise ValueError(
693
+ f"Unknown operation to commit. Operation: {operation}. Upload mode:"
694
+ f" {getattr(operation, '_upload_mode', None)}"
695
+ )
696
+
697
+ if nb_ignored_files > 0:
698
+ logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).")
env-llmeval/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 IGNORE_GIT_FOLDER_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 + IGNORE_GIT_FOLDER_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)
env-llmeval/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .inference._client import InferenceClient
8
+ from .inference._generated._async_client import AsyncInferenceClient
9
+ from .utils import logging, parse_datetime
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from .hf_api import HfApi
14
+
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+
19
+ class InferenceEndpointError(Exception):
20
+ """Generic exception when dealing with Inference Endpoints."""
21
+
22
+
23
+ class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):
24
+ """Exception for timeouts while waiting for Inference Endpoint."""
25
+
26
+
27
+ class InferenceEndpointStatus(str, Enum):
28
+ PENDING = "pending"
29
+ INITIALIZING = "initializing"
30
+ UPDATING = "updating"
31
+ UPDATE_FAILED = "updateFailed"
32
+ RUNNING = "running"
33
+ PAUSED = "paused"
34
+ FAILED = "failed"
35
+ SCALED_TO_ZERO = "scaledToZero"
36
+
37
+
38
+ class InferenceEndpointType(str, Enum):
39
+ PUBlIC = "public"
40
+ PROTECTED = "protected"
41
+ PRIVATE = "private"
42
+
43
+
44
+ @dataclass
45
+ class InferenceEndpoint:
46
+ """
47
+ Contains information about a deployed Inference Endpoint.
48
+
49
+ Args:
50
+ name (`str`):
51
+ The unique name of the Inference Endpoint.
52
+ namespace (`str`):
53
+ The namespace where the Inference Endpoint is located.
54
+ repository (`str`):
55
+ The name of the model repository deployed on this Inference Endpoint.
56
+ status ([`InferenceEndpointStatus`]):
57
+ The current status of the Inference Endpoint.
58
+ url (`str`, *optional*):
59
+ The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL.
60
+ framework (`str`):
61
+ The machine learning framework used for the model.
62
+ revision (`str`):
63
+ The specific model revision deployed on the Inference Endpoint.
64
+ task (`str`):
65
+ The task associated with the deployed model.
66
+ created_at (`datetime.datetime`):
67
+ The timestamp when the Inference Endpoint was created.
68
+ updated_at (`datetime.datetime`):
69
+ The timestamp of the last update of the Inference Endpoint.
70
+ type ([`InferenceEndpointType`]):
71
+ The type of the Inference Endpoint (public, protected, private).
72
+ raw (`Dict`):
73
+ The raw dictionary data returned from the API.
74
+ token (`str` or `bool`, *optional*):
75
+ Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the
76
+ locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server.
77
+
78
+ Example:
79
+ ```python
80
+ >>> from huggingface_hub import get_inference_endpoint
81
+ >>> endpoint = get_inference_endpoint("my-text-to-image")
82
+ >>> endpoint
83
+ InferenceEndpoint(name='my-text-to-image', ...)
84
+
85
+ # Get status
86
+ >>> endpoint.status
87
+ 'running'
88
+ >>> endpoint.url
89
+ 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
90
+
91
+ # Run inference
92
+ >>> endpoint.client.text_to_image(...)
93
+
94
+ # Pause endpoint to save $$$
95
+ >>> endpoint.pause()
96
+
97
+ # ...
98
+ # Resume and wait for deployment
99
+ >>> endpoint.resume()
100
+ >>> endpoint.wait()
101
+ >>> endpoint.client.text_to_image(...)
102
+ ```
103
+ """
104
+
105
+ # Field in __repr__
106
+ name: str = field(init=False)
107
+ namespace: str
108
+ repository: str = field(init=False)
109
+ status: InferenceEndpointStatus = field(init=False)
110
+ url: Optional[str] = field(init=False)
111
+
112
+ # Other fields
113
+ framework: str = field(repr=False, init=False)
114
+ revision: str = field(repr=False, init=False)
115
+ task: str = field(repr=False, init=False)
116
+ created_at: datetime = field(repr=False, init=False)
117
+ updated_at: datetime = field(repr=False, init=False)
118
+ type: InferenceEndpointType = field(repr=False, init=False)
119
+
120
+ # Raw dict from the API
121
+ raw: Dict = field(repr=False)
122
+
123
+ # Internal fields
124
+ _token: Union[str, bool, None] = field(repr=False, compare=False)
125
+ _api: "HfApi" = field(repr=False, compare=False)
126
+
127
+ @classmethod
128
+ def from_raw(
129
+ cls, raw: Dict, namespace: str, token: Union[str, bool, None] = None, api: Optional["HfApi"] = None
130
+ ) -> "InferenceEndpoint":
131
+ """Initialize object from raw dictionary."""
132
+ if api is None:
133
+ from .hf_api import HfApi
134
+
135
+ api = HfApi()
136
+ if token is None:
137
+ token = api.token
138
+
139
+ # All other fields are populated in __post_init__
140
+ return cls(raw=raw, namespace=namespace, _token=token, _api=api)
141
+
142
+ def __post_init__(self) -> None:
143
+ """Populate fields from raw dictionary."""
144
+ self._populate_from_raw()
145
+
146
+ @property
147
+ def client(self) -> InferenceClient:
148
+ """Returns a client to make predictions on this Inference Endpoint.
149
+
150
+ Returns:
151
+ [`InferenceClient`]: an inference client pointing to the deployed endpoint.
152
+
153
+ Raises:
154
+ [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
155
+ """
156
+ if self.url is None:
157
+ raise InferenceEndpointError(
158
+ "Cannot create a client for this Inference Endpoint as it is not yet deployed. "
159
+ "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
160
+ )
161
+ return InferenceClient(model=self.url, token=self._token)
162
+
163
+ @property
164
+ def async_client(self) -> AsyncInferenceClient:
165
+ """Returns a client to make predictions on this Inference Endpoint.
166
+
167
+ Returns:
168
+ [`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint.
169
+
170
+ Raises:
171
+ [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
172
+ """
173
+ if self.url is None:
174
+ raise InferenceEndpointError(
175
+ "Cannot create a client for this Inference Endpoint as it is not yet deployed. "
176
+ "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
177
+ )
178
+ return AsyncInferenceClient(model=self.url, token=self._token)
179
+
180
+ def wait(self, timeout: Optional[int] = None, refresh_every: int = 5) -> "InferenceEndpoint":
181
+ """Wait for the Inference Endpoint to be deployed.
182
+
183
+ Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout`
184
+ seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest
185
+ data.
186
+
187
+ Args:
188
+ timeout (`int`, *optional*):
189
+ The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait
190
+ indefinitely.
191
+ refresh_every (`int`, *optional*):
192
+ The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s.
193
+
194
+ Returns:
195
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
196
+
197
+ Raises:
198
+ [`InferenceEndpointError`]
199
+ If the Inference Endpoint ended up in a failed state.
200
+ [`InferenceEndpointTimeoutError`]
201
+ If the Inference Endpoint is not deployed after `timeout` seconds.
202
+ """
203
+ if self.url is not None: # Means the endpoint is deployed
204
+ logger.info("Inference Endpoint is ready to be used.")
205
+ return self
206
+
207
+ if timeout is not None and timeout < 0:
208
+ raise ValueError("`timeout` cannot be negative.")
209
+ if refresh_every <= 0:
210
+ raise ValueError("`refresh_every` must be positive.")
211
+
212
+ start = time.time()
213
+ while True:
214
+ self.fetch()
215
+ if self.url is not None: # Means the endpoint is deployed
216
+ logger.info("Inference Endpoint is ready to be used.")
217
+ return self
218
+ if self.status == InferenceEndpointStatus.FAILED:
219
+ raise InferenceEndpointError(
220
+ f"Inference Endpoint {self.name} failed to deploy. Please check the logs for more information."
221
+ )
222
+ if timeout is not None:
223
+ if time.time() - start > timeout:
224
+ raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.")
225
+ logger.info(f"Inference Endpoint is not deployed yet ({self.status}). Waiting {refresh_every}s...")
226
+ time.sleep(refresh_every)
227
+
228
+ def fetch(self) -> "InferenceEndpoint":
229
+ """Fetch latest information about the Inference Endpoint.
230
+
231
+ Returns:
232
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
233
+ """
234
+ obj = self._api.get_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
235
+ self.raw = obj.raw
236
+ self._populate_from_raw()
237
+ return self
238
+
239
+ def update(
240
+ self,
241
+ *,
242
+ # Compute update
243
+ accelerator: Optional[str] = None,
244
+ instance_size: Optional[str] = None,
245
+ instance_type: Optional[str] = None,
246
+ min_replica: Optional[int] = None,
247
+ max_replica: Optional[int] = None,
248
+ # Model update
249
+ repository: Optional[str] = None,
250
+ framework: Optional[str] = None,
251
+ revision: Optional[str] = None,
252
+ task: Optional[str] = None,
253
+ ) -> "InferenceEndpoint":
254
+ """Update the Inference Endpoint.
255
+
256
+ This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
257
+ optional but at least one must be provided.
258
+
259
+ This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the
260
+ latest data from the server.
261
+
262
+ Args:
263
+ accelerator (`str`, *optional*):
264
+ The hardware accelerator to be used for inference (e.g. `"cpu"`).
265
+ instance_size (`str`, *optional*):
266
+ The size or type of the instance to be used for hosting the model (e.g. `"large"`).
267
+ instance_type (`str`, *optional*):
268
+ The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`).
269
+ min_replica (`int`, *optional*):
270
+ The minimum number of replicas (instances) to keep running for the Inference Endpoint.
271
+ max_replica (`int`, *optional*):
272
+ The maximum number of replicas (instances) to scale to for the Inference Endpoint.
273
+
274
+ repository (`str`, *optional*):
275
+ The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
276
+ framework (`str`, *optional*):
277
+ The machine learning framework used for the model (e.g. `"custom"`).
278
+ revision (`str`, *optional*):
279
+ The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
280
+ task (`str`, *optional*):
281
+ The task on which to deploy the model (e.g. `"text-classification"`).
282
+
283
+ Returns:
284
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
285
+ """
286
+ # Make API call
287
+ obj = self._api.update_inference_endpoint(
288
+ name=self.name,
289
+ namespace=self.namespace,
290
+ accelerator=accelerator,
291
+ instance_size=instance_size,
292
+ instance_type=instance_type,
293
+ min_replica=min_replica,
294
+ max_replica=max_replica,
295
+ repository=repository,
296
+ framework=framework,
297
+ revision=revision,
298
+ task=task,
299
+ token=self._token, # type: ignore [arg-type]
300
+ )
301
+
302
+ # Mutate current object
303
+ self.raw = obj.raw
304
+ self._populate_from_raw()
305
+ return self
306
+
307
+ def pause(self) -> "InferenceEndpoint":
308
+ """Pause the Inference Endpoint.
309
+
310
+ A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`].
311
+ This is different than scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which
312
+ would be automatically restarted when a request is made to it.
313
+
314
+ This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the
315
+ latest data from the server.
316
+
317
+ Returns:
318
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
319
+ """
320
+ obj = self._api.pause_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
321
+ self.raw = obj.raw
322
+ self._populate_from_raw()
323
+ return self
324
+
325
+ def resume(self) -> "InferenceEndpoint":
326
+ """Resume the Inference Endpoint.
327
+
328
+ This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the
329
+ latest data from the server.
330
+
331
+ Returns:
332
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
333
+ """
334
+ obj = self._api.resume_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
335
+ self.raw = obj.raw
336
+ self._populate_from_raw()
337
+ return self
338
+
339
+ def scale_to_zero(self) -> "InferenceEndpoint":
340
+ """Scale Inference Endpoint to zero.
341
+
342
+ An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
343
+ cold start delay. This is different than pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which
344
+ would require a manual resume with [`InferenceEndpoint.resume`].
345
+
346
+ This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the
347
+ latest data from the server.
348
+
349
+ Returns:
350
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
351
+ """
352
+ obj = self._api.scale_to_zero_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
353
+ self.raw = obj.raw
354
+ self._populate_from_raw()
355
+ return self
356
+
357
+ def delete(self) -> None:
358
+ """Delete the Inference Endpoint.
359
+
360
+ This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
361
+ to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`].
362
+
363
+ This is an alias for [`HfApi.delete_inference_endpoint`].
364
+ """
365
+ self._api.delete_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
366
+
367
+ def _populate_from_raw(self) -> None:
368
+ """Populate fields from raw dictionary.
369
+
370
+ Called in __post_init__ + each time the Inference Endpoint is updated.
371
+ """
372
+ # Repr fields
373
+ self.name = self.raw["name"]
374
+ self.repository = self.raw["model"]["repository"]
375
+ self.status = self.raw["status"]["state"]
376
+ self.url = self.raw["status"].get("url")
377
+
378
+ # Other fields
379
+ self.framework = self.raw["model"]["framework"]
380
+ self.revision = self.raw["model"]["revision"]
381
+ self.task = self.raw["model"]["task"]
382
+ self.created_at = parse_datetime(self.raw["status"]["createdAt"])
383
+ self.updated_at = parse_datetime(self.raw["status"]["updatedAt"])
384
+ self.type = self.raw["type"]
env-llmeval/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
+ token: Optional[str],
277
+ repo_type: Optional[str],
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)}
env-llmeval/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
43
+ library_name: Optional[str] = None,
44
+ library_version: Optional[str] = None,
45
+ user_agent: Optional[Union[Dict, str]] = None,
46
+ proxies: Optional[Dict] = None,
47
+ etag_timeout: float = DEFAULT_ETAG_TIMEOUT,
48
+ resume_download: bool = False,
49
+ force_download: bool = False,
50
+ token: Optional[Union[bool, str]] = None,
51
+ local_files_only: bool = False,
52
+ allow_patterns: Optional[Union[List[str], str]] = None,
53
+ ignore_patterns: Optional[Union[List[str], str]] = None,
54
+ max_workers: int = 8,
55
+ tqdm_class: Optional[base_tqdm] = None,
56
+ headers: Optional[Dict[str, str]] = None,
57
+ endpoint: Optional[str] = None,
58
+ ) -> str:
59
+ """Download repo files.
60
+
61
+ Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
62
+ a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
63
+ to keep their actual filename relative to that folder. You can also filter which files to download using
64
+ `allow_patterns` and `ignore_patterns`.
65
+
66
+ If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure
67
+ how you want to move those files:
68
+ - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob
69
+ files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal
70
+ is to be able to manually edit and save small files without corrupting the cache while saving disk space for
71
+ binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD`
72
+ environment variable.
73
+ - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`.
74
+ This is optimal in term of disk usage but files must not be manually edited.
75
+ - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the
76
+ local dir. This means disk usage is not optimized.
77
+ - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the
78
+ files are downloaded and directly placed under `local_dir`. This means if you need to download them again later,
79
+ they will be re-downloaded entirely.
80
+
81
+ An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
82
+ configured. It is also not possible to filter which files to download when cloning a repository using git.
83
+
84
+ Args:
85
+ repo_id (`str`):
86
+ A user or an organization name and a repo name separated by a `/`.
87
+ repo_type (`str`, *optional*):
88
+ Set to `"dataset"` or `"space"` if downloading from a dataset or space,
89
+ `None` or `"model"` if downloading from a model. Default is `None`.
90
+ revision (`str`, *optional*):
91
+ An optional Git revision id which can be a branch name, a tag, or a
92
+ commit hash.
93
+ cache_dir (`str`, `Path`, *optional*):
94
+ Path to the folder where cached files are stored.
95
+ local_dir (`str` or `Path`, *optional*):
96
+ If provided, the downloaded files will be placed under this directory, either as symlinks (default) or
97
+ regular files (see description for more details).
98
+ local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`):
99
+ To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either
100
+ duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be
101
+ created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if
102
+ already exists) or downloaded from the Hub and not cached. See description for more details.
103
+ library_name (`str`, *optional*):
104
+ The name of the library to which the object corresponds.
105
+ library_version (`str`, *optional*):
106
+ The version of the library.
107
+ user_agent (`str`, `dict`, *optional*):
108
+ The user-agent info in the form of a dictionary or a string.
109
+ proxies (`dict`, *optional*):
110
+ Dictionary mapping protocol to the URL of the proxy passed to
111
+ `requests.request`.
112
+ etag_timeout (`float`, *optional*, defaults to `10`):
113
+ When fetching ETag, how many seconds to wait for the server to send
114
+ data before giving up which is passed to `requests.request`.
115
+ resume_download (`bool`, *optional*, defaults to `False):
116
+ If `True`, resume a previously interrupted download.
117
+ force_download (`bool`, *optional*, defaults to `False`):
118
+ Whether the file should be downloaded even if it already exists in the local cache.
119
+ token (`str`, `bool`, *optional*):
120
+ A token to be used for the download.
121
+ - If `True`, the token is read from the HuggingFace config
122
+ folder.
123
+ - If a string, it's used as the authentication token.
124
+ headers (`dict`, *optional*):
125
+ Additional headers to include in the request. Those headers take precedence over the others.
126
+ local_files_only (`bool`, *optional*, defaults to `False`):
127
+ If `True`, avoid downloading the file and return the path to the
128
+ local cached file if it exists.
129
+ allow_patterns (`List[str]` or `str`, *optional*):
130
+ If provided, only files matching at least one pattern are downloaded.
131
+ ignore_patterns (`List[str]` or `str`, *optional*):
132
+ If provided, files matching any of the patterns are not downloaded.
133
+ max_workers (`int`, *optional*):
134
+ Number of concurrent threads to download files (1 thread = 1 file download).
135
+ Defaults to 8.
136
+ tqdm_class (`tqdm`, *optional*):
137
+ If provided, overwrites the default behavior for the progress bar. Passed
138
+ argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
139
+ Note that the `tqdm_class` is not passed to each individual download.
140
+ Defaults to the custom HF progress bar that can be disabled by setting
141
+ `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
142
+
143
+ Returns:
144
+ Local folder path (string) of repo snapshot
145
+
146
+ <Tip>
147
+
148
+ Raises the following errors:
149
+
150
+ - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
151
+ if `token=True` and the token cannot be found.
152
+ - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
153
+ ETag cannot be determined.
154
+ - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
155
+ if some parameter value is invalid
156
+
157
+ </Tip>
158
+ """
159
+ if cache_dir is None:
160
+ cache_dir = HF_HUB_CACHE
161
+ if revision is None:
162
+ revision = DEFAULT_REVISION
163
+ if isinstance(cache_dir, Path):
164
+ cache_dir = str(cache_dir)
165
+
166
+ if repo_type is None:
167
+ repo_type = "model"
168
+ if repo_type not in REPO_TYPES:
169
+ raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(REPO_TYPES)}")
170
+
171
+ storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
172
+
173
+ repo_info: Union[ModelInfo, DatasetInfo, SpaceInfo, None] = None
174
+ api_call_error: Optional[Exception] = None
175
+ if not local_files_only:
176
+ # try/except logic to handle different errors => taken from `hf_hub_download`
177
+ try:
178
+ # if we have internet connection we want to list files to download
179
+ api = HfApi(
180
+ library_name=library_name,
181
+ library_version=library_version,
182
+ user_agent=user_agent,
183
+ endpoint=endpoint,
184
+ headers=headers,
185
+ )
186
+ repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision, token=token)
187
+ except (requests.exceptions.SSLError, requests.exceptions.ProxyError):
188
+ # Actually raise for those subclasses of ConnectionError
189
+ raise
190
+ except (
191
+ requests.exceptions.ConnectionError,
192
+ requests.exceptions.Timeout,
193
+ OfflineModeIsEnabled,
194
+ ) as error:
195
+ # Internet connection is down
196
+ # => will try to use local files only
197
+ api_call_error = error
198
+ pass
199
+ except RevisionNotFoundError:
200
+ # The repo was found but the revision doesn't exist on the Hub (never existed or got deleted)
201
+ raise
202
+ except requests.HTTPError as error:
203
+ # Multiple reasons for an http error:
204
+ # - Repository is private and invalid/missing token sent
205
+ # - Repository is gated and invalid/missing token sent
206
+ # - Hub is down (error 500 or 504)
207
+ # => let's switch to 'local_files_only=True' to check if the files are already cached.
208
+ # (if it's not the case, the error will be re-raised)
209
+ api_call_error = error
210
+ pass
211
+
212
+ # At this stage, if `repo_info` is None it means either:
213
+ # - internet connection is down
214
+ # - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True)
215
+ # - repo is private/gated and invalid/missing token sent
216
+ # - Hub is down
217
+ # => let's look if we can find the appropriate folder in the cache:
218
+ # - if the specified revision is a commit hash, look inside "snapshots".
219
+ # - f the specified revision is a branch or tag, look inside "refs".
220
+ if repo_info is None:
221
+ # Try to get which commit hash corresponds to the specified revision
222
+ commit_hash = None
223
+ if REGEX_COMMIT_HASH.match(revision):
224
+ commit_hash = revision
225
+ else:
226
+ ref_path = os.path.join(storage_folder, "refs", revision)
227
+ if os.path.exists(ref_path):
228
+ # retrieve commit_hash from refs file
229
+ with open(ref_path) as f:
230
+ commit_hash = f.read()
231
+
232
+ # Try to locate snapshot folder for this commit hash
233
+ if commit_hash is not None:
234
+ snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
235
+ if os.path.exists(snapshot_folder):
236
+ # Snapshot folder exists => let's return it
237
+ # (but we can't check if all the files are actually there)
238
+ return snapshot_folder
239
+
240
+ # If we couldn't find the appropriate folder on disk, raise an error.
241
+ if local_files_only:
242
+ raise LocalEntryNotFoundError(
243
+ "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
244
+ "outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass "
245
+ "'local_files_only=False' as input."
246
+ )
247
+ elif isinstance(api_call_error, OfflineModeIsEnabled):
248
+ raise LocalEntryNotFoundError(
249
+ "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
250
+ "outgoing traffic has been disabled. To enable repo look-ups and downloads online, set "
251
+ "'HF_HUB_OFFLINE=0' as environment variable."
252
+ ) from api_call_error
253
+ elif isinstance(api_call_error, RepositoryNotFoundError) or isinstance(api_call_error, GatedRepoError):
254
+ # Repo not found => let's raise the actual error
255
+ raise api_call_error
256
+ else:
257
+ # Otherwise: most likely a connection issue or Hub downtime => let's warn the user
258
+ raise LocalEntryNotFoundError(
259
+ "An error happened while trying to locate the files on the Hub and we cannot find the appropriate"
260
+ " snapshot folder for the specified revision on the local disk. Please check your internet connection"
261
+ " and try again."
262
+ ) from api_call_error
263
+
264
+ # At this stage, internet connection is up and running
265
+ # => let's download the files!
266
+ assert repo_info.sha is not None, "Repo info returned from server must have a revision sha."
267
+ assert repo_info.siblings is not None, "Repo info returned from server must have a siblings list."
268
+ filtered_repo_files = list(
269
+ filter_repo_objects(
270
+ items=[f.rfilename for f in repo_info.siblings],
271
+ allow_patterns=allow_patterns,
272
+ ignore_patterns=ignore_patterns,
273
+ )
274
+ )
275
+ commit_hash = repo_info.sha
276
+ snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
277
+ # if passed revision is not identical to commit_hash
278
+ # then revision has to be a branch name or tag name.
279
+ # In that case store a ref.
280
+ if revision != commit_hash:
281
+ ref_path = os.path.join(storage_folder, "refs", revision)
282
+ os.makedirs(os.path.dirname(ref_path), exist_ok=True)
283
+ with open(ref_path, "w") as f:
284
+ f.write(commit_hash)
285
+
286
+ # we pass the commit_hash to hf_hub_download
287
+ # so no network call happens if we already
288
+ # have the file locally.
289
+ def _inner_hf_hub_download(repo_file: str):
290
+ return hf_hub_download(
291
+ repo_id,
292
+ filename=repo_file,
293
+ repo_type=repo_type,
294
+ revision=commit_hash,
295
+ endpoint=endpoint,
296
+ cache_dir=cache_dir,
297
+ local_dir=local_dir,
298
+ local_dir_use_symlinks=local_dir_use_symlinks,
299
+ library_name=library_name,
300
+ library_version=library_version,
301
+ user_agent=user_agent,
302
+ proxies=proxies,
303
+ etag_timeout=etag_timeout,
304
+ resume_download=resume_download,
305
+ force_download=force_download,
306
+ token=token,
307
+ headers=headers,
308
+ )
309
+
310
+ if HF_HUB_ENABLE_HF_TRANSFER:
311
+ # when using hf_transfer we don't want extra parallelism
312
+ # from the one hf_transfer provides
313
+ for file in filtered_repo_files:
314
+ _inner_hf_hub_download(file)
315
+ else:
316
+ thread_map(
317
+ _inner_hf_hub_download,
318
+ filtered_repo_files,
319
+ desc=f"Fetching {len(filtered_repo_files)} files",
320
+ max_workers=max_workers,
321
+ # User can use its own tqdm class or the default one from `huggingface_hub.utils`
322
+ tqdm_class=tqdm_class or hf_tqdm,
323
+ )
324
+
325
+ if local_dir is not None:
326
+ return str(os.path.realpath(local_dir))
327
+ return snapshot_folder
env-llmeval/lib/python3.10/site-packages/huggingface_hub/_space_api.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-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
+ from dataclasses import dataclass
16
+ from datetime import datetime
17
+ from enum import Enum
18
+ from typing import Dict, Optional
19
+
20
+ from huggingface_hub.utils import parse_datetime
21
+
22
+
23
+ class SpaceStage(str, Enum):
24
+ """
25
+ Enumeration of possible stage of a Space on the Hub.
26
+
27
+ Value can be compared to a string:
28
+ ```py
29
+ assert SpaceStage.BUILDING == "BUILDING"
30
+ ```
31
+
32
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url).
33
+ """
34
+
35
+ # Copied from moon-landing > server > repo_types > SpaceInfo.ts (private repo)
36
+ NO_APP_FILE = "NO_APP_FILE"
37
+ CONFIG_ERROR = "CONFIG_ERROR"
38
+ BUILDING = "BUILDING"
39
+ BUILD_ERROR = "BUILD_ERROR"
40
+ RUNNING = "RUNNING"
41
+ RUNNING_BUILDING = "RUNNING_BUILDING"
42
+ RUNTIME_ERROR = "RUNTIME_ERROR"
43
+ DELETING = "DELETING"
44
+ STOPPED = "STOPPED"
45
+ PAUSED = "PAUSED"
46
+
47
+
48
+ class SpaceHardware(str, Enum):
49
+ """
50
+ Enumeration of hardwares available to run your Space on the Hub.
51
+
52
+ Value can be compared to a string:
53
+ ```py
54
+ assert SpaceHardware.CPU_BASIC == "cpu-basic"
55
+ ```
56
+
57
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L73 (private url).
58
+ """
59
+
60
+ CPU_BASIC = "cpu-basic"
61
+ CPU_UPGRADE = "cpu-upgrade"
62
+ T4_SMALL = "t4-small"
63
+ T4_MEDIUM = "t4-medium"
64
+ ZERO_A10G = "zero-a10g"
65
+ A10G_SMALL = "a10g-small"
66
+ A10G_LARGE = "a10g-large"
67
+ A10G_LARGEX2 = "a10g-largex2"
68
+ A10G_LARGEX4 = "a10g-largex4"
69
+ A100_LARGE = "a100-large"
70
+
71
+
72
+ class SpaceStorage(str, Enum):
73
+ """
74
+ Enumeration of persistent storage available for your Space on the Hub.
75
+
76
+ Value can be compared to a string:
77
+ ```py
78
+ assert SpaceStorage.SMALL == "small"
79
+ ```
80
+
81
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url).
82
+ """
83
+
84
+ SMALL = "small"
85
+ MEDIUM = "medium"
86
+ LARGE = "large"
87
+
88
+
89
+ @dataclass
90
+ class SpaceRuntime:
91
+ """
92
+ Contains information about the current runtime of a Space.
93
+
94
+ Args:
95
+ stage (`str`):
96
+ Current stage of the space. Example: RUNNING.
97
+ hardware (`str` or `None`):
98
+ Current hardware of the space. Example: "cpu-basic". Can be `None` if Space
99
+ is `BUILDING` for the first time.
100
+ requested_hardware (`str` or `None`):
101
+ Requested hardware. Can be different than `hardware` especially if the request
102
+ has just been made. Example: "t4-medium". Can be `None` if no hardware has
103
+ been requested yet.
104
+ sleep_time (`int` or `None`):
105
+ Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the
106
+ Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48
107
+ hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
108
+ raw (`dict`):
109
+ Raw response from the server. Contains more information about the Space
110
+ runtime like number of replicas, number of cpu, memory size,...
111
+ """
112
+
113
+ stage: SpaceStage
114
+ hardware: Optional[SpaceHardware]
115
+ requested_hardware: Optional[SpaceHardware]
116
+ sleep_time: Optional[int]
117
+ storage: Optional[SpaceStorage]
118
+ raw: Dict
119
+
120
+ def __init__(self, data: Dict) -> None:
121
+ self.stage = data["stage"]
122
+ self.hardware = data.get("hardware", {}).get("current")
123
+ self.requested_hardware = data.get("hardware", {}).get("requested")
124
+ self.sleep_time = data.get("gcTimeout")
125
+ self.storage = data.get("storage")
126
+ self.raw = data
127
+
128
+
129
+ @dataclass
130
+ class SpaceVariable:
131
+ """
132
+ Contains information about the current variables of a Space.
133
+
134
+ Args:
135
+ key (`str`):
136
+ Variable key. Example: `"MODEL_REPO_ID"`
137
+ value (`str`):
138
+ Variable value. Example: `"the_model_repo_id"`.
139
+ description (`str` or None):
140
+ Description of the variable. Example: `"Model Repo ID of the implemented model"`.
141
+ updatedAt (`datetime` or None):
142
+ datetime of the last update of the variable (if the variable has been updated at least once).
143
+ """
144
+
145
+ key: str
146
+ value: str
147
+ description: Optional[str]
148
+ updated_at: Optional[datetime]
149
+
150
+ def __init__(self, key: str, values: Dict) -> None:
151
+ self.key = key
152
+ self.value = values["value"]
153
+ self.description = values.get("description")
154
+ updated_at = values.get("updatedAt")
155
+ self.updated_at = parse_datetime(updated_at) if updated_at is not None else None
env-llmeval/lib/python3.10/site-packages/huggingface_hub/_webhooks_payload.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 data structures to parse the webhooks payload."""
16
+
17
+ from typing import List, Literal, Optional
18
+
19
+ from pydantic import BaseModel
20
+
21
+
22
+ # This is an adaptation of the ReportV3 interface implemented in moon-landing. V0, V1 and V2 have been ignored as they
23
+ # are not in used anymore. To keep in sync when format is updated in
24
+ # https://github.com/huggingface/moon-landing/blob/main/server/lib/HFWebhooks.ts (internal link).
25
+
26
+
27
+ WebhookEvent_T = Literal[
28
+ "create",
29
+ "delete",
30
+ "move",
31
+ "update",
32
+ ]
33
+ RepoChangeEvent_T = Literal[
34
+ "add",
35
+ "move",
36
+ "remove",
37
+ "update",
38
+ ]
39
+ RepoType_T = Literal[
40
+ "dataset",
41
+ "model",
42
+ "space",
43
+ ]
44
+ DiscussionStatus_T = Literal[
45
+ "closed",
46
+ "draft",
47
+ "open",
48
+ "merged",
49
+ ]
50
+ SupportedWebhookVersion = Literal[3]
51
+
52
+
53
+ class ObjectId(BaseModel):
54
+ id: str
55
+
56
+
57
+ class WebhookPayloadUrl(BaseModel):
58
+ web: str
59
+ api: Optional[str] = None
60
+
61
+
62
+ class WebhookPayloadMovedTo(BaseModel):
63
+ name: str
64
+ owner: ObjectId
65
+
66
+
67
+ class WebhookPayloadWebhook(ObjectId):
68
+ version: SupportedWebhookVersion
69
+
70
+
71
+ class WebhookPayloadEvent(BaseModel):
72
+ action: WebhookEvent_T
73
+ scope: str
74
+
75
+
76
+ class WebhookPayloadDiscussionChanges(BaseModel):
77
+ base: str
78
+ mergeCommitId: Optional[str] = None
79
+
80
+
81
+ class WebhookPayloadComment(ObjectId):
82
+ author: ObjectId
83
+ hidden: bool
84
+ content: Optional[str] = None
85
+ url: WebhookPayloadUrl
86
+
87
+
88
+ class WebhookPayloadDiscussion(ObjectId):
89
+ num: int
90
+ author: ObjectId
91
+ url: WebhookPayloadUrl
92
+ title: str
93
+ isPullRequest: bool
94
+ status: DiscussionStatus_T
95
+ changes: Optional[WebhookPayloadDiscussionChanges] = None
96
+ pinned: Optional[bool] = None
97
+
98
+
99
+ class WebhookPayloadRepo(ObjectId):
100
+ owner: ObjectId
101
+ head_sha: Optional[str] = None
102
+ name: str
103
+ private: bool
104
+ subdomain: Optional[str] = None
105
+ tags: Optional[List[str]] = None
106
+ type: Literal["dataset", "model", "space"]
107
+ url: WebhookPayloadUrl
108
+
109
+
110
+ class WebhookPayload(BaseModel):
111
+ event: WebhookPayloadEvent
112
+ repo: WebhookPayloadRepo
113
+ discussion: Optional[WebhookPayloadDiscussion] = None
114
+ comment: Optional[WebhookPayloadComment] = None
115
+ webhook: WebhookPayloadWebhook
116
+ movedTo: Optional[WebhookPayloadMovedTo] = None
env-llmeval/lib/python3.10/site-packages/huggingface_hub/community.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data structures to interact with Discussions and Pull Requests on the Hub.
3
+
4
+ See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions)
5
+ for more information on Pull Requests, Discussions, and the community tab.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+ from datetime import datetime
10
+ from typing import List, Literal, Optional, Union
11
+
12
+ from .constants import REPO_TYPE_MODEL
13
+ from .utils import parse_datetime
14
+
15
+
16
+ DiscussionStatus = Literal["open", "closed", "merged", "draft"]
17
+
18
+
19
+ @dataclass
20
+ class Discussion:
21
+ """
22
+ A Discussion or Pull Request on the Hub.
23
+
24
+ This dataclass is not intended to be instantiated directly.
25
+
26
+ Attributes:
27
+ title (`str`):
28
+ The title of the Discussion / Pull Request
29
+ status (`str`):
30
+ The status of the Discussion / Pull Request.
31
+ It must be one of:
32
+ * `"open"`
33
+ * `"closed"`
34
+ * `"merged"` (only for Pull Requests )
35
+ * `"draft"` (only for Pull Requests )
36
+ num (`int`):
37
+ The number of the Discussion / Pull Request.
38
+ repo_id (`str`):
39
+ The id (`"{namespace}/{repo_name}"`) of the repo on which
40
+ the Discussion / Pull Request was open.
41
+ repo_type (`str`):
42
+ The type of the repo on which the Discussion / Pull Request was open.
43
+ Possible values are: `"model"`, `"dataset"`, `"space"`.
44
+ author (`str`):
45
+ The username of the Discussion / Pull Request author.
46
+ Can be `"deleted"` if the user has been deleted since.
47
+ is_pull_request (`bool`):
48
+ Whether or not this is a Pull Request.
49
+ created_at (`datetime`):
50
+ The `datetime` of creation of the Discussion / Pull Request.
51
+ endpoint (`str`):
52
+ Endpoint of the Hub. Default is https://huggingface.co.
53
+ git_reference (`str`, *optional*):
54
+ (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
55
+ url (`str`):
56
+ (property) URL of the discussion on the Hub.
57
+ """
58
+
59
+ title: str
60
+ status: DiscussionStatus
61
+ num: int
62
+ repo_id: str
63
+ repo_type: str
64
+ author: str
65
+ is_pull_request: bool
66
+ created_at: datetime
67
+ endpoint: str
68
+
69
+ @property
70
+ def git_reference(self) -> Optional[str]:
71
+ """
72
+ If this is a Pull Request , returns the git reference to which changes can be pushed.
73
+ Returns `None` otherwise.
74
+ """
75
+ if self.is_pull_request:
76
+ return f"refs/pr/{self.num}"
77
+ return None
78
+
79
+ @property
80
+ def url(self) -> str:
81
+ """Returns the URL of the discussion on the Hub."""
82
+ if self.repo_type is None or self.repo_type == REPO_TYPE_MODEL:
83
+ return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}"
84
+ return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}"
85
+
86
+
87
+ @dataclass
88
+ class DiscussionWithDetails(Discussion):
89
+ """
90
+ Subclass of [`Discussion`].
91
+
92
+ Attributes:
93
+ title (`str`):
94
+ The title of the Discussion / Pull Request
95
+ status (`str`):
96
+ The status of the Discussion / Pull Request.
97
+ It can be one of:
98
+ * `"open"`
99
+ * `"closed"`
100
+ * `"merged"` (only for Pull Requests )
101
+ * `"draft"` (only for Pull Requests )
102
+ num (`int`):
103
+ The number of the Discussion / Pull Request.
104
+ repo_id (`str`):
105
+ The id (`"{namespace}/{repo_name}"`) of the repo on which
106
+ the Discussion / Pull Request was open.
107
+ repo_type (`str`):
108
+ The type of the repo on which the Discussion / Pull Request was open.
109
+ Possible values are: `"model"`, `"dataset"`, `"space"`.
110
+ author (`str`):
111
+ The username of the Discussion / Pull Request author.
112
+ Can be `"deleted"` if the user has been deleted since.
113
+ is_pull_request (`bool`):
114
+ Whether or not this is a Pull Request.
115
+ created_at (`datetime`):
116
+ The `datetime` of creation of the Discussion / Pull Request.
117
+ events (`list` of [`DiscussionEvent`])
118
+ The list of [`DiscussionEvents`] in this Discussion or Pull Request.
119
+ conflicting_files (`Union[List[str], bool, None]`, *optional*):
120
+ A list of conflicting files if this is a Pull Request.
121
+ `None` if `self.is_pull_request` is `False`.
122
+ `True` if there are conflicting files but the list can't be retrieved.
123
+ target_branch (`str`, *optional*):
124
+ The branch into which changes are to be merged if this is a
125
+ Pull Request . `None` if `self.is_pull_request` is `False`.
126
+ merge_commit_oid (`str`, *optional*):
127
+ If this is a merged Pull Request , this is set to the OID / SHA of
128
+ the merge commit, `None` otherwise.
129
+ diff (`str`, *optional*):
130
+ The git diff if this is a Pull Request , `None` otherwise.
131
+ endpoint (`str`):
132
+ Endpoint of the Hub. Default is https://huggingface.co.
133
+ git_reference (`str`, *optional*):
134
+ (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
135
+ url (`str`):
136
+ (property) URL of the discussion on the Hub.
137
+ """
138
+
139
+ events: List["DiscussionEvent"]
140
+ conflicting_files: Union[List[str], bool, None]
141
+ target_branch: Optional[str]
142
+ merge_commit_oid: Optional[str]
143
+ diff: Optional[str]
144
+
145
+
146
+ @dataclass
147
+ class DiscussionEvent:
148
+ """
149
+ An event in a Discussion or Pull Request.
150
+
151
+ Use concrete classes:
152
+ * [`DiscussionComment`]
153
+ * [`DiscussionStatusChange`]
154
+ * [`DiscussionCommit`]
155
+ * [`DiscussionTitleChange`]
156
+
157
+ Attributes:
158
+ id (`str`):
159
+ The ID of the event. An hexadecimal string.
160
+ type (`str`):
161
+ The type of the event.
162
+ created_at (`datetime`):
163
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
164
+ object holding the creation timestamp for the event.
165
+ author (`str`):
166
+ The username of the Discussion / Pull Request author.
167
+ Can be `"deleted"` if the user has been deleted since.
168
+ """
169
+
170
+ id: str
171
+ type: str
172
+ created_at: datetime
173
+ author: str
174
+
175
+ _event: dict
176
+ """Stores the original event data, in case we need to access it later."""
177
+
178
+
179
+ @dataclass
180
+ class DiscussionComment(DiscussionEvent):
181
+ """A comment in a Discussion / Pull Request.
182
+
183
+ Subclass of [`DiscussionEvent`].
184
+
185
+
186
+ Attributes:
187
+ id (`str`):
188
+ The ID of the event. An hexadecimal string.
189
+ type (`str`):
190
+ The type of the event.
191
+ created_at (`datetime`):
192
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
193
+ object holding the creation timestamp for the event.
194
+ author (`str`):
195
+ The username of the Discussion / Pull Request author.
196
+ Can be `"deleted"` if the user has been deleted since.
197
+ content (`str`):
198
+ The raw markdown content of the comment. Mentions, links and images are not rendered.
199
+ edited (`bool`):
200
+ Whether or not this comment has been edited.
201
+ hidden (`bool`):
202
+ Whether or not this comment has been hidden.
203
+ """
204
+
205
+ content: str
206
+ edited: bool
207
+ hidden: bool
208
+
209
+ @property
210
+ def rendered(self) -> str:
211
+ """The rendered comment, as a HTML string"""
212
+ return self._event["data"]["latest"]["html"]
213
+
214
+ @property
215
+ def last_edited_at(self) -> datetime:
216
+ """The last edit time, as a `datetime` object."""
217
+ return parse_datetime(self._event["data"]["latest"]["updatedAt"])
218
+
219
+ @property
220
+ def last_edited_by(self) -> str:
221
+ """The last edit time, as a `datetime` object."""
222
+ return self._event["data"]["latest"].get("author", {}).get("name", "deleted")
223
+
224
+ @property
225
+ def edit_history(self) -> List[dict]:
226
+ """The edit history of the comment"""
227
+ return self._event["data"]["history"]
228
+
229
+ @property
230
+ def number_of_edits(self) -> int:
231
+ return len(self.edit_history)
232
+
233
+
234
+ @dataclass
235
+ class DiscussionStatusChange(DiscussionEvent):
236
+ """A change of status in a Discussion / Pull Request.
237
+
238
+ Subclass of [`DiscussionEvent`].
239
+
240
+ Attributes:
241
+ id (`str`):
242
+ The ID of the event. An hexadecimal string.
243
+ type (`str`):
244
+ The type of the event.
245
+ created_at (`datetime`):
246
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
247
+ object holding the creation timestamp for the event.
248
+ author (`str`):
249
+ The username of the Discussion / Pull Request author.
250
+ Can be `"deleted"` if the user has been deleted since.
251
+ new_status (`str`):
252
+ The status of the Discussion / Pull Request after the change.
253
+ It can be one of:
254
+ * `"open"`
255
+ * `"closed"`
256
+ * `"merged"` (only for Pull Requests )
257
+ """
258
+
259
+ new_status: str
260
+
261
+
262
+ @dataclass
263
+ class DiscussionCommit(DiscussionEvent):
264
+ """A commit in a Pull Request.
265
+
266
+ Subclass of [`DiscussionEvent`].
267
+
268
+ Attributes:
269
+ id (`str`):
270
+ The ID of the event. An hexadecimal string.
271
+ type (`str`):
272
+ The type of the event.
273
+ created_at (`datetime`):
274
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
275
+ object holding the creation timestamp for the event.
276
+ author (`str`):
277
+ The username of the Discussion / Pull Request author.
278
+ Can be `"deleted"` if the user has been deleted since.
279
+ summary (`str`):
280
+ The summary of the commit.
281
+ oid (`str`):
282
+ The OID / SHA of the commit, as a hexadecimal string.
283
+ """
284
+
285
+ summary: str
286
+ oid: str
287
+
288
+
289
+ @dataclass
290
+ class DiscussionTitleChange(DiscussionEvent):
291
+ """A rename event in a Discussion / Pull Request.
292
+
293
+ Subclass of [`DiscussionEvent`].
294
+
295
+ Attributes:
296
+ id (`str`):
297
+ The ID of the event. An hexadecimal string.
298
+ type (`str`):
299
+ The type of the event.
300
+ created_at (`datetime`):
301
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
302
+ object holding the creation timestamp for the event.
303
+ author (`str`):
304
+ The username of the Discussion / Pull Request author.
305
+ Can be `"deleted"` if the user has been deleted since.
306
+ old_title (`str`):
307
+ The previous title for the Discussion / Pull Request.
308
+ new_title (`str`):
309
+ The new title.
310
+ """
311
+
312
+ old_title: str
313
+ new_title: str
314
+
315
+
316
+ def deserialize_event(event: dict) -> DiscussionEvent:
317
+ """Instantiates a [`DiscussionEvent`] from a dict"""
318
+ event_id: str = event["id"]
319
+ event_type: str = event["type"]
320
+ created_at = parse_datetime(event["createdAt"])
321
+
322
+ common_args = dict(
323
+ id=event_id,
324
+ type=event_type,
325
+ created_at=created_at,
326
+ author=event.get("author", {}).get("name", "deleted"),
327
+ _event=event,
328
+ )
329
+
330
+ if event_type == "comment":
331
+ return DiscussionComment(
332
+ **common_args,
333
+ edited=event["data"]["edited"],
334
+ hidden=event["data"]["hidden"],
335
+ content=event["data"]["latest"]["raw"],
336
+ )
337
+ if event_type == "status-change":
338
+ return DiscussionStatusChange(
339
+ **common_args,
340
+ new_status=event["data"]["status"],
341
+ )
342
+ if event_type == "commit":
343
+ return DiscussionCommit(
344
+ **common_args,
345
+ summary=event["data"]["subject"],
346
+ oid=event["data"]["oid"],
347
+ )
348
+ if event_type == "title-change":
349
+ return DiscussionTitleChange(
350
+ **common_args,
351
+ old_title=event["data"]["from"],
352
+ new_title=event["data"]["to"],
353
+ )
354
+
355
+ return DiscussionEvent(**common_args)
env-llmeval/lib/python3.10/site-packages/huggingface_hub/constants.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import typing
4
+ from typing import Literal, Optional, Tuple
5
+
6
+
7
+ # Possible values for env variables
8
+
9
+
10
+ ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
11
+ ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
12
+
13
+
14
+ def _is_true(value: Optional[str]) -> bool:
15
+ if value is None:
16
+ return False
17
+ return value.upper() in ENV_VARS_TRUE_VALUES
18
+
19
+
20
+ def _as_int(value: Optional[str]) -> Optional[int]:
21
+ if value is None:
22
+ return None
23
+ return int(value)
24
+
25
+
26
+ # Constants for file downloads
27
+
28
+ PYTORCH_WEIGHTS_NAME = "pytorch_model.bin"
29
+ TF2_WEIGHTS_NAME = "tf_model.h5"
30
+ TF_WEIGHTS_NAME = "model.ckpt"
31
+ FLAX_WEIGHTS_NAME = "flax_model.msgpack"
32
+ CONFIG_NAME = "config.json"
33
+ REPOCARD_NAME = "README.md"
34
+ DEFAULT_ETAG_TIMEOUT = 10
35
+ DEFAULT_DOWNLOAD_TIMEOUT = 10
36
+ DEFAULT_REQUEST_TIMEOUT = 10
37
+ DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024
38
+ HF_TRANSFER_CONCURRENCY = 100
39
+
40
+ # Constants for safetensors repos
41
+
42
+ SAFETENSORS_SINGLE_FILE = "model.safetensors"
43
+ SAFETENSORS_INDEX_FILE = "model.safetensors.index.json"
44
+ SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000
45
+
46
+ # Git-related constants
47
+
48
+ DEFAULT_REVISION = "main"
49
+ REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}")
50
+
51
+ HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/"
52
+
53
+ _staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING"))
54
+
55
+ _HF_DEFAULT_ENDPOINT = "https://huggingface.co"
56
+ _HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"
57
+ ENDPOINT = os.getenv("HF_ENDPOINT") or (_HF_DEFAULT_STAGING_ENDPOINT if _staging_mode else _HF_DEFAULT_ENDPOINT)
58
+
59
+ HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
60
+ HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"
61
+ HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"
62
+ HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"
63
+
64
+ INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co")
65
+
66
+ # See https://huggingface.co/docs/inference-endpoints/index
67
+ INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2"
68
+
69
+
70
+ REPO_ID_SEPARATOR = "--"
71
+ # ^ this substring is not allowed in repo_ids on hf.co
72
+ # and is the canonical one we use for serialization of repo ids elsewhere.
73
+
74
+
75
+ REPO_TYPE_DATASET = "dataset"
76
+ REPO_TYPE_SPACE = "space"
77
+ REPO_TYPE_MODEL = "model"
78
+ REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE]
79
+ SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"]
80
+
81
+ REPO_TYPES_URL_PREFIXES = {
82
+ REPO_TYPE_DATASET: "datasets/",
83
+ REPO_TYPE_SPACE: "spaces/",
84
+ }
85
+ REPO_TYPES_MAPPING = {
86
+ "datasets": REPO_TYPE_DATASET,
87
+ "spaces": REPO_TYPE_SPACE,
88
+ "models": REPO_TYPE_MODEL,
89
+ }
90
+
91
+ DiscussionTypeFilter = Literal["all", "discussion", "pull_request"]
92
+ DISCUSSION_TYPES: Tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter)
93
+ DiscussionStatusFilter = Literal["all", "open", "closed"]
94
+ DISCUSSION_STATUS: Tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter)
95
+
96
+ # default cache
97
+ default_home = os.path.join(os.path.expanduser("~"), ".cache")
98
+ HF_HOME = os.path.expanduser(
99
+ os.getenv(
100
+ "HF_HOME",
101
+ os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"),
102
+ )
103
+ )
104
+ hf_cache_home = HF_HOME # for backward compatibility. TODO: remove this in 1.0.0
105
+
106
+ default_cache_path = os.path.join(HF_HOME, "hub")
107
+ default_assets_cache_path = os.path.join(HF_HOME, "assets")
108
+
109
+ # Legacy env variables
110
+ HUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path)
111
+ HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path)
112
+
113
+ # New env variables
114
+ HF_HUB_CACHE = os.getenv("HF_HUB_CACHE", HUGGINGFACE_HUB_CACHE)
115
+ HF_ASSETS_CACHE = os.getenv("HF_ASSETS_CACHE", HUGGINGFACE_ASSETS_CACHE)
116
+
117
+ HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE"))
118
+
119
+ # Opt-out from telemetry requests
120
+ HF_HUB_DISABLE_TELEMETRY = (
121
+ _is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable
122
+ or _is_true(os.environ.get("DISABLE_TELEMETRY"))
123
+ or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/
124
+ )
125
+
126
+ # In the past, token was stored in a hardcoded location
127
+ # `_OLD_HF_TOKEN_PATH` is deprecated and will be removed "at some point".
128
+ # See https://github.com/huggingface/huggingface_hub/issues/1232
129
+ _OLD_HF_TOKEN_PATH = os.path.expanduser("~/.huggingface/token")
130
+ HF_TOKEN_PATH = os.path.join(HF_HOME, "token")
131
+
132
+
133
+ if _staging_mode:
134
+ # In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens
135
+ _staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging")
136
+ HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub")
137
+ _OLD_HF_TOKEN_PATH = os.path.join(_staging_home, "_old_token")
138
+ HF_TOKEN_PATH = os.path.join(_staging_home, "token")
139
+
140
+ # Here, `True` will disable progress bars globally without possibility of enabling it
141
+ # programmatically. `False` will enable them without possibility of disabling them.
142
+ # If environment variable is not set (None), then the user is free to enable/disable
143
+ # them programmatically.
144
+ # TL;DR: env variable has priority over code
145
+ __HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")
146
+ HF_HUB_DISABLE_PROGRESS_BARS: Optional[bool] = (
147
+ _is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None
148
+ )
149
+
150
+ # Disable warning on machines that do not support symlinks (e.g. Windows non-developer)
151
+ HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING"))
152
+
153
+ # Disable warning when using experimental features
154
+ HF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING"))
155
+
156
+ # Disable sending the cached token by default is all HTTP requests to the Hub
157
+ HF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN"))
158
+
159
+ # Enable fast-download using external dependency "hf_transfer"
160
+ # See:
161
+ # - https://pypi.org/project/hf-transfer/
162
+ # - https://github.com/huggingface/hf_transfer (private)
163
+ HF_HUB_ENABLE_HF_TRANSFER: bool = _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER"))
164
+
165
+
166
+ # Used if download to `local_dir` and `local_dir_use_symlinks="auto"`
167
+ # Files smaller than 5MB are copy-pasted while bigger files are symlinked. The idea is to save disk-usage by symlinking
168
+ # huge files (i.e. LFS files most of the time) while allowing small files to be manually edited in local folder.
169
+ HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD: int = (
170
+ _as_int(os.environ.get("HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD")) or 5 * 1024 * 1024
171
+ )
172
+
173
+ # Used to override the etag timeout on a system level
174
+ HF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT
175
+
176
+ # Used to override the get request timeout on a system level
177
+ HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT
178
+
179
+ # List frameworks that are handled by the InferenceAPI service. Useful to scan endpoints and check which models are
180
+ # deployed and running. Since 95% of the models are using the top 4 frameworks listed below, we scan only those by
181
+ # default. We still keep the full list of supported frameworks in case we want to scan all of them.
182
+ MAIN_INFERENCE_API_FRAMEWORKS = [
183
+ "diffusers",
184
+ "sentence-transformers",
185
+ "text-generation-inference",
186
+ "transformers",
187
+ ]
188
+
189
+ ALL_INFERENCE_API_FRAMEWORKS = MAIN_INFERENCE_API_FRAMEWORKS + [
190
+ "adapter-transformers",
191
+ "allennlp",
192
+ "asteroid",
193
+ "bertopic",
194
+ "doctr",
195
+ "espnet",
196
+ "fairseq",
197
+ "fastai",
198
+ "fasttext",
199
+ "flair",
200
+ "generic",
201
+ "k2",
202
+ "keras",
203
+ "mindspore",
204
+ "nemo",
205
+ "open_clip",
206
+ "paddlenlp",
207
+ "peft",
208
+ "pyannote-audio",
209
+ "sklearn",
210
+ "spacy",
211
+ "span-marker",
212
+ "speechbrain",
213
+ "stanza",
214
+ "timm",
215
+ ]
env-llmeval/lib/python3.10/site-packages/huggingface_hub/errors.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains all custom errors."""
2
+
3
+ from requests import HTTPError
4
+
5
+
6
+ # INFERENCE CLIENT ERRORS
7
+
8
+
9
+ class InferenceTimeoutError(HTTPError, TimeoutError):
10
+ """Error raised when a model is unavailable or the request times out."""
11
+
12
+
13
+ # TEXT GENERATION ERRORS
14
+
15
+
16
+ class TextGenerationError(HTTPError):
17
+ """Generic error raised if text-generation went wrong."""
18
+
19
+
20
+ # Text Generation Inference Errors
21
+ class ValidationError(TextGenerationError):
22
+ """Server-side validation error."""
23
+
24
+
25
+ class GenerationError(TextGenerationError):
26
+ pass
27
+
28
+
29
+ class OverloadedError(TextGenerationError):
30
+ pass
31
+
32
+
33
+ class IncompleteGenerationError(TextGenerationError):
34
+ pass
35
+
36
+
37
+ class UnknownError(TextGenerationError):
38
+ pass
env-llmeval/lib/python3.10/site-packages/huggingface_hub/file_download.py ADDED
@@ -0,0 +1,1770 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import errno
3
+ import fnmatch
4
+ import inspect
5
+ import io
6
+ import json
7
+ import os
8
+ import re
9
+ import shutil
10
+ import stat
11
+ import tempfile
12
+ import time
13
+ import uuid
14
+ import warnings
15
+ from contextlib import contextmanager
16
+ from dataclasses import dataclass
17
+ from functools import partial
18
+ from pathlib import Path
19
+ from typing import Any, BinaryIO, Dict, Generator, Literal, Optional, Tuple, Union
20
+ from urllib.parse import quote, urlparse
21
+
22
+ import requests
23
+
24
+ from huggingface_hub import constants
25
+
26
+ from . import __version__ # noqa: F401 # for backward compatibility
27
+ from .constants import (
28
+ DEFAULT_ETAG_TIMEOUT,
29
+ DEFAULT_REQUEST_TIMEOUT,
30
+ DEFAULT_REVISION,
31
+ DOWNLOAD_CHUNK_SIZE,
32
+ ENDPOINT,
33
+ HF_HUB_CACHE,
34
+ HF_HUB_DISABLE_SYMLINKS_WARNING,
35
+ HF_HUB_DOWNLOAD_TIMEOUT,
36
+ HF_HUB_ENABLE_HF_TRANSFER,
37
+ HF_HUB_ETAG_TIMEOUT,
38
+ HF_TRANSFER_CONCURRENCY,
39
+ HUGGINGFACE_CO_URL_TEMPLATE,
40
+ HUGGINGFACE_HEADER_X_LINKED_ETAG,
41
+ HUGGINGFACE_HEADER_X_LINKED_SIZE,
42
+ HUGGINGFACE_HEADER_X_REPO_COMMIT,
43
+ HUGGINGFACE_HUB_CACHE, # noqa: F401 # for backward compatibility
44
+ REPO_ID_SEPARATOR,
45
+ REPO_TYPES,
46
+ REPO_TYPES_URL_PREFIXES,
47
+ )
48
+ from .utils import (
49
+ EntryNotFoundError,
50
+ FileMetadataError,
51
+ GatedRepoError,
52
+ LocalEntryNotFoundError,
53
+ OfflineModeIsEnabled,
54
+ RepositoryNotFoundError,
55
+ RevisionNotFoundError,
56
+ SoftTemporaryDirectory,
57
+ WeakFileLock,
58
+ build_hf_headers,
59
+ get_fastai_version, # noqa: F401 # for backward compatibility
60
+ get_fastcore_version, # noqa: F401 # for backward compatibility
61
+ get_graphviz_version, # noqa: F401 # for backward compatibility
62
+ get_jinja_version, # noqa: F401 # for backward compatibility
63
+ get_pydot_version, # noqa: F401 # for backward compatibility
64
+ get_session,
65
+ get_tf_version, # noqa: F401 # for backward compatibility
66
+ get_torch_version, # noqa: F401 # for backward compatibility
67
+ hf_raise_for_status,
68
+ is_fastai_available, # noqa: F401 # for backward compatibility
69
+ is_fastcore_available, # noqa: F401 # for backward compatibility
70
+ is_graphviz_available, # noqa: F401 # for backward compatibility
71
+ is_jinja_available, # noqa: F401 # for backward compatibility
72
+ is_pydot_available, # noqa: F401 # for backward compatibility
73
+ is_tf_available, # noqa: F401 # for backward compatibility
74
+ is_torch_available, # noqa: F401 # for backward compatibility
75
+ logging,
76
+ reset_sessions,
77
+ tqdm,
78
+ validate_hf_hub_args,
79
+ )
80
+ from .utils._runtime import _PY_VERSION # noqa: F401 # for backward compatibility
81
+ from .utils._typing import HTTP_METHOD_T
82
+ from .utils.insecure_hashlib import sha256
83
+
84
+
85
+ logger = logging.get_logger(__name__)
86
+
87
+ # Regex to get filename from a "Content-Disposition" header for CDN-served files
88
+ HEADER_FILENAME_PATTERN = re.compile(r'filename="(?P<filename>.*?)";')
89
+
90
+
91
+ _are_symlinks_supported_in_dir: Dict[str, bool] = {}
92
+
93
+
94
+ def are_symlinks_supported(cache_dir: Union[str, Path, None] = None) -> bool:
95
+ """Return whether the symlinks are supported on the machine.
96
+
97
+ Since symlinks support can change depending on the mounted disk, we need to check
98
+ on the precise cache folder. By default, the default HF cache directory is checked.
99
+
100
+ Args:
101
+ cache_dir (`str`, `Path`, *optional*):
102
+ Path to the folder where cached files are stored.
103
+
104
+ Returns: [bool] Whether symlinks are supported in the directory.
105
+ """
106
+ # Defaults to HF cache
107
+ if cache_dir is None:
108
+ cache_dir = HF_HUB_CACHE
109
+ cache_dir = str(Path(cache_dir).expanduser().resolve()) # make it unique
110
+
111
+ # Check symlink compatibility only once (per cache directory) at first time use
112
+ if cache_dir not in _are_symlinks_supported_in_dir:
113
+ _are_symlinks_supported_in_dir[cache_dir] = True
114
+
115
+ os.makedirs(cache_dir, exist_ok=True)
116
+ with SoftTemporaryDirectory(dir=cache_dir) as tmpdir:
117
+ src_path = Path(tmpdir) / "dummy_file_src"
118
+ src_path.touch()
119
+ dst_path = Path(tmpdir) / "dummy_file_dst"
120
+
121
+ # Relative source path as in `_create_symlink``
122
+ relative_src = os.path.relpath(src_path, start=os.path.dirname(dst_path))
123
+ try:
124
+ os.symlink(relative_src, dst_path)
125
+ except OSError:
126
+ # Likely running on Windows
127
+ _are_symlinks_supported_in_dir[cache_dir] = False
128
+
129
+ if not HF_HUB_DISABLE_SYMLINKS_WARNING:
130
+ message = (
131
+ "`huggingface_hub` cache-system uses symlinks by default to"
132
+ " efficiently store duplicated files but your machine does not"
133
+ f" support them in {cache_dir}. Caching files will still work"
134
+ " but in a degraded version that might require more space on"
135
+ " your disk. This warning can be disabled by setting the"
136
+ " `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For"
137
+ " more details, see"
138
+ " https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations."
139
+ )
140
+ if os.name == "nt":
141
+ message += (
142
+ "\nTo support symlinks on Windows, you either need to"
143
+ " activate Developer Mode or to run Python as an"
144
+ " administrator. In order to see activate developer mode,"
145
+ " see this article:"
146
+ " https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development"
147
+ )
148
+ warnings.warn(message)
149
+
150
+ return _are_symlinks_supported_in_dir[cache_dir]
151
+
152
+
153
+ # Return value when trying to load a file from cache but the file does not exist in the distant repo.
154
+ _CACHED_NO_EXIST = object()
155
+ _CACHED_NO_EXIST_T = Any
156
+ REGEX_COMMIT_HASH = re.compile(r"^[0-9a-f]{40}$")
157
+
158
+
159
+ @dataclass(frozen=True)
160
+ class HfFileMetadata:
161
+ """Data structure containing information about a file versioned on the Hub.
162
+
163
+ Returned by [`get_hf_file_metadata`] based on a URL.
164
+
165
+ Args:
166
+ commit_hash (`str`, *optional*):
167
+ The commit_hash related to the file.
168
+ etag (`str`, *optional*):
169
+ Etag of the file on the server.
170
+ location (`str`):
171
+ Location where to download the file. Can be a Hub url or not (CDN).
172
+ size (`size`):
173
+ Size of the file. In case of an LFS file, contains the size of the actual
174
+ LFS file, not the pointer.
175
+ """
176
+
177
+ commit_hash: Optional[str]
178
+ etag: Optional[str]
179
+ location: str
180
+ size: Optional[int]
181
+
182
+
183
+ @validate_hf_hub_args
184
+ def hf_hub_url(
185
+ repo_id: str,
186
+ filename: str,
187
+ *,
188
+ subfolder: Optional[str] = None,
189
+ repo_type: Optional[str] = None,
190
+ revision: Optional[str] = None,
191
+ endpoint: Optional[str] = None,
192
+ ) -> str:
193
+ """Construct the URL of a file from the given information.
194
+
195
+ The resolved address can either be a huggingface.co-hosted url, or a link to
196
+ Cloudfront (a Content Delivery Network, or CDN) for large files which are
197
+ more than a few MBs.
198
+
199
+ Args:
200
+ repo_id (`str`):
201
+ A namespace (user or an organization) name and a repo name separated
202
+ by a `/`.
203
+ filename (`str`):
204
+ The name of the file in the repo.
205
+ subfolder (`str`, *optional*):
206
+ An optional value corresponding to a folder inside the repo.
207
+ repo_type (`str`, *optional*):
208
+ Set to `"dataset"` or `"space"` if downloading from a dataset or space,
209
+ `None` or `"model"` if downloading from a model. Default is `None`.
210
+ revision (`str`, *optional*):
211
+ An optional Git revision id which can be a branch name, a tag, or a
212
+ commit hash.
213
+
214
+ Example:
215
+
216
+ ```python
217
+ >>> from huggingface_hub import hf_hub_url
218
+
219
+ >>> hf_hub_url(
220
+ ... repo_id="julien-c/EsperBERTo-small", filename="pytorch_model.bin"
221
+ ... )
222
+ 'https://huggingface.co/julien-c/EsperBERTo-small/resolve/main/pytorch_model.bin'
223
+ ```
224
+
225
+ <Tip>
226
+
227
+ Notes:
228
+
229
+ Cloudfront is replicated over the globe so downloads are way faster for
230
+ the end user (and it also lowers our bandwidth costs).
231
+
232
+ Cloudfront aggressively caches files by default (default TTL is 24
233
+ hours), however this is not an issue here because we implement a
234
+ git-based versioning system on huggingface.co, which means that we store
235
+ the files on S3/Cloudfront in a content-addressable way (i.e., the file
236
+ name is its hash). Using content-addressable filenames means cache can't
237
+ ever be stale.
238
+
239
+ In terms of client-side caching from this library, we base our caching
240
+ on the objects' entity tag (`ETag`), which is an identifier of a
241
+ specific version of a resource [1]_. An object's ETag is: its git-sha1
242
+ if stored in git, or its sha256 if stored in git-lfs.
243
+
244
+ </Tip>
245
+
246
+ References:
247
+
248
+ - [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
249
+ """
250
+ if subfolder == "":
251
+ subfolder = None
252
+ if subfolder is not None:
253
+ filename = f"{subfolder}/{filename}"
254
+
255
+ if repo_type not in REPO_TYPES:
256
+ raise ValueError("Invalid repo type")
257
+
258
+ if repo_type in REPO_TYPES_URL_PREFIXES:
259
+ repo_id = REPO_TYPES_URL_PREFIXES[repo_type] + repo_id
260
+
261
+ if revision is None:
262
+ revision = DEFAULT_REVISION
263
+ url = HUGGINGFACE_CO_URL_TEMPLATE.format(
264
+ repo_id=repo_id, revision=quote(revision, safe=""), filename=quote(filename)
265
+ )
266
+ # Update endpoint if provided
267
+ if endpoint is not None and url.startswith(ENDPOINT):
268
+ url = endpoint + url[len(ENDPOINT) :]
269
+ return url
270
+
271
+
272
+ def url_to_filename(url: str, etag: Optional[str] = None) -> str:
273
+ """Generate a local filename from a url.
274
+
275
+ Convert `url` into a hashed filename in a reproducible way. If `etag` is
276
+ specified, append its hash to the url's, delimited by a period. If the url
277
+ ends with .h5 (Keras HDF5 weights) adds '.h5' to the name so that TF 2.0 can
278
+ identify it as a HDF5 file (see
279
+ https://github.com/tensorflow/tensorflow/blob/00fad90125b18b80fe054de1055770cfb8fe4ba3/tensorflow/python/keras/engine/network.py#L1380)
280
+
281
+ Args:
282
+ url (`str`):
283
+ The address to the file.
284
+ etag (`str`, *optional*):
285
+ The ETag of the file.
286
+
287
+ Returns:
288
+ The generated filename.
289
+ """
290
+ url_bytes = url.encode("utf-8")
291
+ filename = sha256(url_bytes).hexdigest()
292
+
293
+ if etag:
294
+ etag_bytes = etag.encode("utf-8")
295
+ filename += "." + sha256(etag_bytes).hexdigest()
296
+
297
+ if url.endswith(".h5"):
298
+ filename += ".h5"
299
+
300
+ return filename
301
+
302
+
303
+ def filename_to_url(
304
+ filename,
305
+ cache_dir: Optional[str] = None,
306
+ legacy_cache_layout: bool = False,
307
+ ) -> Tuple[str, str]:
308
+ """
309
+ Return the url and etag (which may be `None`) stored for `filename`. Raise
310
+ `EnvironmentError` if `filename` or its stored metadata do not exist.
311
+
312
+ Args:
313
+ filename (`str`):
314
+ The name of the file
315
+ cache_dir (`str`, *optional*):
316
+ The cache directory to use instead of the default one.
317
+ legacy_cache_layout (`bool`, *optional*, defaults to `False`):
318
+ If `True`, uses the legacy file cache layout i.e. just call `hf_hub_url`
319
+ then `cached_download`. This is deprecated as the new cache layout is
320
+ more powerful.
321
+ """
322
+ if not legacy_cache_layout:
323
+ warnings.warn(
324
+ "`filename_to_url` uses the legacy way cache file layout",
325
+ FutureWarning,
326
+ )
327
+
328
+ if cache_dir is None:
329
+ cache_dir = HF_HUB_CACHE
330
+ if isinstance(cache_dir, Path):
331
+ cache_dir = str(cache_dir)
332
+
333
+ cache_path = os.path.join(cache_dir, filename)
334
+ if not os.path.exists(cache_path):
335
+ raise EnvironmentError(f"file {cache_path} not found")
336
+
337
+ meta_path = cache_path + ".json"
338
+ if not os.path.exists(meta_path):
339
+ raise EnvironmentError(f"file {meta_path} not found")
340
+
341
+ with open(meta_path, encoding="utf-8") as meta_file:
342
+ metadata = json.load(meta_file)
343
+ url = metadata["url"]
344
+ etag = metadata["etag"]
345
+
346
+ return url, etag
347
+
348
+
349
+ def _request_wrapper(
350
+ method: HTTP_METHOD_T, url: str, *, follow_relative_redirects: bool = False, **params
351
+ ) -> requests.Response:
352
+ """Wrapper around requests methods to follow relative redirects if `follow_relative_redirects=True` even when
353
+ `allow_redirection=False`.
354
+
355
+ Args:
356
+ method (`str`):
357
+ HTTP method, such as 'GET' or 'HEAD'.
358
+ url (`str`):
359
+ The URL of the resource to fetch.
360
+ follow_relative_redirects (`bool`, *optional*, defaults to `False`)
361
+ If True, relative redirection (redirection to the same site) will be resolved even when `allow_redirection`
362
+ kwarg is set to False. Useful when we want to follow a redirection to a renamed repository without
363
+ following redirection to a CDN.
364
+ **params (`dict`, *optional*):
365
+ Params to pass to `requests.request`.
366
+ """
367
+ # Recursively follow relative redirects
368
+ if follow_relative_redirects:
369
+ response = _request_wrapper(
370
+ method=method,
371
+ url=url,
372
+ follow_relative_redirects=False,
373
+ **params,
374
+ )
375
+
376
+ # If redirection, we redirect only relative paths.
377
+ # This is useful in case of a renamed repository.
378
+ if 300 <= response.status_code <= 399:
379
+ parsed_target = urlparse(response.headers["Location"])
380
+ if parsed_target.netloc == "":
381
+ # This means it is a relative 'location' headers, as allowed by RFC 7231.
382
+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
383
+ # We want to follow this relative redirect !
384
+ #
385
+ # Highly inspired by `resolve_redirects` from requests library.
386
+ # See https://github.com/psf/requests/blob/main/requests/sessions.py#L159
387
+ next_url = urlparse(url)._replace(path=parsed_target.path).geturl()
388
+ return _request_wrapper(method=method, url=next_url, follow_relative_redirects=True, **params)
389
+ return response
390
+
391
+ # Perform request and return if status_code is not in the retry list.
392
+ response = get_session().request(method=method, url=url, **params)
393
+ hf_raise_for_status(response)
394
+ return response
395
+
396
+
397
+ def http_get(
398
+ url: str,
399
+ temp_file: BinaryIO,
400
+ *,
401
+ proxies: Optional[Dict] = None,
402
+ resume_size: float = 0,
403
+ headers: Optional[Dict[str, str]] = None,
404
+ expected_size: Optional[int] = None,
405
+ displayed_filename: Optional[str] = None,
406
+ _nb_retries: int = 5,
407
+ _tqdm_bar: Optional[tqdm] = None,
408
+ ) -> None:
409
+ """
410
+ Download a remote file. Do not gobble up errors, and will return errors tailored to the Hugging Face Hub.
411
+
412
+ If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely a
413
+ transient error (network outage?). We log a warning message and try to resume the download a few times before
414
+ giving up. The method gives up after 5 attempts if no new data has being received from the server.
415
+
416
+ Args:
417
+ url (`str`):
418
+ The URL of the file to download.
419
+ temp_file (`BinaryIO`):
420
+ The file-like object where to save the file.
421
+ proxies (`dict`, *optional*):
422
+ Dictionary mapping protocol to the URL of the proxy passed to `requests.request`.
423
+ resume_size (`float`, *optional*):
424
+ The number of bytes already downloaded. If set to 0 (default), the whole file is download. If set to a
425
+ positive number, the download will resume at the given position.
426
+ headers (`dict`, *optional*):
427
+ Dictionary of HTTP Headers to send with the request.
428
+ expected_size (`int`, *optional*):
429
+ The expected size of the file to download. If set, the download will raise an error if the size of the
430
+ received content is different from the expected one.
431
+ displayed_filename (`str`, *optional*):
432
+ The filename of the file that is being downloaded. Value is used only to display a nice progress bar. If
433
+ not set, the filename is guessed from the URL or the `Content-Disposition` header.
434
+ """
435
+ hf_transfer = None
436
+ if HF_HUB_ENABLE_HF_TRANSFER:
437
+ if resume_size != 0:
438
+ warnings.warn("'hf_transfer' does not support `resume_size`: falling back to regular download method")
439
+ elif proxies is not None:
440
+ warnings.warn("'hf_transfer' does not support `proxies`: falling back to regular download method")
441
+ else:
442
+ try:
443
+ import hf_transfer # type: ignore[no-redef]
444
+ except ImportError:
445
+ raise ValueError(
446
+ "Fast download using 'hf_transfer' is enabled"
447
+ " (HF_HUB_ENABLE_HF_TRANSFER=1) but 'hf_transfer' package is not"
448
+ " available in your environment. Try `pip install hf_transfer`."
449
+ )
450
+
451
+ initial_headers = headers
452
+ headers = copy.deepcopy(headers) or {}
453
+ if resume_size > 0:
454
+ headers["Range"] = "bytes=%d-" % (resume_size,)
455
+
456
+ r = _request_wrapper(
457
+ method="GET", url=url, stream=True, proxies=proxies, headers=headers, timeout=HF_HUB_DOWNLOAD_TIMEOUT
458
+ )
459
+ hf_raise_for_status(r)
460
+ content_length = r.headers.get("Content-Length")
461
+
462
+ # NOTE: 'total' is the total number of bytes to download, not the number of bytes in the file.
463
+ # If the file is compressed, the number of bytes in the saved file will be higher than 'total'.
464
+ total = resume_size + int(content_length) if content_length is not None else None
465
+
466
+ if displayed_filename is None:
467
+ displayed_filename = url
468
+ content_disposition = r.headers.get("Content-Disposition")
469
+ if content_disposition is not None:
470
+ match = HEADER_FILENAME_PATTERN.search(content_disposition)
471
+ if match is not None:
472
+ # Means file is on CDN
473
+ displayed_filename = match.groupdict()["filename"]
474
+
475
+ # Truncate filename if too long to display
476
+ if len(displayed_filename) > 40:
477
+ displayed_filename = f"(…){displayed_filename[-40:]}"
478
+
479
+ consistency_error_message = (
480
+ f"Consistency check failed: file should be of size {expected_size} but has size"
481
+ f" {{actual_size}} ({displayed_filename}).\nWe are sorry for the inconvenience. Please retry download and"
482
+ " pass `force_download=True, resume_download=False` as argument.\nIf the issue persists, please let us"
483
+ " know by opening an issue on https://github.com/huggingface/huggingface_hub."
484
+ )
485
+
486
+ # Stream file to buffer
487
+ progress = _tqdm_bar
488
+ if progress is None:
489
+ progress = tqdm(
490
+ unit="B",
491
+ unit_scale=True,
492
+ total=total,
493
+ initial=resume_size,
494
+ desc=displayed_filename,
495
+ disable=True if (logger.getEffectiveLevel() == logging.NOTSET) else None,
496
+ # ^ set `disable=None` rather than `disable=False` by default to disable progress bar when no TTY attached
497
+ # see https://github.com/huggingface/huggingface_hub/pull/2000
498
+ )
499
+
500
+ if hf_transfer and total is not None and total > 5 * DOWNLOAD_CHUNK_SIZE:
501
+ supports_callback = "callback" in inspect.signature(hf_transfer.download).parameters
502
+ if not supports_callback:
503
+ warnings.warn(
504
+ "You are using an outdated version of `hf_transfer`. "
505
+ "Consider upgrading to latest version to enable progress bars "
506
+ "using `pip install -U hf_transfer`."
507
+ )
508
+ try:
509
+ hf_transfer.download(
510
+ url=url,
511
+ filename=temp_file.name,
512
+ max_files=HF_TRANSFER_CONCURRENCY,
513
+ chunk_size=DOWNLOAD_CHUNK_SIZE,
514
+ headers=headers,
515
+ parallel_failures=3,
516
+ max_retries=5,
517
+ **({"callback": progress.update} if supports_callback else {}),
518
+ )
519
+ except Exception as e:
520
+ raise RuntimeError(
521
+ "An error occurred while downloading using `hf_transfer`. Consider"
522
+ " disabling HF_HUB_ENABLE_HF_TRANSFER for better error handling."
523
+ ) from e
524
+ if not supports_callback:
525
+ progress.update(total)
526
+ if expected_size is not None and expected_size != os.path.getsize(temp_file.name):
527
+ raise EnvironmentError(
528
+ consistency_error_message.format(
529
+ actual_size=os.path.getsize(temp_file.name),
530
+ )
531
+ )
532
+ return
533
+ new_resume_size = resume_size
534
+ try:
535
+ for chunk in r.iter_content(chunk_size=DOWNLOAD_CHUNK_SIZE):
536
+ if chunk: # filter out keep-alive new chunks
537
+ progress.update(len(chunk))
538
+ temp_file.write(chunk)
539
+ new_resume_size += len(chunk)
540
+ # Some data has been downloaded from the server so we reset the number of retries.
541
+ _nb_retries = 5
542
+ except (requests.ConnectionError, requests.ReadTimeout) as e:
543
+ # If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely
544
+ # a transient error (network outage?). We log a warning message and try to resume the download a few times
545
+ # before giving up. Tre retry mechanism is basic but should be enough in most cases.
546
+ if _nb_retries <= 0:
547
+ logger.warning("Error while downloading from %s: %s\nMax retries exceeded.", url, str(e))
548
+ raise
549
+ logger.warning("Error while downloading from %s: %s\nTrying to resume download...", url, str(e))
550
+ time.sleep(1)
551
+ reset_sessions() # In case of SSLError it's best to reset the shared requests.Session objects
552
+ return http_get(
553
+ url=url,
554
+ temp_file=temp_file,
555
+ proxies=proxies,
556
+ resume_size=new_resume_size,
557
+ headers=initial_headers,
558
+ expected_size=expected_size,
559
+ _nb_retries=_nb_retries - 1,
560
+ _tqdm_bar=_tqdm_bar,
561
+ )
562
+
563
+ progress.close()
564
+
565
+ if expected_size is not None and expected_size != temp_file.tell():
566
+ raise EnvironmentError(
567
+ consistency_error_message.format(
568
+ actual_size=temp_file.tell(),
569
+ )
570
+ )
571
+
572
+
573
+ @validate_hf_hub_args
574
+ def cached_download(
575
+ url: str,
576
+ *,
577
+ library_name: Optional[str] = None,
578
+ library_version: Optional[str] = None,
579
+ cache_dir: Union[str, Path, None] = None,
580
+ user_agent: Union[Dict, str, None] = None,
581
+ force_download: bool = False,
582
+ force_filename: Optional[str] = None,
583
+ proxies: Optional[Dict] = None,
584
+ etag_timeout: float = DEFAULT_ETAG_TIMEOUT,
585
+ resume_download: bool = False,
586
+ token: Union[bool, str, None] = None,
587
+ local_files_only: bool = False,
588
+ legacy_cache_layout: bool = False,
589
+ ) -> str:
590
+ """
591
+ Download from a given URL and cache it if it's not already present in the
592
+ local cache.
593
+
594
+ Given a URL, this function looks for the corresponding file in the local
595
+ cache. If it's not there, download it. Then return the path to the cached
596
+ file.
597
+
598
+ Will raise errors tailored to the Hugging Face Hub.
599
+
600
+ Args:
601
+ url (`str`):
602
+ The path to the file to be downloaded.
603
+ library_name (`str`, *optional*):
604
+ The name of the library to which the object corresponds.
605
+ library_version (`str`, *optional*):
606
+ The version of the library.
607
+ cache_dir (`str`, `Path`, *optional*):
608
+ Path to the folder where cached files are stored.
609
+ user_agent (`dict`, `str`, *optional*):
610
+ The user-agent info in the form of a dictionary or a string.
611
+ force_download (`bool`, *optional*, defaults to `False`):
612
+ Whether the file should be downloaded even if it already exists in
613
+ the local cache.
614
+ force_filename (`str`, *optional*):
615
+ Use this name instead of a generated file name.
616
+ proxies (`dict`, *optional*):
617
+ Dictionary mapping protocol to the URL of the proxy passed to
618
+ `requests.request`.
619
+ etag_timeout (`float`, *optional* defaults to `10`):
620
+ When fetching ETag, how many seconds to wait for the server to send
621
+ data before giving up which is passed to `requests.request`.
622
+ resume_download (`bool`, *optional*, defaults to `False`):
623
+ If `True`, resume a previously interrupted download.
624
+ token (`bool`, `str`, *optional*):
625
+ A token to be used for the download.
626
+ - If `True`, the token is read from the HuggingFace config
627
+ folder.
628
+ - If a string, it's used as the authentication token.
629
+ local_files_only (`bool`, *optional*, defaults to `False`):
630
+ If `True`, avoid downloading the file and return the path to the
631
+ local cached file if it exists.
632
+ legacy_cache_layout (`bool`, *optional*, defaults to `False`):
633
+ Set this parameter to `True` to mention that you'd like to continue
634
+ the old cache layout. Putting this to `True` manually will not raise
635
+ any warning when using `cached_download`. We recommend using
636
+ `hf_hub_download` to take advantage of the new cache.
637
+
638
+ Returns:
639
+ Local path (string) of file or if networking is off, last version of
640
+ file cached on disk.
641
+
642
+ <Tip>
643
+
644
+ Raises the following errors:
645
+
646
+ - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
647
+ if `token=True` and the token cannot be found.
648
+ - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
649
+ if ETag cannot be determined.
650
+ - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
651
+ if some parameter value is invalid
652
+ - [`~utils.RepositoryNotFoundError`]
653
+ If the repository to download from cannot be found. This may be because it doesn't exist,
654
+ or because it is set to `private` and you do not have access.
655
+ - [`~utils.RevisionNotFoundError`]
656
+ If the revision to download from cannot be found.
657
+ - [`~utils.EntryNotFoundError`]
658
+ If the file to download cannot be found.
659
+ - [`~utils.LocalEntryNotFoundError`]
660
+ If network is disabled or unavailable and file is not found in cache.
661
+
662
+ </Tip>
663
+ """
664
+ if HF_HUB_ETAG_TIMEOUT != DEFAULT_ETAG_TIMEOUT:
665
+ # Respect environment variable above user value
666
+ etag_timeout = HF_HUB_ETAG_TIMEOUT
667
+
668
+ if not legacy_cache_layout:
669
+ warnings.warn(
670
+ "'cached_download' is the legacy way to download files from the HF hub, please consider upgrading to"
671
+ " 'hf_hub_download'",
672
+ FutureWarning,
673
+ )
674
+
675
+ if cache_dir is None:
676
+ cache_dir = HF_HUB_CACHE
677
+ if isinstance(cache_dir, Path):
678
+ cache_dir = str(cache_dir)
679
+
680
+ os.makedirs(cache_dir, exist_ok=True)
681
+
682
+ headers = build_hf_headers(
683
+ token=token,
684
+ library_name=library_name,
685
+ library_version=library_version,
686
+ user_agent=user_agent,
687
+ )
688
+
689
+ url_to_download = url
690
+ etag = None
691
+ expected_size = None
692
+ if not local_files_only:
693
+ try:
694
+ # Temporary header: we want the full (decompressed) content size returned to be able to check the
695
+ # downloaded file size
696
+ headers["Accept-Encoding"] = "identity"
697
+ r = _request_wrapper(
698
+ method="HEAD",
699
+ url=url,
700
+ headers=headers,
701
+ allow_redirects=False,
702
+ follow_relative_redirects=True,
703
+ proxies=proxies,
704
+ timeout=etag_timeout,
705
+ )
706
+ headers.pop("Accept-Encoding", None)
707
+ hf_raise_for_status(r)
708
+ etag = r.headers.get(HUGGINGFACE_HEADER_X_LINKED_ETAG) or r.headers.get("ETag")
709
+ # We favor a custom header indicating the etag of the linked resource, and
710
+ # we fallback to the regular etag header.
711
+ # If we don't have any of those, raise an error.
712
+ if etag is None:
713
+ raise FileMetadataError(
714
+ "Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility."
715
+ )
716
+ # We get the expected size of the file, to check the download went well.
717
+ expected_size = _int_or_none(r.headers.get("Content-Length"))
718
+ # In case of a redirect, save an extra redirect on the request.get call,
719
+ # and ensure we download the exact atomic version even if it changed
720
+ # between the HEAD and the GET (unlikely, but hey).
721
+ # Useful for lfs blobs that are stored on a CDN.
722
+ if 300 <= r.status_code <= 399:
723
+ url_to_download = r.headers["Location"]
724
+ headers.pop("authorization", None)
725
+ expected_size = None # redirected -> can't know the expected size
726
+ except (requests.exceptions.SSLError, requests.exceptions.ProxyError):
727
+ # Actually raise for those subclasses of ConnectionError
728
+ raise
729
+ except (
730
+ requests.exceptions.ConnectionError,
731
+ requests.exceptions.Timeout,
732
+ OfflineModeIsEnabled,
733
+ ):
734
+ # Otherwise, our Internet connection is down.
735
+ # etag is None
736
+ pass
737
+
738
+ filename = force_filename if force_filename is not None else url_to_filename(url, etag)
739
+
740
+ # get cache path to put the file
741
+ cache_path = os.path.join(cache_dir, filename)
742
+
743
+ # etag is None == we don't have a connection or we passed local_files_only.
744
+ # try to get the last downloaded one
745
+ if etag is None:
746
+ if os.path.exists(cache_path) and not force_download:
747
+ return cache_path
748
+ else:
749
+ matching_files = [
750
+ file
751
+ for file in fnmatch.filter(os.listdir(cache_dir), filename.split(".")[0] + ".*")
752
+ if not file.endswith(".json") and not file.endswith(".lock")
753
+ ]
754
+ if len(matching_files) > 0 and not force_download and force_filename is None:
755
+ return os.path.join(cache_dir, matching_files[-1])
756
+ else:
757
+ # If files cannot be found and local_files_only=True,
758
+ # the models might've been found if local_files_only=False
759
+ # Notify the user about that
760
+ if local_files_only:
761
+ raise LocalEntryNotFoundError(
762
+ "Cannot find the requested files in the cached path and"
763
+ " outgoing traffic has been disabled. To enable model look-ups"
764
+ " and downloads online, set 'local_files_only' to False."
765
+ )
766
+ else:
767
+ raise LocalEntryNotFoundError(
768
+ "Connection error, and we cannot find the requested files in"
769
+ " the cached path. Please try again or make sure your Internet"
770
+ " connection is on."
771
+ )
772
+
773
+ # From now on, etag is not None.
774
+ if os.path.exists(cache_path) and not force_download:
775
+ return cache_path
776
+
777
+ # Prevent parallel downloads of the same file with a lock.
778
+ lock_path = cache_path + ".lock"
779
+
780
+ # Some Windows versions do not allow for paths longer than 255 characters.
781
+ # In this case, we must specify it is an extended path by using the "\\?\" prefix.
782
+ if os.name == "nt" and len(os.path.abspath(lock_path)) > 255:
783
+ lock_path = "\\\\?\\" + os.path.abspath(lock_path)
784
+
785
+ if os.name == "nt" and len(os.path.abspath(cache_path)) > 255:
786
+ cache_path = "\\\\?\\" + os.path.abspath(cache_path)
787
+
788
+ with WeakFileLock(lock_path):
789
+ # If the download just completed while the lock was activated.
790
+ if os.path.exists(cache_path) and not force_download:
791
+ # Even if returning early like here, the lock will be released.
792
+ return cache_path
793
+
794
+ if resume_download:
795
+ incomplete_path = cache_path + ".incomplete"
796
+
797
+ @contextmanager
798
+ def _resumable_file_manager() -> Generator[io.BufferedWriter, None, None]:
799
+ with open(incomplete_path, "ab") as f:
800
+ yield f
801
+
802
+ temp_file_manager = _resumable_file_manager
803
+ if os.path.exists(incomplete_path):
804
+ resume_size = os.stat(incomplete_path).st_size
805
+ else:
806
+ resume_size = 0
807
+ else:
808
+ temp_file_manager = partial( # type: ignore
809
+ tempfile.NamedTemporaryFile, mode="wb", dir=cache_dir, delete=False
810
+ )
811
+ resume_size = 0
812
+
813
+ # Download to temporary file, then copy to cache dir once finished.
814
+ # Otherwise you get corrupt cache entries if the download gets interrupted.
815
+ with temp_file_manager() as temp_file:
816
+ logger.info("downloading %s to %s", url, temp_file.name)
817
+
818
+ http_get(
819
+ url_to_download,
820
+ temp_file,
821
+ proxies=proxies,
822
+ resume_size=resume_size,
823
+ headers=headers,
824
+ expected_size=expected_size,
825
+ )
826
+
827
+ logger.info("storing %s in cache at %s", url, cache_path)
828
+ _chmod_and_replace(temp_file.name, cache_path)
829
+
830
+ if force_filename is None:
831
+ logger.info("creating metadata file for %s", cache_path)
832
+ meta = {"url": url, "etag": etag}
833
+ meta_path = cache_path + ".json"
834
+ with open(meta_path, "w") as meta_file:
835
+ json.dump(meta, meta_file)
836
+
837
+ return cache_path
838
+
839
+
840
+ def _normalize_etag(etag: Optional[str]) -> Optional[str]:
841
+ """Normalize ETag HTTP header, so it can be used to create nice filepaths.
842
+
843
+ The HTTP spec allows two forms of ETag:
844
+ ETag: W/"<etag_value>"
845
+ ETag: "<etag_value>"
846
+
847
+ For now, we only expect the second form from the server, but we want to be future-proof so we support both. For
848
+ more context, see `TestNormalizeEtag` tests and https://github.com/huggingface/huggingface_hub/pull/1428.
849
+
850
+ Args:
851
+ etag (`str`, *optional*): HTTP header
852
+
853
+ Returns:
854
+ `str` or `None`: string that can be used as a nice directory name.
855
+ Returns `None` if input is None.
856
+ """
857
+ if etag is None:
858
+ return None
859
+ return etag.lstrip("W/").strip('"')
860
+
861
+
862
+ def _create_relative_symlink(src: str, dst: str, new_blob: bool = False) -> None:
863
+ """Alias method used in `transformers` conversion script."""
864
+ return _create_symlink(src=src, dst=dst, new_blob=new_blob)
865
+
866
+
867
+ def _create_symlink(src: str, dst: str, new_blob: bool = False) -> None:
868
+ """Create a symbolic link named dst pointing to src.
869
+
870
+ By default, it will try to create a symlink using a relative path. Relative paths have 2 advantages:
871
+ - If the cache_folder is moved (example: back-up on a shared drive), relative paths within the cache folder will
872
+ not break.
873
+ - Relative paths seems to be better handled on Windows. Issue was reported 3 times in less than a week when
874
+ changing from relative to absolute paths. See https://github.com/huggingface/huggingface_hub/issues/1398,
875
+ https://github.com/huggingface/diffusers/issues/2729 and https://github.com/huggingface/transformers/pull/22228.
876
+ NOTE: The issue with absolute paths doesn't happen on admin mode.
877
+ When creating a symlink from the cache to a local folder, it is possible that a relative path cannot be created.
878
+ This happens when paths are not on the same volume. In that case, we use absolute paths.
879
+
880
+
881
+ The result layout looks something like
882
+ └── [ 128] snapshots
883
+ ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
884
+ │ ├── [ 52] README.md -> ../../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
885
+ │ └── [ 76] pytorch_model.bin -> ../../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
886
+
887
+ If symlinks cannot be created on this platform (most likely to be Windows), the workaround is to avoid symlinks by
888
+ having the actual file in `dst`. If it is a new file (`new_blob=True`), we move it to `dst`. If it is not a new file
889
+ (`new_blob=False`), we don't know if the blob file is already referenced elsewhere. To avoid breaking existing
890
+ cache, the file is duplicated on the disk.
891
+
892
+ In case symlinks are not supported, a warning message is displayed to the user once when loading `huggingface_hub`.
893
+ The warning message can be disabled with the `DISABLE_SYMLINKS_WARNING` environment variable.
894
+ """
895
+ try:
896
+ os.remove(dst)
897
+ except OSError:
898
+ pass
899
+
900
+ abs_src = os.path.abspath(os.path.expanduser(src))
901
+ abs_dst = os.path.abspath(os.path.expanduser(dst))
902
+ abs_dst_folder = os.path.dirname(abs_dst)
903
+
904
+ # Use relative_dst in priority
905
+ try:
906
+ relative_src = os.path.relpath(abs_src, abs_dst_folder)
907
+ except ValueError:
908
+ # Raised on Windows if src and dst are not on the same volume. This is the case when creating a symlink to a
909
+ # local_dir instead of within the cache directory.
910
+ # See https://docs.python.org/3/library/os.path.html#os.path.relpath
911
+ relative_src = None
912
+
913
+ try:
914
+ commonpath = os.path.commonpath([abs_src, abs_dst])
915
+ _support_symlinks = are_symlinks_supported(commonpath)
916
+ except ValueError:
917
+ # Raised if src and dst are not on the same volume. Symlinks will still work on Linux/Macos.
918
+ # See https://docs.python.org/3/library/os.path.html#os.path.commonpath
919
+ _support_symlinks = os.name != "nt"
920
+ except PermissionError:
921
+ # Permission error means src and dst are not in the same volume (e.g. destination path has been provided
922
+ # by the user via `local_dir`. Let's test symlink support there)
923
+ _support_symlinks = are_symlinks_supported(abs_dst_folder)
924
+ except OSError as e:
925
+ # OS error (errno=30) means that the commonpath is readonly on Linux/MacOS.
926
+ if e.errno == errno.EROFS:
927
+ _support_symlinks = are_symlinks_supported(abs_dst_folder)
928
+ else:
929
+ raise
930
+
931
+ # Symlinks are supported => let's create a symlink.
932
+ if _support_symlinks:
933
+ src_rel_or_abs = relative_src or abs_src
934
+ logger.debug(f"Creating pointer from {src_rel_or_abs} to {abs_dst}")
935
+ try:
936
+ os.symlink(src_rel_or_abs, abs_dst)
937
+ return
938
+ except FileExistsError:
939
+ if os.path.islink(abs_dst) and os.path.realpath(abs_dst) == os.path.realpath(abs_src):
940
+ # `abs_dst` already exists and is a symlink to the `abs_src` blob. It is most likely that the file has
941
+ # been cached twice concurrently (exactly between `os.remove` and `os.symlink`). Do nothing.
942
+ return
943
+ else:
944
+ # Very unlikely to happen. Means a file `dst` has been created exactly between `os.remove` and
945
+ # `os.symlink` and is not a symlink to the `abs_src` blob file. Raise exception.
946
+ raise
947
+ except PermissionError:
948
+ # Permission error means src and dst are not in the same volume (e.g. download to local dir) and symlink
949
+ # is supported on both volumes but not between them. Let's just make a hard copy in that case.
950
+ pass
951
+
952
+ # Symlinks are not supported => let's move or copy the file.
953
+ if new_blob:
954
+ logger.info(f"Symlink not supported. Moving file from {abs_src} to {abs_dst}")
955
+ shutil.move(abs_src, abs_dst)
956
+ else:
957
+ logger.info(f"Symlink not supported. Copying file from {abs_src} to {abs_dst}")
958
+ shutil.copyfile(abs_src, abs_dst)
959
+
960
+
961
+ def _cache_commit_hash_for_specific_revision(storage_folder: str, revision: str, commit_hash: str) -> None:
962
+ """Cache reference between a revision (tag, branch or truncated commit hash) and the corresponding commit hash.
963
+
964
+ Does nothing if `revision` is already a proper `commit_hash` or reference is already cached.
965
+ """
966
+ if revision != commit_hash:
967
+ ref_path = Path(storage_folder) / "refs" / revision
968
+ ref_path.parent.mkdir(parents=True, exist_ok=True)
969
+ if not ref_path.exists() or commit_hash != ref_path.read_text():
970
+ # Update ref only if has been updated. Could cause useless error in case
971
+ # repo is already cached and user doesn't have write access to cache folder.
972
+ # See https://github.com/huggingface/huggingface_hub/issues/1216.
973
+ ref_path.write_text(commit_hash)
974
+
975
+
976
+ @validate_hf_hub_args
977
+ def repo_folder_name(*, repo_id: str, repo_type: str) -> str:
978
+ """Return a serialized version of a hf.co repo name and type, safe for disk storage
979
+ as a single non-nested folder.
980
+
981
+ Example: models--julien-c--EsperBERTo-small
982
+ """
983
+ # remove all `/` occurrences to correctly convert repo to directory name
984
+ parts = [f"{repo_type}s", *repo_id.split("/")]
985
+ return REPO_ID_SEPARATOR.join(parts)
986
+
987
+
988
+ def _check_disk_space(expected_size: int, target_dir: Union[str, Path]) -> None:
989
+ """Check disk usage and log a warning if there is not enough disk space to download the file.
990
+
991
+ Args:
992
+ expected_size (`int`):
993
+ The expected size of the file in bytes.
994
+ target_dir (`str`):
995
+ The directory where the file will be stored after downloading.
996
+ """
997
+
998
+ target_dir = Path(target_dir) # format as `Path`
999
+ for path in [target_dir] + list(target_dir.parents): # first check target_dir, then each parents one by one
1000
+ try:
1001
+ target_dir_free = shutil.disk_usage(path).free
1002
+ if target_dir_free < expected_size:
1003
+ warnings.warn(
1004
+ "Not enough free disk space to download the file. "
1005
+ f"The expected file size is: {expected_size / 1e6:.2f} MB. "
1006
+ f"The target location {target_dir} only has {target_dir_free / 1e6:.2f} MB free disk space."
1007
+ )
1008
+ return
1009
+ except OSError: # raise on anything: file does not exist or space disk cannot be checked
1010
+ pass
1011
+
1012
+
1013
+ @validate_hf_hub_args
1014
+ def hf_hub_download(
1015
+ repo_id: str,
1016
+ filename: str,
1017
+ *,
1018
+ subfolder: Optional[str] = None,
1019
+ repo_type: Optional[str] = None,
1020
+ revision: Optional[str] = None,
1021
+ library_name: Optional[str] = None,
1022
+ library_version: Optional[str] = None,
1023
+ cache_dir: Union[str, Path, None] = None,
1024
+ local_dir: Union[str, Path, None] = None,
1025
+ local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
1026
+ user_agent: Union[Dict, str, None] = None,
1027
+ force_download: bool = False,
1028
+ force_filename: Optional[str] = None,
1029
+ proxies: Optional[Dict] = None,
1030
+ etag_timeout: float = DEFAULT_ETAG_TIMEOUT,
1031
+ resume_download: bool = False,
1032
+ token: Union[bool, str, None] = None,
1033
+ local_files_only: bool = False,
1034
+ headers: Optional[Dict[str, str]] = None,
1035
+ legacy_cache_layout: bool = False,
1036
+ endpoint: Optional[str] = None,
1037
+ ) -> str:
1038
+ """Download a given file if it's not already present in the local cache.
1039
+
1040
+ The new cache file layout looks like this:
1041
+ - The cache directory contains one subfolder per repo_id (namespaced by repo type)
1042
+ - inside each repo folder:
1043
+ - refs is a list of the latest known revision => commit_hash pairs
1044
+ - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
1045
+ whether they're LFS files or not)
1046
+ - snapshots contains one subfolder per commit, each "commit" contains the subset of the files
1047
+ that have been resolved at that particular commit. Each filename is a symlink to the blob
1048
+ at that particular commit.
1049
+
1050
+ If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure
1051
+ how you want to move those files:
1052
+ - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob
1053
+ files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal
1054
+ is to be able to manually edit and save small files without corrupting the cache while saving disk space for
1055
+ binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD`
1056
+ environment variable.
1057
+ - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`.
1058
+ This is optimal in term of disk usage but files must not be manually edited.
1059
+ - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the
1060
+ local dir. This means disk usage is not optimized.
1061
+ - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the
1062
+ files are downloaded and directly placed under `local_dir`. This means if you need to download them again later,
1063
+ they will be re-downloaded entirely.
1064
+
1065
+ ```
1066
+ [ 96] .
1067
+ └── [ 160] models--julien-c--EsperBERTo-small
1068
+ ├── [ 160] blobs
1069
+ │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
1070
+ │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
1071
+ │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
1072
+ ├── [ 96] refs
1073
+ │ └── [ 40] main
1074
+ └── [ 128] snapshots
1075
+ ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
1076
+ │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
1077
+ │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
1078
+ └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
1079
+ ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
1080
+ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
1081
+ ```
1082
+
1083
+ Args:
1084
+ repo_id (`str`):
1085
+ A user or an organization name and a repo name separated by a `/`.
1086
+ filename (`str`):
1087
+ The name of the file in the repo.
1088
+ subfolder (`str`, *optional*):
1089
+ An optional value corresponding to a folder inside the model repo.
1090
+ repo_type (`str`, *optional*):
1091
+ Set to `"dataset"` or `"space"` if downloading from a dataset or space,
1092
+ `None` or `"model"` if downloading from a model. Default is `None`.
1093
+ revision (`str`, *optional*):
1094
+ An optional Git revision id which can be a branch name, a tag, or a
1095
+ commit hash.
1096
+ library_name (`str`, *optional*):
1097
+ The name of the library to which the object corresponds.
1098
+ library_version (`str`, *optional*):
1099
+ The version of the library.
1100
+ cache_dir (`str`, `Path`, *optional*):
1101
+ Path to the folder where cached files are stored.
1102
+ local_dir (`str` or `Path`, *optional*):
1103
+ If provided, the downloaded file will be placed under this directory, either as a symlink (default) or
1104
+ a regular file (see description for more details).
1105
+ local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`):
1106
+ To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either
1107
+ duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be
1108
+ created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if
1109
+ already exists) or downloaded from the Hub and not cached. See description for more details.
1110
+ user_agent (`dict`, `str`, *optional*):
1111
+ The user-agent info in the form of a dictionary or a string.
1112
+ force_download (`bool`, *optional*, defaults to `False`):
1113
+ Whether the file should be downloaded even if it already exists in
1114
+ the local cache.
1115
+ proxies (`dict`, *optional*):
1116
+ Dictionary mapping protocol to the URL of the proxy passed to
1117
+ `requests.request`.
1118
+ etag_timeout (`float`, *optional*, defaults to `10`):
1119
+ When fetching ETag, how many seconds to wait for the server to send
1120
+ data before giving up which is passed to `requests.request`.
1121
+ resume_download (`bool`, *optional*, defaults to `False`):
1122
+ If `True`, resume a previously interrupted download.
1123
+ token (`str`, `bool`, *optional*):
1124
+ A token to be used for the download.
1125
+ - If `True`, the token is read from the HuggingFace config
1126
+ folder.
1127
+ - If a string, it's used as the authentication token.
1128
+ local_files_only (`bool`, *optional*, defaults to `False`):
1129
+ If `True`, avoid downloading the file and return the path to the
1130
+ local cached file if it exists.
1131
+ headers (`dict`, *optional*):
1132
+ Additional headers to be sent with the request.
1133
+ legacy_cache_layout (`bool`, *optional*, defaults to `False`):
1134
+ If `True`, uses the legacy file cache layout i.e. just call [`hf_hub_url`]
1135
+ then `cached_download`. This is deprecated as the new cache layout is
1136
+ more powerful.
1137
+
1138
+ Returns:
1139
+ Local path (string) of file or if networking is off, last version of
1140
+ file cached on disk.
1141
+
1142
+ <Tip>
1143
+
1144
+ Raises the following errors:
1145
+
1146
+ - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
1147
+ if `token=True` and the token cannot be found.
1148
+ - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
1149
+ if ETag cannot be determined.
1150
+ - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
1151
+ if some parameter value is invalid
1152
+ - [`~utils.RepositoryNotFoundError`]
1153
+ If the repository to download from cannot be found. This may be because it doesn't exist,
1154
+ or because it is set to `private` and you do not have access.
1155
+ - [`~utils.RevisionNotFoundError`]
1156
+ If the revision to download from cannot be found.
1157
+ - [`~utils.EntryNotFoundError`]
1158
+ If the file to download cannot be found.
1159
+ - [`~utils.LocalEntryNotFoundError`]
1160
+ If network is disabled or unavailable and file is not found in cache.
1161
+
1162
+ </Tip>
1163
+ """
1164
+ if HF_HUB_ETAG_TIMEOUT != DEFAULT_ETAG_TIMEOUT:
1165
+ # Respect environment variable above user value
1166
+ etag_timeout = HF_HUB_ETAG_TIMEOUT
1167
+
1168
+ if force_filename is not None:
1169
+ warnings.warn(
1170
+ "The `force_filename` parameter is deprecated as a new caching system, "
1171
+ "which keeps the filenames as they are on the Hub, is now in place.",
1172
+ FutureWarning,
1173
+ )
1174
+ legacy_cache_layout = True
1175
+
1176
+ if legacy_cache_layout:
1177
+ url = hf_hub_url(
1178
+ repo_id,
1179
+ filename,
1180
+ subfolder=subfolder,
1181
+ repo_type=repo_type,
1182
+ revision=revision,
1183
+ endpoint=endpoint,
1184
+ )
1185
+
1186
+ return cached_download(
1187
+ url,
1188
+ library_name=library_name,
1189
+ library_version=library_version,
1190
+ cache_dir=cache_dir,
1191
+ user_agent=user_agent,
1192
+ force_download=force_download,
1193
+ force_filename=force_filename,
1194
+ proxies=proxies,
1195
+ etag_timeout=etag_timeout,
1196
+ resume_download=resume_download,
1197
+ token=token,
1198
+ local_files_only=local_files_only,
1199
+ legacy_cache_layout=legacy_cache_layout,
1200
+ )
1201
+
1202
+ if cache_dir is None:
1203
+ cache_dir = HF_HUB_CACHE
1204
+ if revision is None:
1205
+ revision = DEFAULT_REVISION
1206
+ if isinstance(cache_dir, Path):
1207
+ cache_dir = str(cache_dir)
1208
+ if isinstance(local_dir, Path):
1209
+ local_dir = str(local_dir)
1210
+ locks_dir = os.path.join(cache_dir, ".locks")
1211
+
1212
+ if subfolder == "":
1213
+ subfolder = None
1214
+ if subfolder is not None:
1215
+ # This is used to create a URL, and not a local path, hence the forward slash.
1216
+ filename = f"{subfolder}/{filename}"
1217
+
1218
+ if repo_type is None:
1219
+ repo_type = "model"
1220
+ if repo_type not in REPO_TYPES:
1221
+ raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(REPO_TYPES)}")
1222
+
1223
+ storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
1224
+
1225
+ # cross platform transcription of filename, to be used as a local file path.
1226
+ relative_filename = os.path.join(*filename.split("/"))
1227
+ if os.name == "nt":
1228
+ if relative_filename.startswith("..\\") or "\\..\\" in relative_filename:
1229
+ raise ValueError(
1230
+ f"Invalid filename: cannot handle filename '{relative_filename}' on Windows. Please ask the repository"
1231
+ " owner to rename this file."
1232
+ )
1233
+
1234
+ # if user provides a commit_hash and they already have the file on disk,
1235
+ # shortcut everything.
1236
+ if REGEX_COMMIT_HASH.match(revision):
1237
+ pointer_path = _get_pointer_path(storage_folder, revision, relative_filename)
1238
+ if os.path.exists(pointer_path):
1239
+ if local_dir is not None:
1240
+ return _to_local_dir(pointer_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks)
1241
+ return pointer_path
1242
+
1243
+ url = hf_hub_url(repo_id, filename, repo_type=repo_type, revision=revision, endpoint=endpoint)
1244
+
1245
+ headers = build_hf_headers(
1246
+ token=token,
1247
+ library_name=library_name,
1248
+ library_version=library_version,
1249
+ user_agent=user_agent,
1250
+ headers=headers,
1251
+ )
1252
+
1253
+ url_to_download = url
1254
+ etag = None
1255
+ commit_hash = None
1256
+ expected_size = None
1257
+ head_call_error: Optional[Exception] = None
1258
+ if not local_files_only:
1259
+ try:
1260
+ try:
1261
+ metadata = get_hf_file_metadata(
1262
+ url=url,
1263
+ token=token,
1264
+ proxies=proxies,
1265
+ timeout=etag_timeout,
1266
+ library_name=library_name,
1267
+ library_version=library_version,
1268
+ user_agent=user_agent,
1269
+ )
1270
+ except EntryNotFoundError as http_error:
1271
+ # Cache the non-existence of the file and raise
1272
+ commit_hash = http_error.response.headers.get(HUGGINGFACE_HEADER_X_REPO_COMMIT)
1273
+ if commit_hash is not None and not legacy_cache_layout:
1274
+ no_exist_file_path = Path(storage_folder) / ".no_exist" / commit_hash / relative_filename
1275
+ no_exist_file_path.parent.mkdir(parents=True, exist_ok=True)
1276
+ no_exist_file_path.touch()
1277
+ _cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash)
1278
+ raise
1279
+
1280
+ # Commit hash must exist
1281
+ commit_hash = metadata.commit_hash
1282
+ if commit_hash is None:
1283
+ raise FileMetadataError(
1284
+ "Distant resource does not seem to be on huggingface.co. It is possible that a configuration issue"
1285
+ " prevents you from downloading resources from https://huggingface.co. Please check your firewall"
1286
+ " and proxy settings and make sure your SSL certificates are updated."
1287
+ )
1288
+
1289
+ # Etag must exist
1290
+ etag = metadata.etag
1291
+ # We favor a custom header indicating the etag of the linked resource, and
1292
+ # we fallback to the regular etag header.
1293
+ # If we don't have any of those, raise an error.
1294
+ if etag is None:
1295
+ raise FileMetadataError(
1296
+ "Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility."
1297
+ )
1298
+
1299
+ # Expected (uncompressed) size
1300
+ expected_size = metadata.size
1301
+
1302
+ # In case of a redirect, save an extra redirect on the request.get call,
1303
+ # and ensure we download the exact atomic version even if it changed
1304
+ # between the HEAD and the GET (unlikely, but hey).
1305
+ #
1306
+ # If url domain is different => we are downloading from a CDN => url is signed => don't send auth
1307
+ # If url domain is the same => redirect due to repo rename AND downloading a regular file => keep auth
1308
+ if metadata.location != url:
1309
+ url_to_download = metadata.location
1310
+ if urlparse(url).netloc != urlparse(url_to_download).netloc:
1311
+ # Remove authorization header when downloading a LFS blob
1312
+ headers.pop("authorization", None)
1313
+ except (requests.exceptions.SSLError, requests.exceptions.ProxyError):
1314
+ # Actually raise for those subclasses of ConnectionError
1315
+ raise
1316
+ except (
1317
+ requests.exceptions.ConnectionError,
1318
+ requests.exceptions.Timeout,
1319
+ OfflineModeIsEnabled,
1320
+ ) as error:
1321
+ # Otherwise, our Internet connection is down.
1322
+ # etag is None
1323
+ head_call_error = error
1324
+ pass
1325
+ except (RevisionNotFoundError, EntryNotFoundError):
1326
+ # The repo was found but the revision or entry doesn't exist on the Hub (never existed or got deleted)
1327
+ raise
1328
+ except requests.HTTPError as error:
1329
+ # Multiple reasons for an http error:
1330
+ # - Repository is private and invalid/missing token sent
1331
+ # - Repository is gated and invalid/missing token sent
1332
+ # - Hub is down (error 500 or 504)
1333
+ # => let's switch to 'local_files_only=True' to check if the files are already cached.
1334
+ # (if it's not the case, the error will be re-raised)
1335
+ head_call_error = error
1336
+ pass
1337
+ except FileMetadataError as error:
1338
+ # Multiple reasons for a FileMetadataError:
1339
+ # - Wrong network configuration (proxy, firewall, SSL certificates)
1340
+ # - Inconsistency on the Hub
1341
+ # => let's switch to 'local_files_only=True' to check if the files are already cached.
1342
+ # (if it's not the case, the error will be re-raised)
1343
+ head_call_error = error
1344
+ pass
1345
+
1346
+ assert (
1347
+ local_files_only or etag is not None or head_call_error is not None
1348
+ ), "etag is empty due to uncovered problems"
1349
+
1350
+ # etag can be None for several reasons:
1351
+ # 1. we passed local_files_only.
1352
+ # 2. we don't have a connection
1353
+ # 3. Hub is down (HTTP 500 or 504)
1354
+ # 4. repo is not found -for example private or gated- and invalid/missing token sent
1355
+ # 5. Hub is blocked by a firewall or proxy is not set correctly.
1356
+ # => Try to get the last downloaded one from the specified revision.
1357
+ #
1358
+ # If the specified revision is a commit hash, look inside "snapshots".
1359
+ # If the specified revision is a branch or tag, look inside "refs".
1360
+ if etag is None:
1361
+ # In those cases, we cannot force download.
1362
+ if force_download:
1363
+ if local_files_only:
1364
+ raise ValueError("Cannot pass 'force_download=True' and 'local_files_only=True' at the same time.")
1365
+ elif isinstance(head_call_error, OfflineModeIsEnabled):
1366
+ raise ValueError(
1367
+ "Cannot pass 'force_download=True' when offline mode is enabled."
1368
+ ) from head_call_error
1369
+ else:
1370
+ raise ValueError("Force download failed due to the above error.") from head_call_error
1371
+
1372
+ # Try to get "commit_hash" from "revision"
1373
+ commit_hash = None
1374
+ if REGEX_COMMIT_HASH.match(revision):
1375
+ commit_hash = revision
1376
+ else:
1377
+ ref_path = os.path.join(storage_folder, "refs", revision)
1378
+ if os.path.isfile(ref_path):
1379
+ with open(ref_path) as f:
1380
+ commit_hash = f.read()
1381
+
1382
+ # Return pointer file if exists
1383
+ if commit_hash is not None:
1384
+ pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename)
1385
+ if os.path.exists(pointer_path):
1386
+ if local_dir is not None:
1387
+ return _to_local_dir(
1388
+ pointer_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks
1389
+ )
1390
+ return pointer_path
1391
+
1392
+ # If we couldn't find an appropriate file on disk, raise an error.
1393
+ # If files cannot be found and local_files_only=True,
1394
+ # the models might've been found if local_files_only=False
1395
+ # Notify the user about that
1396
+ if local_files_only:
1397
+ raise LocalEntryNotFoundError(
1398
+ "Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable"
1399
+ " hf.co look-ups and downloads online, set 'local_files_only' to False."
1400
+ )
1401
+ elif isinstance(head_call_error, RepositoryNotFoundError) or isinstance(head_call_error, GatedRepoError):
1402
+ # Repo not found or gated => let's raise the actual error
1403
+ raise head_call_error
1404
+ else:
1405
+ # Otherwise: most likely a connection issue or Hub downtime => let's warn the user
1406
+ raise LocalEntryNotFoundError(
1407
+ "An error happened while trying to locate the file on the Hub and we cannot find the requested files"
1408
+ " in the local cache. Please check your connection and try again or make sure your Internet connection"
1409
+ " is on."
1410
+ ) from head_call_error
1411
+
1412
+ # From now on, etag and commit_hash are not None.
1413
+ assert etag is not None, "etag must have been retrieved from server"
1414
+ assert commit_hash is not None, "commit_hash must have been retrieved from server"
1415
+ blob_path = os.path.join(storage_folder, "blobs", etag)
1416
+ pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename)
1417
+
1418
+ os.makedirs(os.path.dirname(blob_path), exist_ok=True)
1419
+ os.makedirs(os.path.dirname(pointer_path), exist_ok=True)
1420
+ # if passed revision is not identical to commit_hash
1421
+ # then revision has to be a branch name or tag name.
1422
+ # In that case store a ref.
1423
+ _cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash)
1424
+
1425
+ if os.path.exists(pointer_path) and not force_download:
1426
+ if local_dir is not None:
1427
+ return _to_local_dir(pointer_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks)
1428
+ return pointer_path
1429
+
1430
+ if os.path.exists(blob_path) and not force_download:
1431
+ # we have the blob already, but not the pointer
1432
+ if local_dir is not None: # to local dir
1433
+ return _to_local_dir(blob_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks)
1434
+ else: # or in snapshot cache
1435
+ _create_symlink(blob_path, pointer_path, new_blob=False)
1436
+ return pointer_path
1437
+
1438
+ # Prevent parallel downloads of the same file with a lock.
1439
+ # etag could be duplicated across repos,
1440
+ lock_path = os.path.join(locks_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type), f"{etag}.lock")
1441
+
1442
+ # Some Windows versions do not allow for paths longer than 255 characters.
1443
+ # In this case, we must specify it is an extended path by using the "\\?\" prefix.
1444
+ if os.name == "nt" and len(os.path.abspath(lock_path)) > 255:
1445
+ lock_path = "\\\\?\\" + os.path.abspath(lock_path)
1446
+
1447
+ if os.name == "nt" and len(os.path.abspath(blob_path)) > 255:
1448
+ blob_path = "\\\\?\\" + os.path.abspath(blob_path)
1449
+
1450
+ Path(lock_path).parent.mkdir(parents=True, exist_ok=True)
1451
+ with WeakFileLock(lock_path):
1452
+ # If the download just completed while the lock was activated.
1453
+ if os.path.exists(pointer_path) and not force_download:
1454
+ # Even if returning early like here, the lock will be released.
1455
+ if local_dir is not None:
1456
+ return _to_local_dir(pointer_path, local_dir, relative_filename, use_symlinks=local_dir_use_symlinks)
1457
+ return pointer_path
1458
+
1459
+ if resume_download:
1460
+ incomplete_path = blob_path + ".incomplete"
1461
+
1462
+ @contextmanager
1463
+ def _resumable_file_manager() -> Generator[io.BufferedWriter, None, None]:
1464
+ with open(incomplete_path, "ab") as f:
1465
+ yield f
1466
+
1467
+ temp_file_manager = _resumable_file_manager
1468
+ if os.path.exists(incomplete_path):
1469
+ resume_size = os.stat(incomplete_path).st_size
1470
+ else:
1471
+ resume_size = 0
1472
+ else:
1473
+ temp_file_manager = partial( # type: ignore
1474
+ tempfile.NamedTemporaryFile, mode="wb", dir=cache_dir, delete=False
1475
+ )
1476
+ resume_size = 0
1477
+
1478
+ # Download to temporary file, then copy to cache dir once finished.
1479
+ # Otherwise you get corrupt cache entries if the download gets interrupted.
1480
+ with temp_file_manager() as temp_file:
1481
+ logger.info("downloading %s to %s", url, temp_file.name)
1482
+
1483
+ if expected_size is not None: # might be None if HTTP header not set correctly
1484
+ # Check tmp path
1485
+ _check_disk_space(expected_size, os.path.dirname(temp_file.name))
1486
+
1487
+ # Check destination
1488
+ _check_disk_space(expected_size, os.path.dirname(blob_path))
1489
+ if local_dir is not None:
1490
+ _check_disk_space(expected_size, local_dir)
1491
+
1492
+ http_get(
1493
+ url_to_download,
1494
+ temp_file,
1495
+ proxies=proxies,
1496
+ resume_size=resume_size,
1497
+ headers=headers,
1498
+ expected_size=expected_size,
1499
+ displayed_filename=filename,
1500
+ )
1501
+
1502
+ if local_dir is None:
1503
+ logger.debug(f"Storing {url} in cache at {blob_path}")
1504
+ _chmod_and_replace(temp_file.name, blob_path)
1505
+ _create_symlink(blob_path, pointer_path, new_blob=True)
1506
+ else:
1507
+ local_dir_filepath = os.path.join(local_dir, relative_filename)
1508
+ os.makedirs(os.path.dirname(local_dir_filepath), exist_ok=True)
1509
+
1510
+ # If "auto" (default) copy-paste small files to ease manual editing but symlink big files to save disk
1511
+ # In both cases, blob file is cached.
1512
+ is_big_file = os.stat(temp_file.name).st_size > constants.HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD
1513
+ if local_dir_use_symlinks is True or (local_dir_use_symlinks == "auto" and is_big_file):
1514
+ logger.debug(f"Storing {url} in cache at {blob_path}")
1515
+ _chmod_and_replace(temp_file.name, blob_path)
1516
+ logger.debug("Create symlink to local dir")
1517
+ _create_symlink(blob_path, local_dir_filepath, new_blob=False)
1518
+ elif local_dir_use_symlinks == "auto" and not is_big_file:
1519
+ logger.debug(f"Storing {url} in cache at {blob_path}")
1520
+ _chmod_and_replace(temp_file.name, blob_path)
1521
+ logger.debug("Duplicate in local dir (small file and use_symlink set to 'auto')")
1522
+ shutil.copyfile(blob_path, local_dir_filepath)
1523
+ else:
1524
+ logger.debug(f"Storing {url} in local_dir at {local_dir_filepath} (not cached).")
1525
+ _chmod_and_replace(temp_file.name, local_dir_filepath)
1526
+ pointer_path = local_dir_filepath # for return value
1527
+
1528
+ return pointer_path
1529
+
1530
+
1531
+ @validate_hf_hub_args
1532
+ def try_to_load_from_cache(
1533
+ repo_id: str,
1534
+ filename: str,
1535
+ cache_dir: Union[str, Path, None] = None,
1536
+ revision: Optional[str] = None,
1537
+ repo_type: Optional[str] = None,
1538
+ ) -> Union[str, _CACHED_NO_EXIST_T, None]:
1539
+ """
1540
+ Explores the cache to return the latest cached file for a given revision if found.
1541
+
1542
+ This function will not raise any exception if the file in not cached.
1543
+
1544
+ Args:
1545
+ cache_dir (`str` or `os.PathLike`):
1546
+ The folder where the cached files lie.
1547
+ repo_id (`str`):
1548
+ The ID of the repo on huggingface.co.
1549
+ filename (`str`):
1550
+ The filename to look for inside `repo_id`.
1551
+ revision (`str`, *optional*):
1552
+ The specific model version to use. Will default to `"main"` if it's not provided and no `commit_hash` is
1553
+ provided either.
1554
+ repo_type (`str`, *optional*):
1555
+ The type of the repository. Will default to `"model"`.
1556
+
1557
+ Returns:
1558
+ `Optional[str]` or `_CACHED_NO_EXIST`:
1559
+ Will return `None` if the file was not cached. Otherwise:
1560
+ - The exact path to the cached file if it's found in the cache
1561
+ - A special value `_CACHED_NO_EXIST` if the file does not exist at the given commit hash and this fact was
1562
+ cached.
1563
+
1564
+ Example:
1565
+
1566
+ ```python
1567
+ from huggingface_hub import try_to_load_from_cache, _CACHED_NO_EXIST
1568
+
1569
+ filepath = try_to_load_from_cache()
1570
+ if isinstance(filepath, str):
1571
+ # file exists and is cached
1572
+ ...
1573
+ elif filepath is _CACHED_NO_EXIST:
1574
+ # non-existence of file is cached
1575
+ ...
1576
+ else:
1577
+ # file is not cached
1578
+ ...
1579
+ ```
1580
+ """
1581
+ if revision is None:
1582
+ revision = "main"
1583
+ if repo_type is None:
1584
+ repo_type = "model"
1585
+ if repo_type not in REPO_TYPES:
1586
+ raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(REPO_TYPES)}")
1587
+ if cache_dir is None:
1588
+ cache_dir = HF_HUB_CACHE
1589
+
1590
+ object_id = repo_id.replace("/", "--")
1591
+ repo_cache = os.path.join(cache_dir, f"{repo_type}s--{object_id}")
1592
+ if not os.path.isdir(repo_cache):
1593
+ # No cache for this model
1594
+ return None
1595
+
1596
+ refs_dir = os.path.join(repo_cache, "refs")
1597
+ snapshots_dir = os.path.join(repo_cache, "snapshots")
1598
+ no_exist_dir = os.path.join(repo_cache, ".no_exist")
1599
+
1600
+ # Resolve refs (for instance to convert main to the associated commit sha)
1601
+ if os.path.isdir(refs_dir):
1602
+ revision_file = os.path.join(refs_dir, revision)
1603
+ if os.path.isfile(revision_file):
1604
+ with open(revision_file) as f:
1605
+ revision = f.read()
1606
+
1607
+ # Check if file is cached as "no_exist"
1608
+ if os.path.isfile(os.path.join(no_exist_dir, revision, filename)):
1609
+ return _CACHED_NO_EXIST
1610
+
1611
+ # Check if revision folder exists
1612
+ if not os.path.exists(snapshots_dir):
1613
+ return None
1614
+ cached_shas = os.listdir(snapshots_dir)
1615
+ if revision not in cached_shas:
1616
+ # No cache for this revision and we won't try to return a random revision
1617
+ return None
1618
+
1619
+ # Check if file exists in cache
1620
+ cached_file = os.path.join(snapshots_dir, revision, filename)
1621
+ return cached_file if os.path.isfile(cached_file) else None
1622
+
1623
+
1624
+ @validate_hf_hub_args
1625
+ def get_hf_file_metadata(
1626
+ url: str,
1627
+ token: Union[bool, str, None] = None,
1628
+ proxies: Optional[Dict] = None,
1629
+ timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT,
1630
+ library_name: Optional[str] = None,
1631
+ library_version: Optional[str] = None,
1632
+ user_agent: Union[Dict, str, None] = None,
1633
+ headers: Optional[Dict[str, str]] = None,
1634
+ ) -> HfFileMetadata:
1635
+ """Fetch metadata of a file versioned on the Hub for a given url.
1636
+
1637
+ Args:
1638
+ url (`str`):
1639
+ File url, for example returned by [`hf_hub_url`].
1640
+ token (`str` or `bool`, *optional*):
1641
+ A token to be used for the download.
1642
+ - If `True`, the token is read from the HuggingFace config
1643
+ folder.
1644
+ - If `False` or `None`, no token is provided.
1645
+ - If a string, it's used as the authentication token.
1646
+ proxies (`dict`, *optional*):
1647
+ Dictionary mapping protocol to the URL of the proxy passed to
1648
+ `requests.request`.
1649
+ timeout (`float`, *optional*, defaults to 10):
1650
+ How many seconds to wait for the server to send metadata before giving up.
1651
+ library_name (`str`, *optional*):
1652
+ The name of the library to which the object corresponds.
1653
+ library_version (`str`, *optional*):
1654
+ The version of the library.
1655
+ user_agent (`dict`, `str`, *optional*):
1656
+ The user-agent info in the form of a dictionary or a string.
1657
+ headers (`dict`, *optional*):
1658
+ Additional headers to be sent with the request.
1659
+
1660
+ Returns:
1661
+ A [`HfFileMetadata`] object containing metadata such as location, etag, size and
1662
+ commit_hash.
1663
+ """
1664
+ headers = build_hf_headers(
1665
+ token=token,
1666
+ library_name=library_name,
1667
+ library_version=library_version,
1668
+ user_agent=user_agent,
1669
+ headers=headers,
1670
+ )
1671
+ headers["Accept-Encoding"] = "identity" # prevent any compression => we want to know the real size of the file
1672
+
1673
+ # Retrieve metadata
1674
+ r = _request_wrapper(
1675
+ method="HEAD",
1676
+ url=url,
1677
+ headers=headers,
1678
+ allow_redirects=False,
1679
+ follow_relative_redirects=True,
1680
+ proxies=proxies,
1681
+ timeout=timeout,
1682
+ )
1683
+ hf_raise_for_status(r)
1684
+
1685
+ # Return
1686
+ return HfFileMetadata(
1687
+ commit_hash=r.headers.get(HUGGINGFACE_HEADER_X_REPO_COMMIT),
1688
+ # We favor a custom header indicating the etag of the linked resource, and
1689
+ # we fallback to the regular etag header.
1690
+ etag=_normalize_etag(r.headers.get(HUGGINGFACE_HEADER_X_LINKED_ETAG) or r.headers.get("ETag")),
1691
+ # Either from response headers (if redirected) or defaults to request url
1692
+ # Do not use directly `url`, as `_request_wrapper` might have followed relative
1693
+ # redirects.
1694
+ location=r.headers.get("Location") or r.request.url, # type: ignore
1695
+ size=_int_or_none(r.headers.get(HUGGINGFACE_HEADER_X_LINKED_SIZE) or r.headers.get("Content-Length")),
1696
+ )
1697
+
1698
+
1699
+ def _int_or_none(value: Optional[str]) -> Optional[int]:
1700
+ try:
1701
+ return int(value) # type: ignore
1702
+ except (TypeError, ValueError):
1703
+ return None
1704
+
1705
+
1706
+ def _chmod_and_replace(src: str, dst: str) -> None:
1707
+ """Set correct permission before moving a blob from tmp directory to cache dir.
1708
+
1709
+ Do not take into account the `umask` from the process as there is no convenient way
1710
+ to get it that is thread-safe.
1711
+
1712
+ See:
1713
+ - About umask: https://docs.python.org/3/library/os.html#os.umask
1714
+ - Thread-safety: https://stackoverflow.com/a/70343066
1715
+ - About solution: https://github.com/huggingface/huggingface_hub/pull/1220#issuecomment-1326211591
1716
+ - Fix issue: https://github.com/huggingface/huggingface_hub/issues/1141
1717
+ - Fix issue: https://github.com/huggingface/huggingface_hub/issues/1215
1718
+ """
1719
+ # Get umask by creating a temporary file in the cached repo folder.
1720
+ tmp_file = Path(dst).parent.parent / f"tmp_{uuid.uuid4()}"
1721
+ try:
1722
+ tmp_file.touch()
1723
+ cache_dir_mode = Path(tmp_file).stat().st_mode
1724
+ os.chmod(src, stat.S_IMODE(cache_dir_mode))
1725
+ finally:
1726
+ tmp_file.unlink()
1727
+
1728
+ shutil.move(src, dst)
1729
+
1730
+
1731
+ def _get_pointer_path(storage_folder: str, revision: str, relative_filename: str) -> str:
1732
+ # Using `os.path.abspath` instead of `Path.resolve()` to avoid resolving symlinks
1733
+ snapshot_path = os.path.join(storage_folder, "snapshots")
1734
+ pointer_path = os.path.join(snapshot_path, revision, relative_filename)
1735
+ if Path(os.path.abspath(snapshot_path)) not in Path(os.path.abspath(pointer_path)).parents:
1736
+ raise ValueError(
1737
+ "Invalid pointer path: cannot create pointer path in snapshot folder if"
1738
+ f" `storage_folder='{storage_folder}'`, `revision='{revision}'` and"
1739
+ f" `relative_filename='{relative_filename}'`."
1740
+ )
1741
+ return pointer_path
1742
+
1743
+
1744
+ def _to_local_dir(
1745
+ path: str, local_dir: str, relative_filename: str, use_symlinks: Union[bool, Literal["auto"]]
1746
+ ) -> str:
1747
+ """Place a file in a local dir (different than cache_dir).
1748
+
1749
+ Either symlink to blob file in cache or duplicate file depending on `use_symlinks` and file size.
1750
+ """
1751
+ # Using `os.path.abspath` instead of `Path.resolve()` to avoid resolving symlinks
1752
+ local_dir_filepath = os.path.join(local_dir, relative_filename)
1753
+ if Path(os.path.abspath(local_dir)) not in Path(os.path.abspath(local_dir_filepath)).parents:
1754
+ raise ValueError(
1755
+ f"Cannot copy file '{relative_filename}' to local dir '{local_dir}': file would not be in the local"
1756
+ " directory."
1757
+ )
1758
+
1759
+ os.makedirs(os.path.dirname(local_dir_filepath), exist_ok=True)
1760
+ real_blob_path = os.path.realpath(path)
1761
+
1762
+ # If "auto" (default) copy-paste small files to ease manual editing but symlink big files to save disk
1763
+ if use_symlinks == "auto":
1764
+ use_symlinks = os.stat(real_blob_path).st_size > constants.HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD
1765
+
1766
+ if use_symlinks:
1767
+ _create_symlink(real_blob_path, local_dir_filepath, new_blob=False)
1768
+ else:
1769
+ shutil.copyfile(real_blob_path, local_dir_filepath)
1770
+ return local_dir_filepath
env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_api.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/huggingface_hub/hf_file_system.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ import re
4
+ import tempfile
5
+ from collections import deque
6
+ from dataclasses import dataclass, field
7
+ from datetime import datetime
8
+ from itertools import chain
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, NoReturn, Optional, Tuple, Union
11
+ from urllib.parse import quote, unquote
12
+
13
+ import fsspec
14
+ from fsspec.callbacks import _DEFAULT_CALLBACK, NoOpCallback, TqdmCallback
15
+ from fsspec.utils import isfilelike
16
+ from requests import Response
17
+
18
+ from ._commit_api import CommitOperationCopy, CommitOperationDelete
19
+ from .constants import (
20
+ DEFAULT_REVISION,
21
+ ENDPOINT,
22
+ REPO_TYPE_MODEL,
23
+ REPO_TYPES_MAPPING,
24
+ REPO_TYPES_URL_PREFIXES,
25
+ )
26
+ from .file_download import hf_hub_url, http_get
27
+ from .hf_api import HfApi, LastCommitInfo, RepoFile
28
+ from .utils import (
29
+ EntryNotFoundError,
30
+ HFValidationError,
31
+ RepositoryNotFoundError,
32
+ RevisionNotFoundError,
33
+ hf_raise_for_status,
34
+ http_backoff,
35
+ )
36
+
37
+
38
+ # Regex used to match special revisions with "/" in them (see #1710)
39
+ SPECIAL_REFS_REVISION_REGEX = re.compile(
40
+ r"""
41
+ (^refs\/convert\/\w+) # `refs/convert/parquet` revisions
42
+ |
43
+ (^refs\/pr\/\d+) # PR revisions
44
+ """,
45
+ re.VERBOSE,
46
+ )
47
+
48
+
49
+ @dataclass
50
+ class HfFileSystemResolvedPath:
51
+ """Data structure containing information about a resolved Hugging Face file system path."""
52
+
53
+ repo_type: str
54
+ repo_id: str
55
+ revision: str
56
+ path_in_repo: str
57
+ # The part placed after '@' in the initial path. It can be a quoted or unquoted refs revision.
58
+ # Used to reconstruct the unresolved path to return to the user.
59
+ _raw_revision: Optional[str] = field(default=None, repr=False)
60
+
61
+ def unresolve(self) -> str:
62
+ repo_path = REPO_TYPES_URL_PREFIXES.get(self.repo_type, "") + self.repo_id
63
+ if self._raw_revision:
64
+ return f"{repo_path}@{self._raw_revision}/{self.path_in_repo}".rstrip("/")
65
+ elif self.revision != DEFAULT_REVISION:
66
+ return f"{repo_path}@{safe_revision(self.revision)}/{self.path_in_repo}".rstrip("/")
67
+ else:
68
+ return f"{repo_path}/{self.path_in_repo}".rstrip("/")
69
+
70
+
71
+ class HfFileSystem(fsspec.AbstractFileSystem):
72
+ """
73
+ Access a remote Hugging Face Hub repository as if were a local file system.
74
+
75
+ Args:
76
+ token (`str`, *optional*):
77
+ Authentication token, obtained with [`HfApi.login`] method. Will default to the stored token.
78
+
79
+ Usage:
80
+
81
+ ```python
82
+ >>> from huggingface_hub import HfFileSystem
83
+
84
+ >>> fs = HfFileSystem()
85
+
86
+ >>> # List files
87
+ >>> fs.glob("my-username/my-model/*.bin")
88
+ ['my-username/my-model/pytorch_model.bin']
89
+ >>> fs.ls("datasets/my-username/my-dataset", detail=False)
90
+ ['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json']
91
+
92
+ >>> # Read/write files
93
+ >>> with fs.open("my-username/my-model/pytorch_model.bin") as f:
94
+ ... data = f.read()
95
+ >>> with fs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
96
+ ... f.write(data)
97
+ ```
98
+ """
99
+
100
+ root_marker = ""
101
+ protocol = "hf"
102
+
103
+ def __init__(
104
+ self,
105
+ *args,
106
+ endpoint: Optional[str] = None,
107
+ token: Optional[str] = None,
108
+ **storage_options,
109
+ ):
110
+ super().__init__(*args, **storage_options)
111
+ self.endpoint = endpoint or ENDPOINT
112
+ self.token = token
113
+ self._api = HfApi(endpoint=endpoint, token=token)
114
+ # Maps (repo_type, repo_id, revision) to a 2-tuple with:
115
+ # * the 1st element indicating whether the repositoy and the revision exist
116
+ # * the 2nd element being the exception raised if the repository or revision doesn't exist
117
+ self._repo_and_revision_exists_cache: Dict[
118
+ Tuple[str, str, Optional[str]], Tuple[bool, Optional[Exception]]
119
+ ] = {}
120
+
121
+ def _repo_and_revision_exist(
122
+ self, repo_type: str, repo_id: str, revision: Optional[str]
123
+ ) -> Tuple[bool, Optional[Exception]]:
124
+ if (repo_type, repo_id, revision) not in self._repo_and_revision_exists_cache:
125
+ try:
126
+ self._api.repo_info(repo_id, revision=revision, repo_type=repo_type)
127
+ except (RepositoryNotFoundError, HFValidationError) as e:
128
+ self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e
129
+ self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = False, e
130
+ except RevisionNotFoundError as e:
131
+ self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e
132
+ self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None
133
+ else:
134
+ self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = True, None
135
+ self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None
136
+ return self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)]
137
+
138
+ def resolve_path(self, path: str, revision: Optional[str] = None) -> HfFileSystemResolvedPath:
139
+ def _align_revision_in_path_with_revision(
140
+ revision_in_path: Optional[str], revision: Optional[str]
141
+ ) -> Optional[str]:
142
+ if revision is not None:
143
+ if revision_in_path is not None and revision_in_path != revision:
144
+ raise ValueError(
145
+ f'Revision specified in path ("{revision_in_path}") and in `revision` argument ("{revision}")'
146
+ " are not the same."
147
+ )
148
+ else:
149
+ revision = revision_in_path
150
+ return revision
151
+
152
+ path = self._strip_protocol(path)
153
+ if not path:
154
+ # can't list repositories at root
155
+ raise NotImplementedError("Access to repositories lists is not implemented.")
156
+ elif path.split("/")[0] + "/" in REPO_TYPES_URL_PREFIXES.values():
157
+ if "/" not in path:
158
+ # can't list repositories at the repository type level
159
+ raise NotImplementedError("Access to repositories lists is not implemented.")
160
+ repo_type, path = path.split("/", 1)
161
+ repo_type = REPO_TYPES_MAPPING[repo_type]
162
+ else:
163
+ repo_type = REPO_TYPE_MODEL
164
+ if path.count("/") > 0:
165
+ if "@" in path:
166
+ repo_id, revision_in_path = path.split("@", 1)
167
+ if "/" in revision_in_path:
168
+ match = SPECIAL_REFS_REVISION_REGEX.search(revision_in_path)
169
+ if match is not None and revision in (None, match.group()):
170
+ # Handle `refs/convert/parquet` and PR revisions separately
171
+ path_in_repo = SPECIAL_REFS_REVISION_REGEX.sub("", revision_in_path).lstrip("/")
172
+ revision_in_path = match.group()
173
+ else:
174
+ revision_in_path, path_in_repo = revision_in_path.split("/", 1)
175
+ else:
176
+ path_in_repo = ""
177
+ revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision)
178
+ repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision)
179
+ if not repo_and_revision_exist:
180
+ _raise_file_not_found(path, err)
181
+ else:
182
+ revision_in_path = None
183
+ repo_id_with_namespace = "/".join(path.split("/")[:2])
184
+ path_in_repo_with_namespace = "/".join(path.split("/")[2:])
185
+ repo_id_without_namespace = path.split("/")[0]
186
+ path_in_repo_without_namespace = "/".join(path.split("/")[1:])
187
+ repo_id = repo_id_with_namespace
188
+ path_in_repo = path_in_repo_with_namespace
189
+ repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision)
190
+ if not repo_and_revision_exist:
191
+ if isinstance(err, (RepositoryNotFoundError, HFValidationError)):
192
+ repo_id = repo_id_without_namespace
193
+ path_in_repo = path_in_repo_without_namespace
194
+ repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision)
195
+ if not repo_and_revision_exist:
196
+ _raise_file_not_found(path, err)
197
+ else:
198
+ _raise_file_not_found(path, err)
199
+ else:
200
+ repo_id = path
201
+ path_in_repo = ""
202
+ if "@" in path:
203
+ repo_id, revision_in_path = path.split("@", 1)
204
+ revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision)
205
+ else:
206
+ revision_in_path = None
207
+ repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision)
208
+ if not repo_and_revision_exist:
209
+ raise NotImplementedError("Access to repositories lists is not implemented.")
210
+
211
+ revision = revision if revision is not None else DEFAULT_REVISION
212
+ return HfFileSystemResolvedPath(repo_type, repo_id, revision, path_in_repo, _raw_revision=revision_in_path)
213
+
214
+ def invalidate_cache(self, path: Optional[str] = None) -> None:
215
+ if not path:
216
+ self.dircache.clear()
217
+ self._repo_and_revision_exists_cache.clear()
218
+ else:
219
+ path = self.resolve_path(path).unresolve()
220
+ while path:
221
+ self.dircache.pop(path, None)
222
+ path = self._parent(path)
223
+
224
+ def _open(
225
+ self,
226
+ path: str,
227
+ mode: str = "rb",
228
+ revision: Optional[str] = None,
229
+ block_size: Optional[int] = None,
230
+ **kwargs,
231
+ ) -> "HfFileSystemFile":
232
+ if "a" in mode:
233
+ raise NotImplementedError("Appending to remote files is not yet supported.")
234
+ if block_size == 0:
235
+ return HfFileSystemStreamFile(self, path, mode=mode, revision=revision, block_size=block_size, **kwargs)
236
+ else:
237
+ return HfFileSystemFile(self, path, mode=mode, revision=revision, block_size=block_size, **kwargs)
238
+
239
+ def _rm(self, path: str, revision: Optional[str] = None, **kwargs) -> None:
240
+ resolved_path = self.resolve_path(path, revision=revision)
241
+ self._api.delete_file(
242
+ path_in_repo=resolved_path.path_in_repo,
243
+ repo_id=resolved_path.repo_id,
244
+ token=self.token,
245
+ repo_type=resolved_path.repo_type,
246
+ revision=resolved_path.revision,
247
+ commit_message=kwargs.get("commit_message"),
248
+ commit_description=kwargs.get("commit_description"),
249
+ )
250
+ self.invalidate_cache(path=resolved_path.unresolve())
251
+
252
+ def rm(
253
+ self,
254
+ path: str,
255
+ recursive: bool = False,
256
+ maxdepth: Optional[int] = None,
257
+ revision: Optional[str] = None,
258
+ **kwargs,
259
+ ) -> None:
260
+ resolved_path = self.resolve_path(path, revision=revision)
261
+ paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth, revision=revision)
262
+ paths_in_repo = [self.resolve_path(path).path_in_repo for path in paths if not self.isdir(path)]
263
+ operations = [CommitOperationDelete(path_in_repo=path_in_repo) for path_in_repo in paths_in_repo]
264
+ commit_message = f"Delete {path} "
265
+ commit_message += "recursively " if recursive else ""
266
+ commit_message += f"up to depth {maxdepth} " if maxdepth is not None else ""
267
+ # TODO: use `commit_description` to list all the deleted paths?
268
+ self._api.create_commit(
269
+ repo_id=resolved_path.repo_id,
270
+ repo_type=resolved_path.repo_type,
271
+ token=self.token,
272
+ operations=operations,
273
+ revision=resolved_path.revision,
274
+ commit_message=kwargs.get("commit_message", commit_message),
275
+ commit_description=kwargs.get("commit_description"),
276
+ )
277
+ self.invalidate_cache(path=resolved_path.unresolve())
278
+
279
+ def ls(
280
+ self, path: str, detail: bool = True, refresh: bool = False, revision: Optional[str] = None, **kwargs
281
+ ) -> List[Union[str, Dict[str, Any]]]:
282
+ """List the contents of a directory."""
283
+ resolved_path = self.resolve_path(path, revision=revision)
284
+ path = resolved_path.unresolve()
285
+ kwargs = {"expand_info": detail, **kwargs}
286
+ try:
287
+ out = self._ls_tree(path, refresh=refresh, revision=revision, **kwargs)
288
+ except EntryNotFoundError:
289
+ # Path could be a file
290
+ if not resolved_path.path_in_repo:
291
+ _raise_file_not_found(path, None)
292
+ out = self._ls_tree(self._parent(path), refresh=refresh, revision=revision, **kwargs)
293
+ out = [o for o in out if o["name"] == path]
294
+ if len(out) == 0:
295
+ _raise_file_not_found(path, None)
296
+ return out if detail else [o["name"] for o in out]
297
+
298
+ def _ls_tree(
299
+ self,
300
+ path: str,
301
+ recursive: bool = False,
302
+ refresh: bool = False,
303
+ revision: Optional[str] = None,
304
+ expand_info: bool = True,
305
+ ):
306
+ resolved_path = self.resolve_path(path, revision=revision)
307
+ path = resolved_path.unresolve()
308
+ root_path = HfFileSystemResolvedPath(
309
+ resolved_path.repo_type,
310
+ resolved_path.repo_id,
311
+ resolved_path.revision,
312
+ path_in_repo="",
313
+ _raw_revision=resolved_path._raw_revision,
314
+ ).unresolve()
315
+
316
+ out = []
317
+ if path in self.dircache and not refresh:
318
+ cached_path_infos = self.dircache[path]
319
+ out.extend(cached_path_infos)
320
+ dirs_not_in_dircache = []
321
+ if recursive:
322
+ # Use BFS to traverse the cache and build the "recursive "output
323
+ # (The Hub uses a so-called "tree first" strategy for the tree endpoint but we sort the output to follow the spec so the result is (eventually) the same)
324
+ dirs_to_visit = deque(
325
+ [path_info for path_info in cached_path_infos if path_info["type"] == "directory"]
326
+ )
327
+ while dirs_to_visit:
328
+ dir_info = dirs_to_visit.popleft()
329
+ if dir_info["name"] not in self.dircache:
330
+ dirs_not_in_dircache.append(dir_info["name"])
331
+ else:
332
+ cached_path_infos = self.dircache[dir_info["name"]]
333
+ out.extend(cached_path_infos)
334
+ dirs_to_visit.extend(
335
+ [path_info for path_info in cached_path_infos if path_info["type"] == "directory"]
336
+ )
337
+
338
+ dirs_not_expanded = []
339
+ if expand_info:
340
+ # Check if there are directories with non-expanded entries
341
+ dirs_not_expanded = [self._parent(o["name"]) for o in out if o["last_commit"] is None]
342
+
343
+ if (recursive and dirs_not_in_dircache) or (expand_info and dirs_not_expanded):
344
+ # If the dircache is incomplete, find the common path of the missing and non-expanded entries
345
+ # and extend the output with the result of `_ls_tree(common_path, recursive=True)`
346
+ common_prefix = os.path.commonprefix(dirs_not_in_dircache + dirs_not_expanded)
347
+ # Get the parent directory if the common prefix itself is not a directory
348
+ common_path = (
349
+ common_prefix.rstrip("/")
350
+ if common_prefix.endswith("/")
351
+ or common_prefix == root_path
352
+ or common_prefix in chain(dirs_not_in_dircache, dirs_not_expanded)
353
+ else self._parent(common_prefix)
354
+ )
355
+ out = [o for o in out if not o["name"].startswith(common_path + "/")]
356
+ for cached_path in self.dircache:
357
+ if cached_path.startswith(common_path + "/"):
358
+ self.dircache.pop(cached_path, None)
359
+ self.dircache.pop(common_path, None)
360
+ out.extend(
361
+ self._ls_tree(
362
+ common_path,
363
+ recursive=recursive,
364
+ refresh=True,
365
+ revision=revision,
366
+ expand_info=expand_info,
367
+ )
368
+ )
369
+ else:
370
+ tree = self._api.list_repo_tree(
371
+ resolved_path.repo_id,
372
+ resolved_path.path_in_repo,
373
+ recursive=recursive,
374
+ expand=expand_info,
375
+ revision=resolved_path.revision,
376
+ repo_type=resolved_path.repo_type,
377
+ )
378
+ for path_info in tree:
379
+ if isinstance(path_info, RepoFile):
380
+ cache_path_info = {
381
+ "name": root_path + "/" + path_info.path,
382
+ "size": path_info.size,
383
+ "type": "file",
384
+ "blob_id": path_info.blob_id,
385
+ "lfs": path_info.lfs,
386
+ "last_commit": path_info.last_commit,
387
+ "security": path_info.security,
388
+ }
389
+ else:
390
+ cache_path_info = {
391
+ "name": root_path + "/" + path_info.path,
392
+ "size": 0,
393
+ "type": "directory",
394
+ "tree_id": path_info.tree_id,
395
+ "last_commit": path_info.last_commit,
396
+ }
397
+ parent_path = self._parent(cache_path_info["name"])
398
+ self.dircache.setdefault(parent_path, []).append(cache_path_info)
399
+ out.append(cache_path_info)
400
+ return copy.deepcopy(out) # copy to not let users modify the dircache
401
+
402
+ def glob(self, path, **kwargs):
403
+ # Set expand_info=False by default to get a x10 speed boost
404
+ kwargs = {"expand_info": kwargs.get("detail", False), **kwargs}
405
+ path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve()
406
+ return super().glob(path, **kwargs)
407
+
408
+ def find(
409
+ self,
410
+ path: str,
411
+ maxdepth: Optional[int] = None,
412
+ withdirs: bool = False,
413
+ detail: bool = False,
414
+ refresh: bool = False,
415
+ revision: Optional[str] = None,
416
+ **kwargs,
417
+ ) -> Union[List[str], Dict[str, Dict[str, Any]]]:
418
+ if maxdepth:
419
+ return super().find(
420
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, refresh=refresh, revision=revision, **kwargs
421
+ )
422
+ resolved_path = self.resolve_path(path, revision=revision)
423
+ path = resolved_path.unresolve()
424
+ kwargs = {"expand_info": detail, **kwargs}
425
+ try:
426
+ out = self._ls_tree(path, recursive=True, refresh=refresh, revision=resolved_path.revision, **kwargs)
427
+ except EntryNotFoundError:
428
+ # Path could be a file
429
+ if self.info(path, revision=revision, **kwargs)["type"] == "file":
430
+ out = {path: {}}
431
+ else:
432
+ out = {}
433
+ else:
434
+ if not withdirs:
435
+ out = [o for o in out if o["type"] != "directory"]
436
+ else:
437
+ # If `withdirs=True`, include the directory itself to be consistent with the spec
438
+ path_info = self.info(path, revision=resolved_path.revision, **kwargs)
439
+ out = [path_info] + out if path_info["type"] == "directory" else out
440
+ out = {o["name"]: o for o in out}
441
+ names = sorted(out)
442
+ if not detail:
443
+ return names
444
+ else:
445
+ return {name: out[name] for name in names}
446
+
447
+ def cp_file(self, path1: str, path2: str, revision: Optional[str] = None, **kwargs) -> None:
448
+ resolved_path1 = self.resolve_path(path1, revision=revision)
449
+ resolved_path2 = self.resolve_path(path2, revision=revision)
450
+
451
+ same_repo = (
452
+ resolved_path1.repo_type == resolved_path2.repo_type and resolved_path1.repo_id == resolved_path2.repo_id
453
+ )
454
+
455
+ if same_repo:
456
+ commit_message = f"Copy {path1} to {path2}"
457
+ self._api.create_commit(
458
+ repo_id=resolved_path1.repo_id,
459
+ repo_type=resolved_path1.repo_type,
460
+ revision=resolved_path2.revision,
461
+ commit_message=kwargs.get("commit_message", commit_message),
462
+ commit_description=kwargs.get("commit_description", ""),
463
+ operations=[
464
+ CommitOperationCopy(
465
+ src_path_in_repo=resolved_path1.path_in_repo,
466
+ path_in_repo=resolved_path2.path_in_repo,
467
+ src_revision=resolved_path1.revision,
468
+ )
469
+ ],
470
+ )
471
+ else:
472
+ with self.open(path1, "rb", revision=resolved_path1.revision) as f:
473
+ content = f.read()
474
+ commit_message = f"Copy {path1} to {path2}"
475
+ self._api.upload_file(
476
+ path_or_fileobj=content,
477
+ path_in_repo=resolved_path2.path_in_repo,
478
+ repo_id=resolved_path2.repo_id,
479
+ token=self.token,
480
+ repo_type=resolved_path2.repo_type,
481
+ revision=resolved_path2.revision,
482
+ commit_message=kwargs.get("commit_message", commit_message),
483
+ commit_description=kwargs.get("commit_description"),
484
+ )
485
+ self.invalidate_cache(path=resolved_path1.unresolve())
486
+ self.invalidate_cache(path=resolved_path2.unresolve())
487
+
488
+ def modified(self, path: str, **kwargs) -> datetime:
489
+ info = self.info(path, **kwargs)
490
+ return info["last_commit"]["date"]
491
+
492
+ def info(self, path: str, refresh: bool = False, revision: Optional[str] = None, **kwargs) -> Dict[str, Any]:
493
+ resolved_path = self.resolve_path(path, revision=revision)
494
+ path = resolved_path.unresolve()
495
+ expand_info = kwargs.get(
496
+ "expand_info", True
497
+ ) # don't expose it as a parameter in the public API to follow the spec
498
+ if not resolved_path.path_in_repo:
499
+ # Path is the root directory
500
+ out = {
501
+ "name": path,
502
+ "size": 0,
503
+ "type": "directory",
504
+ }
505
+ if expand_info:
506
+ last_commit = self._api.list_repo_commits(
507
+ resolved_path.repo_id, repo_type=resolved_path.repo_type, revision=resolved_path.revision
508
+ )[-1]
509
+ out = {
510
+ **out,
511
+ "tree_id": None, # TODO: tree_id of the root directory?
512
+ "last_commit": LastCommitInfo(
513
+ oid=last_commit.commit_id, title=last_commit.title, date=last_commit.created_at
514
+ ),
515
+ }
516
+ else:
517
+ out = None
518
+ parent_path = self._parent(path)
519
+ if parent_path in self.dircache:
520
+ # Check if the path is in the cache
521
+ out1 = [o for o in self.dircache[parent_path] if o["name"] == path]
522
+ if not out1:
523
+ _raise_file_not_found(path, None)
524
+ out = out1[0]
525
+ if refresh or out is None or (expand_info and out and out["last_commit"] is None):
526
+ paths_info = self._api.get_paths_info(
527
+ resolved_path.repo_id,
528
+ resolved_path.path_in_repo,
529
+ expand=expand_info,
530
+ revision=resolved_path.revision,
531
+ repo_type=resolved_path.repo_type,
532
+ )
533
+ if not paths_info:
534
+ _raise_file_not_found(path, None)
535
+ path_info = paths_info[0]
536
+ root_path = HfFileSystemResolvedPath(
537
+ resolved_path.repo_type,
538
+ resolved_path.repo_id,
539
+ resolved_path.revision,
540
+ path_in_repo="",
541
+ _raw_revision=resolved_path._raw_revision,
542
+ ).unresolve()
543
+ if isinstance(path_info, RepoFile):
544
+ out = {
545
+ "name": root_path + "/" + path_info.path,
546
+ "size": path_info.size,
547
+ "type": "file",
548
+ "blob_id": path_info.blob_id,
549
+ "lfs": path_info.lfs,
550
+ "last_commit": path_info.last_commit,
551
+ "security": path_info.security,
552
+ }
553
+ else:
554
+ out = {
555
+ "name": root_path + "/" + path_info.path,
556
+ "size": 0,
557
+ "type": "directory",
558
+ "tree_id": path_info.tree_id,
559
+ "last_commit": path_info.last_commit,
560
+ }
561
+ if not expand_info:
562
+ out = {k: out[k] for k in ["name", "size", "type"]}
563
+ assert out is not None
564
+ return copy.deepcopy(out) # copy to not let users modify the dircache
565
+
566
+ def exists(self, path, **kwargs):
567
+ """Is there a file at the given path"""
568
+ try:
569
+ self.info(path, **{**kwargs, "expand_info": False})
570
+ return True
571
+ except: # noqa: E722
572
+ # any exception allowed bar FileNotFoundError?
573
+ return False
574
+
575
+ def isdir(self, path):
576
+ """Is this entry directory-like?"""
577
+ try:
578
+ return self.info(path, expand_info=False)["type"] == "directory"
579
+ except OSError:
580
+ return False
581
+
582
+ def isfile(self, path):
583
+ """Is this entry file-like?"""
584
+ try:
585
+ return self.info(path, expand_info=False)["type"] == "file"
586
+ except: # noqa: E722
587
+ return False
588
+
589
+ def url(self, path: str) -> str:
590
+ """Get the HTTP URL of the given path"""
591
+ resolved_path = self.resolve_path(path)
592
+ url = hf_hub_url(
593
+ resolved_path.repo_id,
594
+ resolved_path.path_in_repo,
595
+ repo_type=resolved_path.repo_type,
596
+ revision=resolved_path.revision,
597
+ endpoint=self.endpoint,
598
+ )
599
+ if self.isdir(path):
600
+ url = url.replace("/resolve/", "/tree/", 1)
601
+ return url
602
+
603
+ def get_file(self, rpath, lpath, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None:
604
+ """Copy single remote file to local."""
605
+ revision = kwargs.get("revision")
606
+ unhandled_kwargs = set(kwargs.keys()) - {"revision"}
607
+ if not isinstance(callback, (NoOpCallback, TqdmCallback)) or len(unhandled_kwargs) > 0:
608
+ # for now, let's not handle custom callbacks
609
+ # and let's not handle custom kwargs
610
+ return super().get_file(rpath, lpath, callback=callback, outfile=outfile, **kwargs)
611
+
612
+ # Taken from https://github.com/fsspec/filesystem_spec/blob/47b445ae4c284a82dd15e0287b1ffc410e8fc470/fsspec/spec.py#L883
613
+ if isfilelike(lpath):
614
+ outfile = lpath
615
+ elif self.isdir(rpath):
616
+ os.makedirs(lpath, exist_ok=True)
617
+ return None
618
+
619
+ if isinstance(lpath, (str, Path)): # otherwise, let's assume it's a file-like object
620
+ os.makedirs(os.path.dirname(lpath), exist_ok=True)
621
+
622
+ # Open file if not already open
623
+ close_file = False
624
+ if outfile is None:
625
+ outfile = open(lpath, "wb")
626
+ close_file = True
627
+ initial_pos = outfile.tell()
628
+
629
+ # Custom implementation of `get_file` to use `http_get`.
630
+ resolve_remote_path = self.resolve_path(rpath, revision=revision)
631
+ expected_size = self.info(rpath, revision=revision)["size"]
632
+ callback.set_size(expected_size)
633
+ try:
634
+ http_get(
635
+ url=hf_hub_url(
636
+ repo_id=resolve_remote_path.repo_id,
637
+ revision=resolve_remote_path.revision,
638
+ filename=resolve_remote_path.path_in_repo,
639
+ repo_type=resolve_remote_path.repo_type,
640
+ endpoint=self.endpoint,
641
+ ),
642
+ temp_file=outfile,
643
+ displayed_filename=rpath,
644
+ expected_size=expected_size,
645
+ resume_size=0,
646
+ headers=self._api._build_hf_headers(),
647
+ _tqdm_bar=callback.tqdm if isinstance(callback, TqdmCallback) else None,
648
+ )
649
+ outfile.seek(initial_pos)
650
+ finally:
651
+ # Close file only if we opened it ourselves
652
+ if close_file:
653
+ outfile.close()
654
+
655
+ @property
656
+ def transaction(self):
657
+ """A context within which files are committed together upon exit
658
+
659
+ Requires the file class to implement `.commit()` and `.discard()`
660
+ for the normal and exception cases.
661
+ """
662
+ # Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L231
663
+ # See https://github.com/huggingface/huggingface_hub/issues/1733
664
+ raise NotImplementedError("Transactional commits are not supported.")
665
+
666
+ def start_transaction(self):
667
+ """Begin write transaction for deferring files, non-context version"""
668
+ # Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L241
669
+ # See https://github.com/huggingface/huggingface_hub/issues/1733
670
+ raise NotImplementedError("Transactional commits are not supported.")
671
+
672
+
673
+ class HfFileSystemFile(fsspec.spec.AbstractBufferedFile):
674
+ def __init__(self, fs: HfFileSystem, path: str, revision: Optional[str] = None, **kwargs):
675
+ try:
676
+ self.resolved_path = fs.resolve_path(path, revision=revision)
677
+ except FileNotFoundError as e:
678
+ if "w" in kwargs.get("mode", ""):
679
+ raise FileNotFoundError(
680
+ f"{e}.\nMake sure the repository and revision exist before writing data."
681
+ ) from e
682
+ raise
683
+ super().__init__(fs, self.resolved_path.unresolve(), **kwargs)
684
+ self.fs: HfFileSystem
685
+
686
+ def __del__(self):
687
+ if not hasattr(self, "resolved_path"):
688
+ # Means that the constructor failed. Nothing to do.
689
+ return
690
+ return super().__del__()
691
+
692
+ def _fetch_range(self, start: int, end: int) -> bytes:
693
+ headers = {
694
+ "range": f"bytes={start}-{end - 1}",
695
+ **self.fs._api._build_hf_headers(),
696
+ }
697
+ url = hf_hub_url(
698
+ repo_id=self.resolved_path.repo_id,
699
+ revision=self.resolved_path.revision,
700
+ filename=self.resolved_path.path_in_repo,
701
+ repo_type=self.resolved_path.repo_type,
702
+ endpoint=self.fs.endpoint,
703
+ )
704
+ r = http_backoff("GET", url, headers=headers, retry_on_status_codes=(502, 503, 504))
705
+ hf_raise_for_status(r)
706
+ return r.content
707
+
708
+ def _initiate_upload(self) -> None:
709
+ self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False)
710
+
711
+ def _upload_chunk(self, final: bool = False) -> None:
712
+ self.buffer.seek(0)
713
+ block = self.buffer.read()
714
+ self.temp_file.write(block)
715
+ if final:
716
+ self.temp_file.close()
717
+ self.fs._api.upload_file(
718
+ path_or_fileobj=self.temp_file.name,
719
+ path_in_repo=self.resolved_path.path_in_repo,
720
+ repo_id=self.resolved_path.repo_id,
721
+ token=self.fs.token,
722
+ repo_type=self.resolved_path.repo_type,
723
+ revision=self.resolved_path.revision,
724
+ commit_message=self.kwargs.get("commit_message"),
725
+ commit_description=self.kwargs.get("commit_description"),
726
+ )
727
+ os.remove(self.temp_file.name)
728
+ self.fs.invalidate_cache(
729
+ path=self.resolved_path.unresolve(),
730
+ )
731
+
732
+ def read(self, length=-1):
733
+ """Read remote file.
734
+
735
+ If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems and if
736
+ `hf_transfer` is not enabled, the file is loaded in memory directly. Otherwise, the file is downloaded to a
737
+ temporary file and read from there.
738
+ """
739
+ if self.mode == "rb" and (length is None or length == -1) and self.loc == 0:
740
+ with self.fs.open(self.path, "rb", block_size=0) as f: # block_size=0 enables fast streaming
741
+ return f.read()
742
+ return super().read(length)
743
+
744
+ def url(self) -> str:
745
+ return self.fs.url(self.path)
746
+
747
+
748
+ class HfFileSystemStreamFile(fsspec.spec.AbstractBufferedFile):
749
+ def __init__(
750
+ self,
751
+ fs: HfFileSystem,
752
+ path: str,
753
+ mode: str = "rb",
754
+ revision: Optional[str] = None,
755
+ block_size: int = 0,
756
+ cache_type: str = "none",
757
+ **kwargs,
758
+ ):
759
+ if block_size != 0:
760
+ raise ValueError(f"HfFileSystemStreamFile only supports block_size=0 but got {block_size}")
761
+ if cache_type != "none":
762
+ raise ValueError(f"HfFileSystemStreamFile only supports cache_type='none' but got {cache_type}")
763
+ if "w" in mode:
764
+ raise ValueError(f"HfFileSystemStreamFile only supports reading but got mode='{mode}'")
765
+ try:
766
+ self.resolved_path = fs.resolve_path(path, revision=revision)
767
+ except FileNotFoundError as e:
768
+ if "w" in kwargs.get("mode", ""):
769
+ raise FileNotFoundError(
770
+ f"{e}.\nMake sure the repository and revision exist before writing data."
771
+ ) from e
772
+ # avoid an unnecessary .info() call to instantiate .details
773
+ self.details = {"name": self.resolved_path.unresolve(), "size": None}
774
+ super().__init__(
775
+ fs, self.resolved_path.unresolve(), mode=mode, block_size=block_size, cache_type=cache_type, **kwargs
776
+ )
777
+ self.response: Optional[Response] = None
778
+ self.fs: HfFileSystem
779
+
780
+ def seek(self, loc: int, whence: int = 0):
781
+ if loc == 0 and whence == 1:
782
+ return
783
+ if loc == self.loc and whence == 0:
784
+ return
785
+ raise ValueError("Cannot seek streaming HF file")
786
+
787
+ def read(self, length: int = -1):
788
+ read_args = (length,) if length >= 0 else ()
789
+ if self.response is None or self.response.raw.isclosed():
790
+ url = hf_hub_url(
791
+ repo_id=self.resolved_path.repo_id,
792
+ revision=self.resolved_path.revision,
793
+ filename=self.resolved_path.path_in_repo,
794
+ repo_type=self.resolved_path.repo_type,
795
+ endpoint=self.fs.endpoint,
796
+ )
797
+ self.response = http_backoff(
798
+ "GET",
799
+ url,
800
+ headers=self.fs._api._build_hf_headers(),
801
+ retry_on_status_codes=(502, 503, 504),
802
+ stream=True,
803
+ )
804
+ hf_raise_for_status(self.response)
805
+ try:
806
+ out = self.response.raw.read(*read_args)
807
+ except Exception:
808
+ self.response.close()
809
+
810
+ # Retry by recreating the connection
811
+ url = hf_hub_url(
812
+ repo_id=self.resolved_path.repo_id,
813
+ revision=self.resolved_path.revision,
814
+ filename=self.resolved_path.path_in_repo,
815
+ repo_type=self.resolved_path.repo_type,
816
+ endpoint=self.fs.endpoint,
817
+ )
818
+ self.response = http_backoff(
819
+ "GET",
820
+ url,
821
+ headers={"Range": "bytes=%d-" % self.loc, **self.fs._api._build_hf_headers()},
822
+ retry_on_status_codes=(502, 503, 504),
823
+ stream=True,
824
+ )
825
+ hf_raise_for_status(self.response)
826
+ try:
827
+ out = self.response.raw.read(*read_args)
828
+ except Exception:
829
+ self.response.close()
830
+ raise
831
+ self.loc += len(out)
832
+ return out
833
+
834
+ def url(self) -> str:
835
+ return self.fs.url(self.path)
836
+
837
+ def __del__(self):
838
+ if not hasattr(self, "resolved_path"):
839
+ # Means that the constructor failed. Nothing to do.
840
+ return
841
+ return super().__del__()
842
+
843
+ def __reduce__(self):
844
+ return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name)
845
+
846
+
847
+ def safe_revision(revision: str) -> str:
848
+ return revision if SPECIAL_REFS_REVISION_REGEX.match(revision) else safe_quote(revision)
849
+
850
+
851
+ def safe_quote(s: str) -> str:
852
+ return quote(s, safe="")
853
+
854
+
855
+ def _raise_file_not_found(path: str, err: Optional[Exception]) -> NoReturn:
856
+ msg = path
857
+ if isinstance(err, RepositoryNotFoundError):
858
+ msg = f"{path} (repository not found)"
859
+ elif isinstance(err, RevisionNotFoundError):
860
+ msg = f"{path} (revision not found)"
861
+ elif isinstance(err, HFValidationError):
862
+ msg = f"{path} (invalid repository id)"
863
+ raise FileNotFoundError(msg) from err
864
+
865
+
866
+ def reopen(fs: HfFileSystem, path: str, mode: str, block_size: int, cache_type: str):
867
+ return fs.open(path, mode=mode, block_size=block_size, cache_type=cache_type)
env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference_api.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from typing import Any, Dict, List, Optional, Union
3
+
4
+ from .constants import INFERENCE_ENDPOINT
5
+ from .hf_api import HfApi
6
+ from .utils import build_hf_headers, get_session, is_pillow_available, logging, validate_hf_hub_args
7
+ from .utils._deprecation import _deprecate_method
8
+
9
+
10
+ logger = logging.get_logger(__name__)
11
+
12
+
13
+ ALL_TASKS = [
14
+ # NLP
15
+ "text-classification",
16
+ "token-classification",
17
+ "table-question-answering",
18
+ "question-answering",
19
+ "zero-shot-classification",
20
+ "translation",
21
+ "summarization",
22
+ "conversational",
23
+ "feature-extraction",
24
+ "text-generation",
25
+ "text2text-generation",
26
+ "fill-mask",
27
+ "sentence-similarity",
28
+ # Audio
29
+ "text-to-speech",
30
+ "automatic-speech-recognition",
31
+ "audio-to-audio",
32
+ "audio-classification",
33
+ "voice-activity-detection",
34
+ # Computer vision
35
+ "image-classification",
36
+ "object-detection",
37
+ "image-segmentation",
38
+ "text-to-image",
39
+ "image-to-image",
40
+ # Others
41
+ "tabular-classification",
42
+ "tabular-regression",
43
+ ]
44
+
45
+
46
+ class InferenceApi:
47
+ """Client to configure requests and make calls to the HuggingFace Inference API.
48
+
49
+ Example:
50
+
51
+ ```python
52
+ >>> from huggingface_hub.inference_api import InferenceApi
53
+
54
+ >>> # Mask-fill example
55
+ >>> inference = InferenceApi("bert-base-uncased")
56
+ >>> inference(inputs="The goal of life is [MASK].")
57
+ [{'sequence': 'the goal of life is life.', 'score': 0.10933292657136917, 'token': 2166, 'token_str': 'life'}]
58
+
59
+ >>> # Question Answering example
60
+ >>> inference = InferenceApi("deepset/roberta-base-squad2")
61
+ >>> inputs = {
62
+ ... "question": "What's my name?",
63
+ ... "context": "My name is Clara and I live in Berkeley.",
64
+ ... }
65
+ >>> inference(inputs)
66
+ {'score': 0.9326569437980652, 'start': 11, 'end': 16, 'answer': 'Clara'}
67
+
68
+ >>> # Zero-shot example
69
+ >>> inference = InferenceApi("typeform/distilbert-base-uncased-mnli")
70
+ >>> inputs = "Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!"
71
+ >>> params = {"candidate_labels": ["refund", "legal", "faq"]}
72
+ >>> inference(inputs, params)
73
+ {'sequence': 'Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!', 'labels': ['refund', 'faq', 'legal'], 'scores': [0.9378499388694763, 0.04914155602455139, 0.013008488342165947]}
74
+
75
+ >>> # Overriding configured task
76
+ >>> inference = InferenceApi("bert-base-uncased", task="feature-extraction")
77
+
78
+ >>> # Text-to-image
79
+ >>> inference = InferenceApi("stabilityai/stable-diffusion-2-1")
80
+ >>> inference("cat")
81
+ <PIL.PngImagePlugin.PngImageFile image (...)>
82
+
83
+ >>> # Return as raw response to parse the output yourself
84
+ >>> inference = InferenceApi("mio/amadeus")
85
+ >>> response = inference("hello world", raw_response=True)
86
+ >>> response.headers
87
+ {"Content-Type": "audio/flac", ...}
88
+ >>> response.content # raw bytes from server
89
+ b'(...)'
90
+ ```
91
+ """
92
+
93
+ @validate_hf_hub_args
94
+ @_deprecate_method(
95
+ version="1.0",
96
+ message=(
97
+ "`InferenceApi` client is deprecated in favor of the more feature-complete `InferenceClient`. Check out"
98
+ " this guide to learn how to convert your script to use it:"
99
+ " https://huggingface.co/docs/huggingface_hub/guides/inference#legacy-inferenceapi-client."
100
+ ),
101
+ )
102
+ def __init__(
103
+ self,
104
+ repo_id: str,
105
+ task: Optional[str] = None,
106
+ token: Optional[str] = None,
107
+ gpu: bool = False,
108
+ ):
109
+ """Inits headers and API call information.
110
+
111
+ Args:
112
+ repo_id (``str``):
113
+ Id of repository (e.g. `user/bert-base-uncased`).
114
+ task (``str``, `optional`, defaults ``None``):
115
+ Whether to force a task instead of using task specified in the
116
+ repository.
117
+ token (`str`, `optional`):
118
+ The API token to use as HTTP bearer authorization. This is not
119
+ the authentication token. You can find the token in
120
+ https://huggingface.co/settings/token. Alternatively, you can
121
+ find both your organizations and personal API tokens using
122
+ `HfApi().whoami(token)`.
123
+ gpu (`bool`, `optional`, defaults `False`):
124
+ Whether to use GPU instead of CPU for inference(requires Startup
125
+ plan at least).
126
+ """
127
+ self.options = {"wait_for_model": True, "use_gpu": gpu}
128
+ self.headers = build_hf_headers(token=token)
129
+
130
+ # Configure task
131
+ model_info = HfApi(token=token).model_info(repo_id=repo_id)
132
+ if not model_info.pipeline_tag and not task:
133
+ raise ValueError(
134
+ "Task not specified in the repository. Please add it to the model card"
135
+ " using pipeline_tag"
136
+ " (https://huggingface.co/docs#how-is-a-models-type-of-inference-api-and-widget-determined)"
137
+ )
138
+
139
+ if task and task != model_info.pipeline_tag:
140
+ if task not in ALL_TASKS:
141
+ raise ValueError(f"Invalid task {task}. Make sure it's valid.")
142
+
143
+ logger.warning(
144
+ "You're using a different task than the one specified in the"
145
+ " repository. Be sure to know what you're doing :)"
146
+ )
147
+ self.task = task
148
+ else:
149
+ assert model_info.pipeline_tag is not None, "Pipeline tag cannot be None"
150
+ self.task = model_info.pipeline_tag
151
+
152
+ self.api_url = f"{INFERENCE_ENDPOINT}/pipeline/{self.task}/{repo_id}"
153
+
154
+ def __repr__(self):
155
+ # Do not add headers to repr to avoid leaking token.
156
+ return f"InferenceAPI(api_url='{self.api_url}', task='{self.task}', options={self.options})"
157
+
158
+ def __call__(
159
+ self,
160
+ inputs: Optional[Union[str, Dict, List[str], List[List[str]]]] = None,
161
+ params: Optional[Dict] = None,
162
+ data: Optional[bytes] = None,
163
+ raw_response: bool = False,
164
+ ) -> Any:
165
+ """Make a call to the Inference API.
166
+
167
+ Args:
168
+ inputs (`str` or `Dict` or `List[str]` or `List[List[str]]`, *optional*):
169
+ Inputs for the prediction.
170
+ params (`Dict`, *optional*):
171
+ Additional parameters for the models. Will be sent as `parameters` in the
172
+ payload.
173
+ data (`bytes`, *optional*):
174
+ Bytes content of the request. In this case, leave `inputs` and `params` empty.
175
+ raw_response (`bool`, defaults to `False`):
176
+ If `True`, the raw `Response` object is returned. You can parse its content
177
+ as preferred. By default, the content is parsed into a more practical format
178
+ (json dictionary or PIL Image for example).
179
+ """
180
+ # Build payload
181
+ payload: Dict[str, Any] = {
182
+ "options": self.options,
183
+ }
184
+ if inputs:
185
+ payload["inputs"] = inputs
186
+ if params:
187
+ payload["parameters"] = params
188
+
189
+ # Make API call
190
+ response = get_session().post(self.api_url, headers=self.headers, json=payload, data=data)
191
+
192
+ # Let the user handle the response
193
+ if raw_response:
194
+ return response
195
+
196
+ # By default, parse the response for the user.
197
+ content_type = response.headers.get("Content-Type") or ""
198
+ if content_type.startswith("image"):
199
+ if not is_pillow_available():
200
+ raise ImportError(
201
+ f"Task '{self.task}' returned as image but Pillow is not installed."
202
+ " Please install it (`pip install Pillow`) or pass"
203
+ " `raw_response=True` to get the raw `Response` object and parse"
204
+ " the image by yourself."
205
+ )
206
+
207
+ from PIL import Image
208
+
209
+ return Image.open(io.BytesIO(response.content))
210
+ elif content_type == "application/json":
211
+ return response.json()
212
+ else:
213
+ raise NotImplementedError(
214
+ f"{content_type} output type is not implemented yet. You can pass"
215
+ " `raw_response=True` to get the raw `Response` object and parse the"
216
+ " output by yourself."
217
+ )
env-llmeval/lib/python3.10/site-packages/huggingface_hub/lfs.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-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
+ """Git LFS related type definitions and utilities"""
16
+
17
+ import inspect
18
+ import io
19
+ import os
20
+ import re
21
+ import warnings
22
+ from contextlib import AbstractContextManager
23
+ from dataclasses import dataclass
24
+ from math import ceil
25
+ from os.path import getsize
26
+ from pathlib import Path
27
+ from typing import TYPE_CHECKING, BinaryIO, Dict, Iterable, List, Optional, Tuple, TypedDict
28
+ from urllib.parse import unquote
29
+
30
+ from huggingface_hub.constants import ENDPOINT, HF_HUB_ENABLE_HF_TRANSFER, REPO_TYPES_URL_PREFIXES
31
+
32
+ from .utils import (
33
+ build_hf_headers,
34
+ fix_hf_endpoint_in_url,
35
+ get_session,
36
+ hf_raise_for_status,
37
+ http_backoff,
38
+ logging,
39
+ tqdm,
40
+ validate_hf_hub_args,
41
+ )
42
+ from .utils.sha import sha256, sha_fileobj
43
+
44
+
45
+ if TYPE_CHECKING:
46
+ from ._commit_api import CommitOperationAdd
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ OID_REGEX = re.compile(r"^[0-9a-f]{40}$")
51
+
52
+ LFS_MULTIPART_UPLOAD_COMMAND = "lfs-multipart-upload"
53
+
54
+ LFS_HEADERS = {
55
+ "Accept": "application/vnd.git-lfs+json",
56
+ "Content-Type": "application/vnd.git-lfs+json",
57
+ }
58
+
59
+
60
+ @dataclass
61
+ class UploadInfo:
62
+ """
63
+ Dataclass holding required information to determine whether a blob
64
+ should be uploaded to the hub using the LFS protocol or the regular protocol
65
+
66
+ Args:
67
+ sha256 (`bytes`):
68
+ SHA256 hash of the blob
69
+ size (`int`):
70
+ Size in bytes of the blob
71
+ sample (`bytes`):
72
+ First 512 bytes of the blob
73
+ """
74
+
75
+ sha256: bytes
76
+ size: int
77
+ sample: bytes
78
+
79
+ @classmethod
80
+ def from_path(cls, path: str):
81
+ size = getsize(path)
82
+ with io.open(path, "rb") as file:
83
+ sample = file.peek(512)[:512]
84
+ sha = sha_fileobj(file)
85
+ return cls(size=size, sha256=sha, sample=sample)
86
+
87
+ @classmethod
88
+ def from_bytes(cls, data: bytes):
89
+ sha = sha256(data).digest()
90
+ return cls(size=len(data), sample=data[:512], sha256=sha)
91
+
92
+ @classmethod
93
+ def from_fileobj(cls, fileobj: BinaryIO):
94
+ sample = fileobj.read(512)
95
+ fileobj.seek(0, io.SEEK_SET)
96
+ sha = sha_fileobj(fileobj)
97
+ size = fileobj.tell()
98
+ fileobj.seek(0, io.SEEK_SET)
99
+ return cls(size=size, sha256=sha, sample=sample)
100
+
101
+
102
+ @validate_hf_hub_args
103
+ def post_lfs_batch_info(
104
+ upload_infos: Iterable[UploadInfo],
105
+ token: Optional[str],
106
+ repo_type: str,
107
+ repo_id: str,
108
+ revision: Optional[str] = None,
109
+ endpoint: Optional[str] = None,
110
+ headers: Optional[Dict[str, str]] = None,
111
+ ) -> Tuple[List[dict], List[dict]]:
112
+ """
113
+ Requests the LFS batch endpoint to retrieve upload instructions
114
+
115
+ Learn more: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
116
+
117
+ Args:
118
+ upload_infos (`Iterable` of `UploadInfo`):
119
+ `UploadInfo` for the files that are being uploaded, typically obtained
120
+ from `CommitOperationAdd.upload_info`
121
+ repo_type (`str`):
122
+ Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
123
+ repo_id (`str`):
124
+ A namespace (user or an organization) and a repo name separated
125
+ by a `/`.
126
+ revision (`str`, *optional*):
127
+ The git revision to upload to.
128
+ headers (`dict`, *optional*):
129
+ Additional headers to include in the request
130
+
131
+ Returns:
132
+ `LfsBatchInfo`: 2-tuple:
133
+ - First element is the list of upload instructions from the server
134
+ - Second element is an list of errors, if any
135
+
136
+ Raises:
137
+ `ValueError`: If an argument is invalid or the server response is malformed
138
+
139
+ `HTTPError`: If the server returned an error
140
+ """
141
+ endpoint = endpoint if endpoint is not None else ENDPOINT
142
+ url_prefix = ""
143
+ if repo_type in REPO_TYPES_URL_PREFIXES:
144
+ url_prefix = REPO_TYPES_URL_PREFIXES[repo_type]
145
+ batch_url = f"{endpoint}/{url_prefix}{repo_id}.git/info/lfs/objects/batch"
146
+ payload: Dict = {
147
+ "operation": "upload",
148
+ "transfers": ["basic", "multipart"],
149
+ "objects": [
150
+ {
151
+ "oid": upload.sha256.hex(),
152
+ "size": upload.size,
153
+ }
154
+ for upload in upload_infos
155
+ ],
156
+ "hash_algo": "sha256",
157
+ }
158
+ if revision is not None:
159
+ payload["ref"] = {"name": unquote(revision)} # revision has been previously 'quoted'
160
+
161
+ headers = {
162
+ **LFS_HEADERS,
163
+ **build_hf_headers(token=token),
164
+ **(headers or {}),
165
+ }
166
+ resp = get_session().post(batch_url, headers=headers, json=payload)
167
+ hf_raise_for_status(resp)
168
+ batch_info = resp.json()
169
+
170
+ objects = batch_info.get("objects", None)
171
+ if not isinstance(objects, list):
172
+ raise ValueError("Malformed response from server")
173
+
174
+ return (
175
+ [_validate_batch_actions(obj) for obj in objects if "error" not in obj],
176
+ [_validate_batch_error(obj) for obj in objects if "error" in obj],
177
+ )
178
+
179
+
180
+ class PayloadPartT(TypedDict):
181
+ partNumber: int
182
+ etag: str
183
+
184
+
185
+ class CompletionPayloadT(TypedDict):
186
+ """Payload that will be sent to the Hub when uploading multi-part."""
187
+
188
+ oid: str
189
+ parts: List[PayloadPartT]
190
+
191
+
192
+ def lfs_upload(
193
+ operation: "CommitOperationAdd",
194
+ lfs_batch_action: Dict,
195
+ token: Optional[str] = None,
196
+ headers: Optional[Dict[str, str]] = None,
197
+ endpoint: Optional[str] = None,
198
+ ) -> None:
199
+ """
200
+ Handles uploading a given object to the Hub with the LFS protocol.
201
+
202
+ Can be a No-op if the content of the file is already present on the hub large file storage.
203
+
204
+ Args:
205
+ operation (`CommitOperationAdd`):
206
+ The add operation triggering this upload.
207
+ lfs_batch_action (`dict`):
208
+ Upload instructions from the LFS batch endpoint for this object. See [`~utils.lfs.post_lfs_batch_info`] for
209
+ more details.
210
+ headers (`dict`, *optional*):
211
+ Headers to include in the request, including authentication and user agent headers.
212
+
213
+ Raises:
214
+ - `ValueError` if `lfs_batch_action` is improperly formatted
215
+ - `HTTPError` if the upload resulted in an error
216
+ """
217
+ # 0. If LFS file is already present, skip upload
218
+ _validate_batch_actions(lfs_batch_action)
219
+ actions = lfs_batch_action.get("actions")
220
+ if actions is None:
221
+ # The file was already uploaded
222
+ logger.debug(f"Content of file {operation.path_in_repo} is already present upstream - skipping upload")
223
+ return
224
+
225
+ # 1. Validate server response (check required keys in dict)
226
+ upload_action = lfs_batch_action["actions"]["upload"]
227
+ _validate_lfs_action(upload_action)
228
+ verify_action = lfs_batch_action["actions"].get("verify")
229
+ if verify_action is not None:
230
+ _validate_lfs_action(verify_action)
231
+
232
+ # 2. Upload file (either single part or multi-part)
233
+ header = upload_action.get("header", {})
234
+ chunk_size = header.get("chunk_size")
235
+ upload_url = fix_hf_endpoint_in_url(upload_action["href"], endpoint=endpoint)
236
+ if chunk_size is not None:
237
+ try:
238
+ chunk_size = int(chunk_size)
239
+ except (ValueError, TypeError):
240
+ raise ValueError(
241
+ f"Malformed response from LFS batch endpoint: `chunk_size` should be an integer. Got '{chunk_size}'."
242
+ )
243
+ _upload_multi_part(operation=operation, header=header, chunk_size=chunk_size, upload_url=upload_url)
244
+ else:
245
+ _upload_single_part(operation=operation, upload_url=upload_url)
246
+
247
+ # 3. Verify upload went well
248
+ if verify_action is not None:
249
+ _validate_lfs_action(verify_action)
250
+ verify_url = fix_hf_endpoint_in_url(verify_action["href"], endpoint)
251
+ verify_resp = get_session().post(
252
+ verify_url,
253
+ headers=build_hf_headers(token=token, headers=headers),
254
+ json={"oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size},
255
+ )
256
+ hf_raise_for_status(verify_resp)
257
+ logger.debug(f"{operation.path_in_repo}: Upload successful")
258
+
259
+
260
+ def _validate_lfs_action(lfs_action: dict):
261
+ """validates response from the LFS batch endpoint"""
262
+ if not (
263
+ isinstance(lfs_action.get("href"), str)
264
+ and (lfs_action.get("header") is None or isinstance(lfs_action.get("header"), dict))
265
+ ):
266
+ raise ValueError("lfs_action is improperly formatted")
267
+ return lfs_action
268
+
269
+
270
+ def _validate_batch_actions(lfs_batch_actions: dict):
271
+ """validates response from the LFS batch endpoint"""
272
+ if not (isinstance(lfs_batch_actions.get("oid"), str) and isinstance(lfs_batch_actions.get("size"), int)):
273
+ raise ValueError("lfs_batch_actions is improperly formatted")
274
+
275
+ upload_action = lfs_batch_actions.get("actions", {}).get("upload")
276
+ verify_action = lfs_batch_actions.get("actions", {}).get("verify")
277
+ if upload_action is not None:
278
+ _validate_lfs_action(upload_action)
279
+ if verify_action is not None:
280
+ _validate_lfs_action(verify_action)
281
+ return lfs_batch_actions
282
+
283
+
284
+ def _validate_batch_error(lfs_batch_error: dict):
285
+ """validates response from the LFS batch endpoint"""
286
+ if not (isinstance(lfs_batch_error.get("oid"), str) and isinstance(lfs_batch_error.get("size"), int)):
287
+ raise ValueError("lfs_batch_error is improperly formatted")
288
+ error_info = lfs_batch_error.get("error")
289
+ if not (
290
+ isinstance(error_info, dict)
291
+ and isinstance(error_info.get("message"), str)
292
+ and isinstance(error_info.get("code"), int)
293
+ ):
294
+ raise ValueError("lfs_batch_error is improperly formatted")
295
+ return lfs_batch_error
296
+
297
+
298
+ def _upload_single_part(operation: "CommitOperationAdd", upload_url: str) -> None:
299
+ """
300
+ Uploads `fileobj` as a single PUT HTTP request (basic LFS transfer protocol)
301
+
302
+ Args:
303
+ upload_url (`str`):
304
+ The URL to PUT the file to.
305
+ fileobj:
306
+ The file-like object holding the data to upload.
307
+
308
+ Returns: `requests.Response`
309
+
310
+ Raises: `requests.HTTPError` if the upload resulted in an error
311
+ """
312
+ with operation.as_file(with_tqdm=True) as fileobj:
313
+ # S3 might raise a transient 500 error -> let's retry if that happens
314
+ response = http_backoff("PUT", upload_url, data=fileobj, retry_on_status_codes=(500, 502, 503, 504))
315
+ hf_raise_for_status(response)
316
+
317
+
318
+ def _upload_multi_part(operation: "CommitOperationAdd", header: Dict, chunk_size: int, upload_url: str) -> None:
319
+ """
320
+ Uploads file using HF multipart LFS transfer protocol.
321
+ """
322
+ # 1. Get upload URLs for each part
323
+ sorted_parts_urls = _get_sorted_parts_urls(header=header, upload_info=operation.upload_info, chunk_size=chunk_size)
324
+
325
+ # 2. Upload parts (either with hf_transfer or in pure Python)
326
+ use_hf_transfer = HF_HUB_ENABLE_HF_TRANSFER
327
+ if (
328
+ HF_HUB_ENABLE_HF_TRANSFER
329
+ and not isinstance(operation.path_or_fileobj, str)
330
+ and not isinstance(operation.path_or_fileobj, Path)
331
+ ):
332
+ warnings.warn(
333
+ "hf_transfer is enabled but does not support uploading from bytes or BinaryIO, falling back to regular"
334
+ " upload"
335
+ )
336
+ use_hf_transfer = False
337
+
338
+ response_headers = (
339
+ _upload_parts_hf_transfer(operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size)
340
+ if use_hf_transfer
341
+ else _upload_parts_iteratively(operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size)
342
+ )
343
+
344
+ # 3. Send completion request
345
+ completion_res = get_session().post(
346
+ upload_url,
347
+ json=_get_completion_payload(response_headers, operation.upload_info.sha256.hex()),
348
+ headers=LFS_HEADERS,
349
+ )
350
+ hf_raise_for_status(completion_res)
351
+
352
+
353
+ def _get_sorted_parts_urls(header: Dict, upload_info: UploadInfo, chunk_size: int) -> List[str]:
354
+ sorted_part_upload_urls = [
355
+ upload_url
356
+ for _, upload_url in sorted(
357
+ [
358
+ (int(part_num, 10), upload_url)
359
+ for part_num, upload_url in header.items()
360
+ if part_num.isdigit() and len(part_num) > 0
361
+ ],
362
+ key=lambda t: t[0],
363
+ )
364
+ ]
365
+ num_parts = len(sorted_part_upload_urls)
366
+ if num_parts != ceil(upload_info.size / chunk_size):
367
+ raise ValueError("Invalid server response to upload large LFS file")
368
+ return sorted_part_upload_urls
369
+
370
+
371
+ def _get_completion_payload(response_headers: List[Dict], oid: str) -> CompletionPayloadT:
372
+ parts: List[PayloadPartT] = []
373
+ for part_number, header in enumerate(response_headers):
374
+ etag = header.get("etag")
375
+ if etag is None or etag == "":
376
+ raise ValueError(f"Invalid etag (`{etag}`) returned for part {part_number + 1}")
377
+ parts.append(
378
+ {
379
+ "partNumber": part_number + 1,
380
+ "etag": etag,
381
+ }
382
+ )
383
+ return {"oid": oid, "parts": parts}
384
+
385
+
386
+ def _upload_parts_iteratively(
387
+ operation: "CommitOperationAdd", sorted_parts_urls: List[str], chunk_size: int
388
+ ) -> List[Dict]:
389
+ headers = []
390
+ with operation.as_file(with_tqdm=True) as fileobj:
391
+ for part_idx, part_upload_url in enumerate(sorted_parts_urls):
392
+ with SliceFileObj(
393
+ fileobj,
394
+ seek_from=chunk_size * part_idx,
395
+ read_limit=chunk_size,
396
+ ) as fileobj_slice:
397
+ # S3 might raise a transient 500 error -> let's retry if that happens
398
+ part_upload_res = http_backoff(
399
+ "PUT", part_upload_url, data=fileobj_slice, retry_on_status_codes=(500, 502, 503, 504)
400
+ )
401
+ hf_raise_for_status(part_upload_res)
402
+ headers.append(part_upload_res.headers)
403
+ return headers # type: ignore
404
+
405
+
406
+ def _upload_parts_hf_transfer(
407
+ operation: "CommitOperationAdd", sorted_parts_urls: List[str], chunk_size: int
408
+ ) -> List[Dict]:
409
+ # Upload file using an external Rust-based package. Upload is faster but support less features (no progress bars).
410
+ try:
411
+ from hf_transfer import multipart_upload
412
+ except ImportError:
413
+ raise ValueError(
414
+ "Fast uploading using 'hf_transfer' is enabled (HF_HUB_ENABLE_HF_TRANSFER=1) but 'hf_transfer' package is"
415
+ " not available in your environment. Try `pip install hf_transfer`."
416
+ )
417
+
418
+ supports_callback = "callback" in inspect.signature(multipart_upload).parameters
419
+ if not supports_callback:
420
+ warnings.warn(
421
+ "You are using an outdated version of `hf_transfer`. Consider upgrading to latest version to enable progress bars using `pip install -U hf_transfer`."
422
+ )
423
+
424
+ total = operation.upload_info.size
425
+ desc = operation.path_in_repo
426
+ if len(desc) > 40:
427
+ desc = f"(…){desc[-40:]}"
428
+
429
+ # set `disable=None` rather than `disable=False` by default to disable progress bar when no TTY attached
430
+ # see https://github.com/huggingface/huggingface_hub/pull/2000
431
+ disable = True if (logger.getEffectiveLevel() == logging.NOTSET) else None
432
+
433
+ with tqdm(unit="B", unit_scale=True, total=total, initial=0, desc=desc, disable=disable) as progress:
434
+ try:
435
+ output = multipart_upload(
436
+ file_path=operation.path_or_fileobj,
437
+ parts_urls=sorted_parts_urls,
438
+ chunk_size=chunk_size,
439
+ max_files=128,
440
+ parallel_failures=127, # could be removed
441
+ max_retries=5,
442
+ **({"callback": progress.update} if supports_callback else {}),
443
+ )
444
+ except Exception as e:
445
+ raise RuntimeError(
446
+ "An error occurred while uploading using `hf_transfer`. Consider disabling HF_HUB_ENABLE_HF_TRANSFER for"
447
+ " better error handling."
448
+ ) from e
449
+ if not supports_callback:
450
+ progress.update(total)
451
+ return output
452
+
453
+
454
+ class SliceFileObj(AbstractContextManager):
455
+ """
456
+ Utility context manager to read a *slice* of a seekable file-like object as a seekable, file-like object.
457
+
458
+ This is NOT thread safe
459
+
460
+ Inspired by stackoverflow.com/a/29838711/593036
461
+
462
+ Credits to @julien-c
463
+
464
+ Args:
465
+ fileobj (`BinaryIO`):
466
+ A file-like object to slice. MUST implement `tell()` and `seek()` (and `read()` of course).
467
+ `fileobj` will be reset to its original position when exiting the context manager.
468
+ seek_from (`int`):
469
+ The start of the slice (offset from position 0 in bytes).
470
+ read_limit (`int`):
471
+ The maximum number of bytes to read from the slice.
472
+
473
+ Attributes:
474
+ previous_position (`int`):
475
+ The previous position
476
+
477
+ Examples:
478
+
479
+ Reading 200 bytes with an offset of 128 bytes from a file (ie bytes 128 to 327):
480
+ ```python
481
+ >>> with open("path/to/file", "rb") as file:
482
+ ... with SliceFileObj(file, seek_from=128, read_limit=200) as fslice:
483
+ ... fslice.read(...)
484
+ ```
485
+
486
+ Reading a file in chunks of 512 bytes
487
+ ```python
488
+ >>> import os
489
+ >>> chunk_size = 512
490
+ >>> file_size = os.getsize("path/to/file")
491
+ >>> with open("path/to/file", "rb") as file:
492
+ ... for chunk_idx in range(ceil(file_size / chunk_size)):
493
+ ... with SliceFileObj(file, seek_from=chunk_idx * chunk_size, read_limit=chunk_size) as fslice:
494
+ ... chunk = fslice.read(...)
495
+
496
+ ```
497
+ """
498
+
499
+ def __init__(self, fileobj: BinaryIO, seek_from: int, read_limit: int):
500
+ self.fileobj = fileobj
501
+ self.seek_from = seek_from
502
+ self.read_limit = read_limit
503
+
504
+ def __enter__(self):
505
+ self._previous_position = self.fileobj.tell()
506
+ end_of_stream = self.fileobj.seek(0, os.SEEK_END)
507
+ self._len = min(self.read_limit, end_of_stream - self.seek_from)
508
+ # ^^ The actual number of bytes that can be read from the slice
509
+ self.fileobj.seek(self.seek_from, io.SEEK_SET)
510
+ return self
511
+
512
+ def __exit__(self, exc_type, exc_value, traceback):
513
+ self.fileobj.seek(self._previous_position, io.SEEK_SET)
514
+
515
+ def read(self, n: int = -1):
516
+ pos = self.tell()
517
+ if pos >= self._len:
518
+ return b""
519
+ remaining_amount = self._len - pos
520
+ data = self.fileobj.read(remaining_amount if n < 0 else min(n, remaining_amount))
521
+ return data
522
+
523
+ def tell(self) -> int:
524
+ return self.fileobj.tell() - self.seek_from
525
+
526
+ def seek(self, offset: int, whence: int = os.SEEK_SET) -> int:
527
+ start = self.seek_from
528
+ end = start + self._len
529
+ if whence in (os.SEEK_SET, os.SEEK_END):
530
+ offset = start + offset if whence == os.SEEK_SET else end + offset
531
+ offset = max(start, min(offset, end))
532
+ whence = os.SEEK_SET
533
+ elif whence == os.SEEK_CUR:
534
+ cur_pos = self.fileobj.tell()
535
+ offset = max(start - cur_pos, min(offset, end - cur_pos))
536
+ else:
537
+ raise ValueError(f"whence value {whence} is not supported")
538
+ return self.fileobj.seek(offset, whence) - self.seek_from
539
+
540
+ def __iter__(self):
541
+ yield self.read(n=4 * 1024 * 1024)
env-llmeval/lib/python3.10/site-packages/huggingface_hub/repocard.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from pathlib import Path
4
+ from typing import Any, Dict, Literal, Optional, Type, Union
5
+
6
+ import requests
7
+ import yaml
8
+
9
+ from huggingface_hub.file_download import hf_hub_download
10
+ from huggingface_hub.hf_api import upload_file
11
+ from huggingface_hub.repocard_data import (
12
+ CardData,
13
+ DatasetCardData,
14
+ EvalResult,
15
+ ModelCardData,
16
+ SpaceCardData,
17
+ eval_results_to_model_index,
18
+ model_index_to_eval_results,
19
+ )
20
+ from huggingface_hub.utils import get_session, is_jinja_available, yaml_dump
21
+
22
+ from .constants import REPOCARD_NAME
23
+ from .utils import EntryNotFoundError, SoftTemporaryDirectory, logging, validate_hf_hub_args
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ TEMPLATE_MODELCARD_PATH = Path(__file__).parent / "templates" / "modelcard_template.md"
30
+ TEMPLATE_DATASETCARD_PATH = Path(__file__).parent / "templates" / "datasetcard_template.md"
31
+
32
+ # exact same regex as in the Hub server. Please keep in sync.
33
+ # See https://github.com/huggingface/moon-landing/blob/main/server/lib/ViewMarkdown.ts#L18
34
+ REGEX_YAML_BLOCK = re.compile(r"^(\s*---[\r\n]+)([\S\s]*?)([\r\n]+---(\r\n|\n|$))")
35
+
36
+
37
+ class RepoCard:
38
+ card_data_class = CardData
39
+ default_template_path = TEMPLATE_MODELCARD_PATH
40
+ repo_type = "model"
41
+
42
+ def __init__(self, content: str, ignore_metadata_errors: bool = False):
43
+ """Initialize a RepoCard from string content. The content should be a
44
+ Markdown file with a YAML block at the beginning and a Markdown body.
45
+
46
+ Args:
47
+ content (`str`): The content of the Markdown file.
48
+
49
+ Example:
50
+ ```python
51
+ >>> from huggingface_hub.repocard import RepoCard
52
+ >>> text = '''
53
+ ... ---
54
+ ... language: en
55
+ ... license: mit
56
+ ... ---
57
+ ...
58
+ ... # My repo
59
+ ... '''
60
+ >>> card = RepoCard(text)
61
+ >>> card.data.to_dict()
62
+ {'language': 'en', 'license': 'mit'}
63
+ >>> card.text
64
+ '\\n# My repo\\n'
65
+
66
+ ```
67
+ <Tip>
68
+ Raises the following error:
69
+
70
+ - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
71
+ when the content of the repo card metadata is not a dictionary.
72
+
73
+ </Tip>
74
+ """
75
+
76
+ # Set the content of the RepoCard, as well as underlying .data and .text attributes.
77
+ # See the `content` property setter for more details.
78
+ self.ignore_metadata_errors = ignore_metadata_errors
79
+ self.content = content
80
+
81
+ @property
82
+ def content(self):
83
+ """The content of the RepoCard, including the YAML block and the Markdown body."""
84
+ line_break = _detect_line_ending(self._content) or "\n"
85
+ return f"---{line_break}{self.data.to_yaml(line_break=line_break)}{line_break}---{line_break}{self.text}"
86
+
87
+ @content.setter
88
+ def content(self, content: str):
89
+ """Set the content of the RepoCard."""
90
+ self._content = content
91
+
92
+ match = REGEX_YAML_BLOCK.search(content)
93
+ if match:
94
+ # Metadata found in the YAML block
95
+ yaml_block = match.group(2)
96
+ self.text = content[match.end() :]
97
+ data_dict = yaml.safe_load(yaml_block)
98
+
99
+ if data_dict is None:
100
+ data_dict = {}
101
+
102
+ # The YAML block's data should be a dictionary
103
+ if not isinstance(data_dict, dict):
104
+ raise ValueError("repo card metadata block should be a dict")
105
+ else:
106
+ # Model card without metadata... create empty metadata
107
+ logger.warning("Repo card metadata block was not found. Setting CardData to empty.")
108
+ data_dict = {}
109
+ self.text = content
110
+
111
+ self.data = self.card_data_class(**data_dict, ignore_metadata_errors=self.ignore_metadata_errors)
112
+
113
+ def __str__(self):
114
+ return self.content
115
+
116
+ def save(self, filepath: Union[Path, str]):
117
+ r"""Save a RepoCard to a file.
118
+
119
+ Args:
120
+ filepath (`Union[Path, str]`): Filepath to the markdown file to save.
121
+
122
+ Example:
123
+ ```python
124
+ >>> from huggingface_hub.repocard import RepoCard
125
+ >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
126
+ >>> card.save("/tmp/test.md")
127
+
128
+ ```
129
+ """
130
+ filepath = Path(filepath)
131
+ filepath.parent.mkdir(parents=True, exist_ok=True)
132
+ # Preserve newlines as in the existing file.
133
+ with open(filepath, mode="w", newline="", encoding="utf-8") as f:
134
+ f.write(str(self))
135
+
136
+ @classmethod
137
+ def load(
138
+ cls,
139
+ repo_id_or_path: Union[str, Path],
140
+ repo_type: Optional[str] = None,
141
+ token: Optional[str] = None,
142
+ ignore_metadata_errors: bool = False,
143
+ ):
144
+ """Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath.
145
+
146
+ Args:
147
+ repo_id_or_path (`Union[str, Path]`):
148
+ The repo ID associated with a Hugging Face Hub repo or a local filepath.
149
+ repo_type (`str`, *optional*):
150
+ The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options
151
+ are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child
152
+ class, the default value will be the child class's `repo_type`.
153
+ token (`str`, *optional*):
154
+ Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
155
+ ignore_metadata_errors (`str`):
156
+ If True, errors while parsing the metadata section will be ignored. Some information might be lost during
157
+ the process. Use it at your own risk.
158
+
159
+ Returns:
160
+ [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's
161
+ README.md file or filepath.
162
+
163
+ Example:
164
+ ```python
165
+ >>> from huggingface_hub.repocard import RepoCard
166
+ >>> card = RepoCard.load("nateraw/food")
167
+ >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]
168
+
169
+ ```
170
+ """
171
+
172
+ if Path(repo_id_or_path).exists():
173
+ card_path = Path(repo_id_or_path)
174
+ elif isinstance(repo_id_or_path, str):
175
+ card_path = Path(
176
+ hf_hub_download(
177
+ repo_id_or_path,
178
+ REPOCARD_NAME,
179
+ repo_type=repo_type or cls.repo_type,
180
+ token=token,
181
+ )
182
+ )
183
+ else:
184
+ raise ValueError(f"Cannot load RepoCard: path not found on disk ({repo_id_or_path}).")
185
+
186
+ # Preserve newlines in the existing file.
187
+ with card_path.open(mode="r", newline="", encoding="utf-8") as f:
188
+ return cls(f.read(), ignore_metadata_errors=ignore_metadata_errors)
189
+
190
+ def validate(self, repo_type: Optional[str] = None):
191
+ """Validates card against Hugging Face Hub's card validation logic.
192
+ Using this function requires access to the internet, so it is only called
193
+ internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`].
194
+
195
+ Args:
196
+ repo_type (`str`, *optional*, defaults to "model"):
197
+ The type of Hugging Face repo to push to. Options are "model", "dataset", and "space".
198
+ If this function is called from a child class, the default will be the child class's `repo_type`.
199
+
200
+ <Tip>
201
+ Raises the following errors:
202
+
203
+ - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
204
+ if the card fails validation checks.
205
+ - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
206
+ if the request to the Hub API fails for any other reason.
207
+
208
+ </Tip>
209
+ """
210
+
211
+ # If repo type is provided, otherwise, use the repo type of the card.
212
+ repo_type = repo_type or self.repo_type
213
+
214
+ body = {
215
+ "repoType": repo_type,
216
+ "content": str(self),
217
+ }
218
+ headers = {"Accept": "text/plain"}
219
+
220
+ try:
221
+ r = get_session().post("https://huggingface.co/api/validate-yaml", body, headers=headers)
222
+ r.raise_for_status()
223
+ except requests.exceptions.HTTPError as exc:
224
+ if r.status_code == 400:
225
+ raise ValueError(r.text)
226
+ else:
227
+ raise exc
228
+
229
+ def push_to_hub(
230
+ self,
231
+ repo_id: str,
232
+ token: Optional[str] = None,
233
+ repo_type: Optional[str] = None,
234
+ commit_message: Optional[str] = None,
235
+ commit_description: Optional[str] = None,
236
+ revision: Optional[str] = None,
237
+ create_pr: Optional[bool] = None,
238
+ parent_commit: Optional[str] = None,
239
+ ):
240
+ """Push a RepoCard to a Hugging Face Hub repo.
241
+
242
+ Args:
243
+ repo_id (`str`):
244
+ The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food".
245
+ token (`str`, *optional*):
246
+ Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to
247
+ the stored token.
248
+ repo_type (`str`, *optional*, defaults to "model"):
249
+ The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this
250
+ function is called by a child class, it will default to the child class's `repo_type`.
251
+ commit_message (`str`, *optional*):
252
+ The summary / title / first line of the generated commit.
253
+ commit_description (`str`, *optional*)
254
+ The description of the generated commit.
255
+ revision (`str`, *optional*):
256
+ The git revision to commit from. Defaults to the head of the `"main"` branch.
257
+ create_pr (`bool`, *optional*):
258
+ Whether or not to create a Pull Request with this commit. Defaults to `False`.
259
+ parent_commit (`str`, *optional*):
260
+ The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
261
+ If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
262
+ If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
263
+ Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
264
+ especially useful if the repo is updated / committed to concurrently.
265
+ Returns:
266
+ `str`: URL of the commit which updated the card metadata.
267
+ """
268
+
269
+ # If repo type is provided, otherwise, use the repo type of the card.
270
+ repo_type = repo_type or self.repo_type
271
+
272
+ # Validate card before pushing to hub
273
+ self.validate(repo_type=repo_type)
274
+
275
+ with SoftTemporaryDirectory() as tmpdir:
276
+ tmp_path = Path(tmpdir) / REPOCARD_NAME
277
+ tmp_path.write_text(str(self))
278
+ url = upload_file(
279
+ path_or_fileobj=str(tmp_path),
280
+ path_in_repo=REPOCARD_NAME,
281
+ repo_id=repo_id,
282
+ token=token,
283
+ repo_type=repo_type,
284
+ commit_message=commit_message,
285
+ commit_description=commit_description,
286
+ create_pr=create_pr,
287
+ revision=revision,
288
+ parent_commit=parent_commit,
289
+ )
290
+ return url
291
+
292
+ @classmethod
293
+ def from_template(
294
+ cls,
295
+ card_data: CardData,
296
+ template_path: Optional[str] = None,
297
+ template_str: Optional[str] = None,
298
+ **template_kwargs,
299
+ ):
300
+ """Initialize a RepoCard from a template. By default, it uses the default template.
301
+
302
+ Templates are Jinja2 templates that can be customized by passing keyword arguments.
303
+
304
+ Args:
305
+ card_data (`huggingface_hub.CardData`):
306
+ A huggingface_hub.CardData instance containing the metadata you want to include in the YAML
307
+ header of the repo card on the Hugging Face Hub.
308
+ template_path (`str`, *optional*):
309
+ A path to a markdown file with optional Jinja template variables that can be filled
310
+ in with `template_kwargs`. Defaults to the default template.
311
+
312
+ Returns:
313
+ [`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the
314
+ template.
315
+ """
316
+ if is_jinja_available():
317
+ import jinja2
318
+ else:
319
+ raise ImportError(
320
+ "Using RepoCard.from_template requires Jinja2 to be installed. Please"
321
+ " install it with `pip install Jinja2`."
322
+ )
323
+
324
+ kwargs = card_data.to_dict().copy()
325
+ kwargs.update(template_kwargs) # Template_kwargs have priority
326
+
327
+ if template_path is not None:
328
+ template_str = Path(template_path).read_text()
329
+ if template_str is None:
330
+ template_str = Path(cls.default_template_path).read_text()
331
+ template = jinja2.Template(template_str)
332
+ content = template.render(card_data=card_data.to_yaml(), **kwargs)
333
+ return cls(content)
334
+
335
+
336
+ class ModelCard(RepoCard):
337
+ card_data_class = ModelCardData
338
+ default_template_path = TEMPLATE_MODELCARD_PATH
339
+ repo_type = "model"
340
+
341
+ @classmethod
342
+ def from_template( # type: ignore # violates Liskov property but easier to use
343
+ cls,
344
+ card_data: ModelCardData,
345
+ template_path: Optional[str] = None,
346
+ template_str: Optional[str] = None,
347
+ **template_kwargs,
348
+ ):
349
+ """Initialize a ModelCard from a template. By default, it uses the default template, which can be found here:
350
+ https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md
351
+
352
+ Templates are Jinja2 templates that can be customized by passing keyword arguments.
353
+
354
+ Args:
355
+ card_data (`huggingface_hub.ModelCardData`):
356
+ A huggingface_hub.ModelCardData instance containing the metadata you want to include in the YAML
357
+ header of the model card on the Hugging Face Hub.
358
+ template_path (`str`, *optional*):
359
+ A path to a markdown file with optional Jinja template variables that can be filled
360
+ in with `template_kwargs`. Defaults to the default template.
361
+
362
+ Returns:
363
+ [`huggingface_hub.ModelCard`]: A ModelCard instance with the specified card data and content from the
364
+ template.
365
+
366
+ Example:
367
+ ```python
368
+ >>> from huggingface_hub import ModelCard, ModelCardData, EvalResult
369
+
370
+ >>> # Using the Default Template
371
+ >>> card_data = ModelCardData(
372
+ ... language='en',
373
+ ... license='mit',
374
+ ... library_name='timm',
375
+ ... tags=['image-classification', 'resnet'],
376
+ ... datasets=['beans'],
377
+ ... metrics=['accuracy'],
378
+ ... )
379
+ >>> card = ModelCard.from_template(
380
+ ... card_data,
381
+ ... model_description='This model does x + y...'
382
+ ... )
383
+
384
+ >>> # Including Evaluation Results
385
+ >>> card_data = ModelCardData(
386
+ ... language='en',
387
+ ... tags=['image-classification', 'resnet'],
388
+ ... eval_results=[
389
+ ... EvalResult(
390
+ ... task_type='image-classification',
391
+ ... dataset_type='beans',
392
+ ... dataset_name='Beans',
393
+ ... metric_type='accuracy',
394
+ ... metric_value=0.9,
395
+ ... ),
396
+ ... ],
397
+ ... model_name='my-cool-model',
398
+ ... )
399
+ >>> card = ModelCard.from_template(card_data)
400
+
401
+ >>> # Using a Custom Template
402
+ >>> card_data = ModelCardData(
403
+ ... language='en',
404
+ ... tags=['image-classification', 'resnet']
405
+ ... )
406
+ >>> card = ModelCard.from_template(
407
+ ... card_data=card_data,
408
+ ... template_path='./src/huggingface_hub/templates/modelcard_template.md',
409
+ ... custom_template_var='custom value', # will be replaced in template if it exists
410
+ ... )
411
+
412
+ ```
413
+ """
414
+ return super().from_template(card_data, template_path, template_str, **template_kwargs)
415
+
416
+
417
+ class DatasetCard(RepoCard):
418
+ card_data_class = DatasetCardData
419
+ default_template_path = TEMPLATE_DATASETCARD_PATH
420
+ repo_type = "dataset"
421
+
422
+ @classmethod
423
+ def from_template( # type: ignore # violates Liskov property but easier to use
424
+ cls,
425
+ card_data: DatasetCardData,
426
+ template_path: Optional[str] = None,
427
+ template_str: Optional[str] = None,
428
+ **template_kwargs,
429
+ ):
430
+ """Initialize a DatasetCard from a template. By default, it uses the default template, which can be found here:
431
+ https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md
432
+
433
+ Templates are Jinja2 templates that can be customized by passing keyword arguments.
434
+
435
+ Args:
436
+ card_data (`huggingface_hub.DatasetCardData`):
437
+ A huggingface_hub.DatasetCardData instance containing the metadata you want to include in the YAML
438
+ header of the dataset card on the Hugging Face Hub.
439
+ template_path (`str`, *optional*):
440
+ A path to a markdown file with optional Jinja template variables that can be filled
441
+ in with `template_kwargs`. Defaults to the default template.
442
+
443
+ Returns:
444
+ [`huggingface_hub.DatasetCard`]: A DatasetCard instance with the specified card data and content from the
445
+ template.
446
+
447
+ Example:
448
+ ```python
449
+ >>> from huggingface_hub import DatasetCard, DatasetCardData
450
+
451
+ >>> # Using the Default Template
452
+ >>> card_data = DatasetCardData(
453
+ ... language='en',
454
+ ... license='mit',
455
+ ... annotations_creators='crowdsourced',
456
+ ... task_categories=['text-classification'],
457
+ ... task_ids=['sentiment-classification', 'text-scoring'],
458
+ ... multilinguality='monolingual',
459
+ ... pretty_name='My Text Classification Dataset',
460
+ ... )
461
+ >>> card = DatasetCard.from_template(
462
+ ... card_data,
463
+ ... pretty_name=card_data.pretty_name,
464
+ ... )
465
+
466
+ >>> # Using a Custom Template
467
+ >>> card_data = DatasetCardData(
468
+ ... language='en',
469
+ ... license='mit',
470
+ ... )
471
+ >>> card = DatasetCard.from_template(
472
+ ... card_data=card_data,
473
+ ... template_path='./src/huggingface_hub/templates/datasetcard_template.md',
474
+ ... custom_template_var='custom value', # will be replaced in template if it exists
475
+ ... )
476
+
477
+ ```
478
+ """
479
+ return super().from_template(card_data, template_path, template_str, **template_kwargs)
480
+
481
+
482
+ class SpaceCard(RepoCard):
483
+ card_data_class = SpaceCardData
484
+ default_template_path = TEMPLATE_MODELCARD_PATH
485
+ repo_type = "space"
486
+
487
+
488
+ def _detect_line_ending(content: str) -> Literal["\r", "\n", "\r\n", None]: # noqa: F722
489
+ """Detect the line ending of a string. Used by RepoCard to avoid making huge diff on newlines.
490
+
491
+ Uses same implementation as in Hub server, keep it in sync.
492
+
493
+ Returns:
494
+ str: The detected line ending of the string.
495
+ """
496
+ cr = content.count("\r")
497
+ lf = content.count("\n")
498
+ crlf = content.count("\r\n")
499
+ if cr + lf == 0:
500
+ return None
501
+ if crlf == cr and crlf == lf:
502
+ return "\r\n"
503
+ if cr > lf:
504
+ return "\r"
505
+ else:
506
+ return "\n"
507
+
508
+
509
+ def metadata_load(local_path: Union[str, Path]) -> Optional[Dict]:
510
+ content = Path(local_path).read_text()
511
+ match = REGEX_YAML_BLOCK.search(content)
512
+ if match:
513
+ yaml_block = match.group(2)
514
+ data = yaml.safe_load(yaml_block)
515
+ if data is None or isinstance(data, dict):
516
+ return data
517
+ raise ValueError("repo card metadata block should be a dict")
518
+ else:
519
+ return None
520
+
521
+
522
+ def metadata_save(local_path: Union[str, Path], data: Dict) -> None:
523
+ """
524
+ Save the metadata dict in the upper YAML part Trying to preserve newlines as
525
+ in the existing file. Docs about open() with newline="" parameter:
526
+ https://docs.python.org/3/library/functions.html?highlight=open#open Does
527
+ not work with "^M" linebreaks, which are replaced by \n
528
+ """
529
+ line_break = "\n"
530
+ content = ""
531
+ # try to detect existing newline character
532
+ if os.path.exists(local_path):
533
+ with open(local_path, "r", newline="", encoding="utf8") as readme:
534
+ content = readme.read()
535
+ if isinstance(readme.newlines, tuple):
536
+ line_break = readme.newlines[0]
537
+ elif isinstance(readme.newlines, str):
538
+ line_break = readme.newlines
539
+
540
+ # creates a new file if it not
541
+ with open(local_path, "w", newline="", encoding="utf8") as readme:
542
+ data_yaml = yaml_dump(data, sort_keys=False, line_break=line_break)
543
+ # sort_keys: keep dict order
544
+ match = REGEX_YAML_BLOCK.search(content)
545
+ if match:
546
+ output = content[: match.start()] + f"---{line_break}{data_yaml}---{line_break}" + content[match.end() :]
547
+ else:
548
+ output = f"---{line_break}{data_yaml}---{line_break}{content}"
549
+
550
+ readme.write(output)
551
+ readme.close()
552
+
553
+
554
+ def metadata_eval_result(
555
+ *,
556
+ model_pretty_name: str,
557
+ task_pretty_name: str,
558
+ task_id: str,
559
+ metrics_pretty_name: str,
560
+ metrics_id: str,
561
+ metrics_value: Any,
562
+ dataset_pretty_name: str,
563
+ dataset_id: str,
564
+ metrics_config: Optional[str] = None,
565
+ metrics_verified: bool = False,
566
+ dataset_config: Optional[str] = None,
567
+ dataset_split: Optional[str] = None,
568
+ dataset_revision: Optional[str] = None,
569
+ metrics_verification_token: Optional[str] = None,
570
+ ) -> Dict:
571
+ """
572
+ Creates a metadata dict with the result from a model evaluated on a dataset.
573
+
574
+ Args:
575
+ model_pretty_name (`str`):
576
+ The name of the model in natural language.
577
+ task_pretty_name (`str`):
578
+ The name of a task in natural language.
579
+ task_id (`str`):
580
+ Example: automatic-speech-recognition. A task id.
581
+ metrics_pretty_name (`str`):
582
+ A name for the metric in natural language. Example: Test WER.
583
+ metrics_id (`str`):
584
+ Example: wer. A metric id from https://hf.co/metrics.
585
+ metrics_value (`Any`):
586
+ The value from the metric. Example: 20.0 or "20.0 ± 1.2".
587
+ dataset_pretty_name (`str`):
588
+ The name of the dataset in natural language.
589
+ dataset_id (`str`):
590
+ Example: common_voice. A dataset id from https://hf.co/datasets.
591
+ metrics_config (`str`, *optional*):
592
+ The name of the metric configuration used in `load_metric()`.
593
+ Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
594
+ metrics_verified (`bool`, *optional*, defaults to `False`):
595
+ Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
596
+ dataset_config (`str`, *optional*):
597
+ Example: fr. The name of the dataset configuration used in `load_dataset()`.
598
+ dataset_split (`str`, *optional*):
599
+ Example: test. The name of the dataset split used in `load_dataset()`.
600
+ dataset_revision (`str`, *optional*):
601
+ Example: 5503434ddd753f426f4b38109466949a1217c2bb. The name of the dataset dataset revision
602
+ used in `load_dataset()`.
603
+ metrics_verification_token (`bool`, *optional*):
604
+ A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
605
+
606
+ Returns:
607
+ `dict`: a metadata dict with the result from a model evaluated on a dataset.
608
+
609
+ Example:
610
+ ```python
611
+ >>> from huggingface_hub import metadata_eval_result
612
+ >>> results = metadata_eval_result(
613
+ ... model_pretty_name="RoBERTa fine-tuned on ReactionGIF",
614
+ ... task_pretty_name="Text Classification",
615
+ ... task_id="text-classification",
616
+ ... metrics_pretty_name="Accuracy",
617
+ ... metrics_id="accuracy",
618
+ ... metrics_value=0.2662102282047272,
619
+ ... dataset_pretty_name="ReactionJPEG",
620
+ ... dataset_id="julien-c/reactionjpeg",
621
+ ... dataset_config="default",
622
+ ... dataset_split="test",
623
+ ... )
624
+ >>> results == {
625
+ ... 'model-index': [
626
+ ... {
627
+ ... 'name': 'RoBERTa fine-tuned on ReactionGIF',
628
+ ... 'results': [
629
+ ... {
630
+ ... 'task': {
631
+ ... 'type': 'text-classification',
632
+ ... 'name': 'Text Classification'
633
+ ... },
634
+ ... 'dataset': {
635
+ ... 'name': 'ReactionJPEG',
636
+ ... 'type': 'julien-c/reactionjpeg',
637
+ ... 'config': 'default',
638
+ ... 'split': 'test'
639
+ ... },
640
+ ... 'metrics': [
641
+ ... {
642
+ ... 'type': 'accuracy',
643
+ ... 'value': 0.2662102282047272,
644
+ ... 'name': 'Accuracy',
645
+ ... 'verified': False
646
+ ... }
647
+ ... ]
648
+ ... }
649
+ ... ]
650
+ ... }
651
+ ... ]
652
+ ... }
653
+ True
654
+
655
+ ```
656
+ """
657
+
658
+ return {
659
+ "model-index": eval_results_to_model_index(
660
+ model_name=model_pretty_name,
661
+ eval_results=[
662
+ EvalResult(
663
+ task_name=task_pretty_name,
664
+ task_type=task_id,
665
+ metric_name=metrics_pretty_name,
666
+ metric_type=metrics_id,
667
+ metric_value=metrics_value,
668
+ dataset_name=dataset_pretty_name,
669
+ dataset_type=dataset_id,
670
+ metric_config=metrics_config,
671
+ verified=metrics_verified,
672
+ verify_token=metrics_verification_token,
673
+ dataset_config=dataset_config,
674
+ dataset_split=dataset_split,
675
+ dataset_revision=dataset_revision,
676
+ )
677
+ ],
678
+ )
679
+ }
680
+
681
+
682
+ @validate_hf_hub_args
683
+ def metadata_update(
684
+ repo_id: str,
685
+ metadata: Dict,
686
+ *,
687
+ repo_type: Optional[str] = None,
688
+ overwrite: bool = False,
689
+ token: Optional[str] = None,
690
+ commit_message: Optional[str] = None,
691
+ commit_description: Optional[str] = None,
692
+ revision: Optional[str] = None,
693
+ create_pr: bool = False,
694
+ parent_commit: Optional[str] = None,
695
+ ) -> str:
696
+ """
697
+ Updates the metadata in the README.md of a repository on the Hugging Face Hub.
698
+ If the README.md file doesn't exist yet, a new one is created with metadata and an
699
+ the default ModelCard or DatasetCard template. For `space` repo, an error is thrown
700
+ as a Space cannot exist without a `README.md` file.
701
+
702
+ Args:
703
+ repo_id (`str`):
704
+ The name of the repository.
705
+ metadata (`dict`):
706
+ A dictionary containing the metadata to be updated.
707
+ repo_type (`str`, *optional*):
708
+ Set to `"dataset"` or `"space"` if updating to a dataset or space,
709
+ `None` or `"model"` if updating to a model. Default is `None`.
710
+ overwrite (`bool`, *optional*, defaults to `False`):
711
+ If set to `True` an existing field can be overwritten, otherwise
712
+ attempting to overwrite an existing field will cause an error.
713
+ token (`str`, *optional*):
714
+ The Hugging Face authentication token.
715
+ commit_message (`str`, *optional*):
716
+ The summary / title / first line of the generated commit. Defaults to
717
+ `f"Update metadata with huggingface_hub"`
718
+ commit_description (`str` *optional*)
719
+ The description of the generated commit
720
+ revision (`str`, *optional*):
721
+ The git revision to commit from. Defaults to the head of the
722
+ `"main"` branch.
723
+ create_pr (`boolean`, *optional*):
724
+ Whether or not to create a Pull Request from `revision` with that commit.
725
+ Defaults to `False`.
726
+ parent_commit (`str`, *optional*):
727
+ The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
728
+ If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
729
+ If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
730
+ Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
731
+ especially useful if the repo is updated / committed to concurrently.
732
+ Returns:
733
+ `str`: URL of the commit which updated the card metadata.
734
+
735
+ Example:
736
+ ```python
737
+ >>> from huggingface_hub import metadata_update
738
+ >>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF',
739
+ ... 'results': [{'dataset': {'name': 'ReactionGIF',
740
+ ... 'type': 'julien-c/reactiongif'},
741
+ ... 'metrics': [{'name': 'Recall',
742
+ ... 'type': 'recall',
743
+ ... 'value': 0.7762102282047272}],
744
+ ... 'task': {'name': 'Text Classification',
745
+ ... 'type': 'text-classification'}}]}]}
746
+ >>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata)
747
+
748
+ ```
749
+ """
750
+ commit_message = commit_message if commit_message is not None else "Update metadata with huggingface_hub"
751
+
752
+ # Card class given repo_type
753
+ card_class: Type[RepoCard]
754
+ if repo_type is None or repo_type == "model":
755
+ card_class = ModelCard
756
+ elif repo_type == "dataset":
757
+ card_class = DatasetCard
758
+ elif repo_type == "space":
759
+ card_class = RepoCard
760
+ else:
761
+ raise ValueError(f"Unknown repo_type: {repo_type}")
762
+
763
+ # Either load repo_card from the Hub or create an empty one.
764
+ # NOTE: Will not create the repo if it doesn't exist.
765
+ try:
766
+ card = card_class.load(repo_id, token=token, repo_type=repo_type)
767
+ except EntryNotFoundError:
768
+ if repo_type == "space":
769
+ raise ValueError("Cannot update metadata on a Space that doesn't contain a `README.md` file.")
770
+
771
+ # Initialize a ModelCard or DatasetCard from default template and no data.
772
+ card = card_class.from_template(CardData())
773
+
774
+ for key, value in metadata.items():
775
+ if key == "model-index":
776
+ # if the new metadata doesn't include a name, either use existing one or repo name
777
+ if "name" not in value[0]:
778
+ value[0]["name"] = getattr(card, "model_name", repo_id)
779
+ model_name, new_results = model_index_to_eval_results(value)
780
+ if card.data.eval_results is None:
781
+ card.data.eval_results = new_results
782
+ card.data.model_name = model_name
783
+ else:
784
+ existing_results = card.data.eval_results
785
+
786
+ # Iterate over new results
787
+ # Iterate over existing results
788
+ # If both results describe the same metric but value is different:
789
+ # If overwrite=True: overwrite the metric value
790
+ # Else: raise ValueError
791
+ # Else: append new result to existing ones.
792
+ for new_result in new_results:
793
+ result_found = False
794
+ for existing_result in existing_results:
795
+ if new_result.is_equal_except_value(existing_result):
796
+ if new_result != existing_result and not overwrite:
797
+ raise ValueError(
798
+ "You passed a new value for the existing metric"
799
+ f" 'name: {new_result.metric_name}, type: "
800
+ f"{new_result.metric_type}'. Set `overwrite=True`"
801
+ " to overwrite existing metrics."
802
+ )
803
+ result_found = True
804
+ existing_result.metric_value = new_result.metric_value
805
+ if existing_result.verified is True:
806
+ existing_result.verify_token = new_result.verify_token
807
+ if not result_found:
808
+ card.data.eval_results.append(new_result)
809
+ else:
810
+ # Any metadata that is not a result metric
811
+ if card.data.get(key) is not None and not overwrite and card.data.get(key) != value:
812
+ raise ValueError(
813
+ f"You passed a new value for the existing meta data field '{key}'."
814
+ " Set `overwrite=True` to overwrite existing metadata."
815
+ )
816
+ else:
817
+ card.data[key] = value
818
+
819
+ return card.push_to_hub(
820
+ repo_id,
821
+ token=token,
822
+ repo_type=repo_type,
823
+ commit_message=commit_message,
824
+ commit_description=commit_description,
825
+ create_pr=create_pr,
826
+ revision=revision,
827
+ parent_commit=parent_commit,
828
+ )
env-llmeval/lib/python3.10/site-packages/huggingface_hub/repository.py ADDED
@@ -0,0 +1,1476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import os
3
+ import re
4
+ import subprocess
5
+ import threading
6
+ import time
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+ from typing import Callable, Dict, Iterator, List, Optional, Tuple, TypedDict, Union
10
+ from urllib.parse import urlparse
11
+
12
+ from huggingface_hub.constants import REPO_TYPES_URL_PREFIXES, REPOCARD_NAME
13
+ from huggingface_hub.repocard import metadata_load, metadata_save
14
+
15
+ from .hf_api import HfApi, repo_type_and_id_from_hf_id
16
+ from .lfs import LFS_MULTIPART_UPLOAD_COMMAND
17
+ from .utils import (
18
+ SoftTemporaryDirectory,
19
+ get_token,
20
+ logging,
21
+ run_subprocess,
22
+ tqdm,
23
+ validate_hf_hub_args,
24
+ )
25
+ from .utils._deprecation import _deprecate_method
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ class CommandInProgress:
32
+ """
33
+ Utility to follow commands launched asynchronously.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ title: str,
39
+ is_done_method: Callable,
40
+ status_method: Callable,
41
+ process: subprocess.Popen,
42
+ post_method: Optional[Callable] = None,
43
+ ):
44
+ self.title = title
45
+ self._is_done = is_done_method
46
+ self._status = status_method
47
+ self._process = process
48
+ self._stderr = ""
49
+ self._stdout = ""
50
+ self._post_method = post_method
51
+
52
+ @property
53
+ def is_done(self) -> bool:
54
+ """
55
+ Whether the process is done.
56
+ """
57
+ result = self._is_done()
58
+
59
+ if result and self._post_method is not None:
60
+ self._post_method()
61
+ self._post_method = None
62
+
63
+ return result
64
+
65
+ @property
66
+ def status(self) -> int:
67
+ """
68
+ The exit code/status of the current action. Will return `0` if the
69
+ command has completed successfully, and a number between 1 and 255 if
70
+ the process errored-out.
71
+
72
+ Will return -1 if the command is still ongoing.
73
+ """
74
+ return self._status()
75
+
76
+ @property
77
+ def failed(self) -> bool:
78
+ """
79
+ Whether the process errored-out.
80
+ """
81
+ return self.status > 0
82
+
83
+ @property
84
+ def stderr(self) -> str:
85
+ """
86
+ The current output message on the standard error.
87
+ """
88
+ if self._process.stderr is not None:
89
+ self._stderr += self._process.stderr.read()
90
+ return self._stderr
91
+
92
+ @property
93
+ def stdout(self) -> str:
94
+ """
95
+ The current output message on the standard output.
96
+ """
97
+ if self._process.stdout is not None:
98
+ self._stdout += self._process.stdout.read()
99
+ return self._stdout
100
+
101
+ def __repr__(self):
102
+ status = self.status
103
+
104
+ if status == -1:
105
+ status = "running"
106
+
107
+ return (
108
+ f"[{self.title} command, status code: {status},"
109
+ f" {'in progress.' if not self.is_done else 'finished.'} PID:"
110
+ f" {self._process.pid}]"
111
+ )
112
+
113
+
114
+ def is_git_repo(folder: Union[str, Path]) -> bool:
115
+ """
116
+ Check if the folder is the root or part of a git repository
117
+
118
+ Args:
119
+ folder (`str`):
120
+ The folder in which to run the command.
121
+
122
+ Returns:
123
+ `bool`: `True` if the repository is part of a repository, `False`
124
+ otherwise.
125
+ """
126
+ folder_exists = os.path.exists(os.path.join(folder, ".git"))
127
+ git_branch = subprocess.run("git branch".split(), cwd=folder, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
128
+ return folder_exists and git_branch.returncode == 0
129
+
130
+
131
+ def is_local_clone(folder: Union[str, Path], remote_url: str) -> bool:
132
+ """
133
+ Check if the folder is a local clone of the remote_url
134
+
135
+ Args:
136
+ folder (`str` or `Path`):
137
+ The folder in which to run the command.
138
+ remote_url (`str`):
139
+ The url of a git repository.
140
+
141
+ Returns:
142
+ `bool`: `True` if the repository is a local clone of the remote
143
+ repository specified, `False` otherwise.
144
+ """
145
+ if not is_git_repo(folder):
146
+ return False
147
+
148
+ remotes = run_subprocess("git remote -v", folder).stdout
149
+
150
+ # Remove token for the test with remotes.
151
+ remote_url = re.sub(r"https://.*@", "https://", remote_url)
152
+ remotes = [re.sub(r"https://.*@", "https://", remote) for remote in remotes.split()]
153
+ return remote_url in remotes
154
+
155
+
156
+ def is_tracked_with_lfs(filename: Union[str, Path]) -> bool:
157
+ """
158
+ Check if the file passed is tracked with git-lfs.
159
+
160
+ Args:
161
+ filename (`str` or `Path`):
162
+ The filename to check.
163
+
164
+ Returns:
165
+ `bool`: `True` if the file passed is tracked with git-lfs, `False`
166
+ otherwise.
167
+ """
168
+ folder = Path(filename).parent
169
+ filename = Path(filename).name
170
+
171
+ try:
172
+ p = run_subprocess("git check-attr -a".split() + [filename], folder)
173
+ attributes = p.stdout.strip()
174
+ except subprocess.CalledProcessError as exc:
175
+ if not is_git_repo(folder):
176
+ return False
177
+ else:
178
+ raise OSError(exc.stderr)
179
+
180
+ if len(attributes) == 0:
181
+ return False
182
+
183
+ found_lfs_tag = {"diff": False, "merge": False, "filter": False}
184
+
185
+ for attribute in attributes.split("\n"):
186
+ for tag in found_lfs_tag.keys():
187
+ if tag in attribute and "lfs" in attribute:
188
+ found_lfs_tag[tag] = True
189
+
190
+ return all(found_lfs_tag.values())
191
+
192
+
193
+ def is_git_ignored(filename: Union[str, Path]) -> bool:
194
+ """
195
+ Check if file is git-ignored. Supports nested .gitignore files.
196
+
197
+ Args:
198
+ filename (`str` or `Path`):
199
+ The filename to check.
200
+
201
+ Returns:
202
+ `bool`: `True` if the file passed is ignored by `git`, `False`
203
+ otherwise.
204
+ """
205
+ folder = Path(filename).parent
206
+ filename = Path(filename).name
207
+
208
+ try:
209
+ p = run_subprocess("git check-ignore".split() + [filename], folder, check=False)
210
+ # Will return exit code 1 if not gitignored
211
+ is_ignored = not bool(p.returncode)
212
+ except subprocess.CalledProcessError as exc:
213
+ raise OSError(exc.stderr)
214
+
215
+ return is_ignored
216
+
217
+
218
+ def is_binary_file(filename: Union[str, Path]) -> bool:
219
+ """
220
+ Check if file is a binary file.
221
+
222
+ Args:
223
+ filename (`str` or `Path`):
224
+ The filename to check.
225
+
226
+ Returns:
227
+ `bool`: `True` if the file passed is a binary file, `False` otherwise.
228
+ """
229
+ try:
230
+ with open(filename, "rb") as f:
231
+ content = f.read(10 * (1024**2)) # Read a maximum of 10MB
232
+
233
+ # Code sample taken from the following stack overflow thread
234
+ # https://stackoverflow.com/questions/898669/how-can-i-detect-if-a-file-is-binary-non-text-in-python/7392391#7392391
235
+ text_chars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7F})
236
+ return bool(content.translate(None, text_chars))
237
+ except UnicodeDecodeError:
238
+ return True
239
+
240
+
241
+ def files_to_be_staged(pattern: str = ".", folder: Union[str, Path, None] = None) -> List[str]:
242
+ """
243
+ Returns a list of filenames that are to be staged.
244
+
245
+ Args:
246
+ pattern (`str` or `Path`):
247
+ The pattern of filenames to check. Put `.` to get all files.
248
+ folder (`str` or `Path`):
249
+ The folder in which to run the command.
250
+
251
+ Returns:
252
+ `List[str]`: List of files that are to be staged.
253
+ """
254
+ try:
255
+ p = run_subprocess("git ls-files --exclude-standard -mo".split() + [pattern], folder)
256
+ if len(p.stdout.strip()):
257
+ files = p.stdout.strip().split("\n")
258
+ else:
259
+ files = []
260
+ except subprocess.CalledProcessError as exc:
261
+ raise EnvironmentError(exc.stderr)
262
+
263
+ return files
264
+
265
+
266
+ def is_tracked_upstream(folder: Union[str, Path]) -> bool:
267
+ """
268
+ Check if the current checked-out branch is tracked upstream.
269
+
270
+ Args:
271
+ folder (`str` or `Path`):
272
+ The folder in which to run the command.
273
+
274
+ Returns:
275
+ `bool`: `True` if the current checked-out branch is tracked upstream,
276
+ `False` otherwise.
277
+ """
278
+ try:
279
+ run_subprocess("git rev-parse --symbolic-full-name --abbrev-ref @{u}", folder)
280
+ return True
281
+ except subprocess.CalledProcessError as exc:
282
+ if "HEAD" in exc.stderr:
283
+ raise OSError("No branch checked out")
284
+
285
+ return False
286
+
287
+
288
+ def commits_to_push(folder: Union[str, Path], upstream: Optional[str] = None) -> int:
289
+ """
290
+ Check the number of commits that would be pushed upstream
291
+
292
+ Args:
293
+ folder (`str` or `Path`):
294
+ The folder in which to run the command.
295
+ upstream (`str`, *optional*):
296
+ The name of the upstream repository with which the comparison should be
297
+ made.
298
+
299
+ Returns:
300
+ `int`: Number of commits that would be pushed upstream were a `git
301
+ push` to proceed.
302
+ """
303
+ try:
304
+ result = run_subprocess(f"git cherry -v {upstream or ''}", folder)
305
+ return len(result.stdout.split("\n")) - 1
306
+ except subprocess.CalledProcessError as exc:
307
+ raise EnvironmentError(exc.stderr)
308
+
309
+
310
+ class PbarT(TypedDict):
311
+ # Used to store an opened progress bar in `_lfs_log_progress`
312
+ bar: tqdm
313
+ past_bytes: int
314
+
315
+
316
+ @contextmanager
317
+ def _lfs_log_progress():
318
+ """
319
+ This is a context manager that will log the Git LFS progress of cleaning,
320
+ smudging, pulling and pushing.
321
+ """
322
+
323
+ if logger.getEffectiveLevel() >= logging.ERROR:
324
+ try:
325
+ yield
326
+ except Exception:
327
+ pass
328
+ return
329
+
330
+ def output_progress(stopping_event: threading.Event):
331
+ """
332
+ To be launched as a separate thread with an event meaning it should stop
333
+ the tail.
334
+ """
335
+ # Key is tuple(state, filename), value is a dict(tqdm bar and a previous value)
336
+ pbars: Dict[Tuple[str, str], PbarT] = {}
337
+
338
+ def close_pbars():
339
+ for pbar in pbars.values():
340
+ pbar["bar"].update(pbar["bar"].total - pbar["past_bytes"])
341
+ pbar["bar"].refresh()
342
+ pbar["bar"].close()
343
+
344
+ def tail_file(filename) -> Iterator[str]:
345
+ """
346
+ Creates a generator to be iterated through, which will return each
347
+ line one by one. Will stop tailing the file if the stopping_event is
348
+ set.
349
+ """
350
+ with open(filename, "r") as file:
351
+ current_line = ""
352
+ while True:
353
+ if stopping_event.is_set():
354
+ close_pbars()
355
+ break
356
+
357
+ line_bit = file.readline()
358
+ if line_bit is not None and not len(line_bit.strip()) == 0:
359
+ current_line += line_bit
360
+ if current_line.endswith("\n"):
361
+ yield current_line
362
+ current_line = ""
363
+ else:
364
+ time.sleep(1)
365
+
366
+ # If the file isn't created yet, wait for a few seconds before trying again.
367
+ # Can be interrupted with the stopping_event.
368
+ while not os.path.exists(os.environ["GIT_LFS_PROGRESS"]):
369
+ if stopping_event.is_set():
370
+ close_pbars()
371
+ return
372
+
373
+ time.sleep(2)
374
+
375
+ for line in tail_file(os.environ["GIT_LFS_PROGRESS"]):
376
+ try:
377
+ state, file_progress, byte_progress, filename = line.split()
378
+ except ValueError as error:
379
+ # Try/except to ease debugging. See https://github.com/huggingface/huggingface_hub/issues/1373.
380
+ raise ValueError(f"Cannot unpack LFS progress line:\n{line}") from error
381
+ description = f"{state.capitalize()} file {filename}"
382
+
383
+ current_bytes, total_bytes = byte_progress.split("/")
384
+ current_bytes_int = int(current_bytes)
385
+ total_bytes_int = int(total_bytes)
386
+
387
+ pbar = pbars.get((state, filename))
388
+ if pbar is None:
389
+ # Initialize progress bar
390
+ pbars[(state, filename)] = {
391
+ "bar": tqdm(
392
+ desc=description,
393
+ initial=current_bytes_int,
394
+ total=total_bytes_int,
395
+ unit="B",
396
+ unit_scale=True,
397
+ unit_divisor=1024,
398
+ ),
399
+ "past_bytes": int(current_bytes),
400
+ }
401
+ else:
402
+ # Update progress bar
403
+ pbar["bar"].update(current_bytes_int - pbar["past_bytes"])
404
+ pbar["past_bytes"] = current_bytes_int
405
+
406
+ current_lfs_progress_value = os.environ.get("GIT_LFS_PROGRESS", "")
407
+
408
+ with SoftTemporaryDirectory() as tmpdir:
409
+ os.environ["GIT_LFS_PROGRESS"] = os.path.join(tmpdir, "lfs_progress")
410
+ logger.debug(f"Following progress in {os.environ['GIT_LFS_PROGRESS']}")
411
+
412
+ exit_event = threading.Event()
413
+ x = threading.Thread(target=output_progress, args=(exit_event,), daemon=True)
414
+ x.start()
415
+
416
+ try:
417
+ yield
418
+ finally:
419
+ exit_event.set()
420
+ x.join()
421
+
422
+ os.environ["GIT_LFS_PROGRESS"] = current_lfs_progress_value
423
+
424
+
425
+ class Repository:
426
+ """
427
+ Helper class to wrap the git and git-lfs commands.
428
+
429
+ The aim is to facilitate interacting with huggingface.co hosted model or
430
+ dataset repos, though not a lot here (if any) is actually specific to
431
+ huggingface.co.
432
+
433
+ <Tip warning={true}>
434
+
435
+ [`Repository`] is deprecated in favor of the http-based alternatives implemented in
436
+ [`HfApi`]. Given its large adoption in legacy code, the complete removal of
437
+ [`Repository`] will only happen in release `v1.0`. For more details, please read
438
+ https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http.
439
+
440
+ </Tip>
441
+ """
442
+
443
+ command_queue: List[CommandInProgress]
444
+
445
+ @validate_hf_hub_args
446
+ @_deprecate_method(
447
+ version="1.0",
448
+ message=(
449
+ "Please prefer the http-based alternatives instead. Given its large adoption in legacy code, the complete"
450
+ " removal is only planned on next major release.\nFor more details, please read"
451
+ " https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http."
452
+ ),
453
+ )
454
+ def __init__(
455
+ self,
456
+ local_dir: Union[str, Path],
457
+ clone_from: Optional[str] = None,
458
+ repo_type: Optional[str] = None,
459
+ token: Union[bool, str] = True,
460
+ git_user: Optional[str] = None,
461
+ git_email: Optional[str] = None,
462
+ revision: Optional[str] = None,
463
+ skip_lfs_files: bool = False,
464
+ client: Optional[HfApi] = None,
465
+ ):
466
+ """
467
+ Instantiate a local clone of a git repo.
468
+
469
+ If `clone_from` is set, the repo will be cloned from an existing remote repository.
470
+ If the remote repo does not exist, a `EnvironmentError` exception will be thrown.
471
+ Please create the remote repo first using [`create_repo`].
472
+
473
+ `Repository` uses the local git credentials by default. If explicitly set, the `token`
474
+ or the `git_user`/`git_email` pair will be used instead.
475
+
476
+ Args:
477
+ local_dir (`str` or `Path`):
478
+ path (e.g. `'my_trained_model/'`) to the local directory, where
479
+ the `Repository` will be initialized.
480
+ clone_from (`str`, *optional*):
481
+ Either a repository url or `repo_id`.
482
+ Example:
483
+ - `"https://huggingface.co/philschmid/playground-tests"`
484
+ - `"philschmid/playground-tests"`
485
+ repo_type (`str`, *optional*):
486
+ To set when cloning a repo from a repo_id. Default is model.
487
+ token (`bool` or `str`, *optional*):
488
+ A valid authentication token (see https://huggingface.co/settings/token).
489
+ If `None` or `True` and machine is logged in (through `huggingface-cli login`
490
+ or [`~huggingface_hub.login`]), token will be retrieved from the cache.
491
+ If `False`, token is not sent in the request header.
492
+ git_user (`str`, *optional*):
493
+ will override the `git config user.name` for committing and
494
+ pushing files to the hub.
495
+ git_email (`str`, *optional*):
496
+ will override the `git config user.email` for committing and
497
+ pushing files to the hub.
498
+ revision (`str`, *optional*):
499
+ Revision to checkout after initializing the repository. If the
500
+ revision doesn't exist, a branch will be created with that
501
+ revision name from the default branch's current HEAD.
502
+ skip_lfs_files (`bool`, *optional*, defaults to `False`):
503
+ whether to skip git-LFS files or not.
504
+ client (`HfApi`, *optional*):
505
+ Instance of [`HfApi`] to use when calling the HF Hub API. A new
506
+ instance will be created if this is left to `None`.
507
+
508
+ Raises:
509
+ - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
510
+ if the remote repository set in `clone_from` does not exist.
511
+ """
512
+ if isinstance(local_dir, Path):
513
+ local_dir = str(local_dir)
514
+ os.makedirs(local_dir, exist_ok=True)
515
+ self.local_dir = os.path.join(os.getcwd(), local_dir)
516
+ self._repo_type = repo_type
517
+ self.command_queue = []
518
+ self.skip_lfs_files = skip_lfs_files
519
+ self.client = client if client is not None else HfApi()
520
+
521
+ self.check_git_versions()
522
+
523
+ if isinstance(token, str):
524
+ self.huggingface_token: Optional[str] = token
525
+ elif token is False:
526
+ self.huggingface_token = None
527
+ else:
528
+ # if `True` -> explicit use of the cached token
529
+ # if `None` -> implicit use of the cached token
530
+ self.huggingface_token = get_token()
531
+
532
+ if clone_from is not None:
533
+ self.clone_from(repo_url=clone_from)
534
+ else:
535
+ if is_git_repo(self.local_dir):
536
+ logger.debug("[Repository] is a valid git repo")
537
+ else:
538
+ raise ValueError("If not specifying `clone_from`, you need to pass Repository a valid git clone.")
539
+
540
+ if self.huggingface_token is not None and (git_email is None or git_user is None):
541
+ user = self.client.whoami(self.huggingface_token)
542
+
543
+ if git_email is None:
544
+ git_email = user["email"]
545
+
546
+ if git_user is None:
547
+ git_user = user["fullname"]
548
+
549
+ if git_user is not None or git_email is not None:
550
+ self.git_config_username_and_email(git_user, git_email)
551
+
552
+ self.lfs_enable_largefiles()
553
+ self.git_credential_helper_store()
554
+
555
+ if revision is not None:
556
+ self.git_checkout(revision, create_branch_ok=True)
557
+
558
+ # This ensures that all commands exit before exiting the Python runtime.
559
+ # This will ensure all pushes register on the hub, even if other errors happen in subsequent operations.
560
+ atexit.register(self.wait_for_commands)
561
+
562
+ @property
563
+ def current_branch(self) -> str:
564
+ """
565
+ Returns the current checked out branch.
566
+
567
+ Returns:
568
+ `str`: Current checked out branch.
569
+ """
570
+ try:
571
+ result = run_subprocess("git rev-parse --abbrev-ref HEAD", self.local_dir).stdout.strip()
572
+ except subprocess.CalledProcessError as exc:
573
+ raise EnvironmentError(exc.stderr)
574
+
575
+ return result
576
+
577
+ def check_git_versions(self):
578
+ """
579
+ Checks that `git` and `git-lfs` can be run.
580
+
581
+ Raises:
582
+ - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
583
+ if `git` or `git-lfs` are not installed.
584
+ """
585
+ try:
586
+ git_version = run_subprocess("git --version", self.local_dir).stdout.strip()
587
+ except FileNotFoundError:
588
+ raise EnvironmentError("Looks like you do not have git installed, please install.")
589
+
590
+ try:
591
+ lfs_version = run_subprocess("git-lfs --version", self.local_dir).stdout.strip()
592
+ except FileNotFoundError:
593
+ raise EnvironmentError(
594
+ "Looks like you do not have git-lfs installed, please install."
595
+ " You can install from https://git-lfs.github.com/."
596
+ " Then run `git lfs install` (you only have to do this once)."
597
+ )
598
+ logger.info(git_version + "\n" + lfs_version)
599
+
600
+ @validate_hf_hub_args
601
+ def clone_from(self, repo_url: str, token: Union[bool, str, None] = None):
602
+ """
603
+ Clone from a remote. If the folder already exists, will try to clone the
604
+ repository within it.
605
+
606
+ If this folder is a git repository with linked history, will try to
607
+ update the repository.
608
+
609
+ Args:
610
+ repo_url (`str`):
611
+ The URL from which to clone the repository
612
+ token (`Union[str, bool]`, *optional*):
613
+ Whether to use the authentication token. It can be:
614
+ - a string which is the token itself
615
+ - `False`, which would not use the authentication token
616
+ - `True`, which would fetch the authentication token from the
617
+ local folder and use it (you should be logged in for this to
618
+ work).
619
+ - `None`, which would retrieve the value of
620
+ `self.huggingface_token`.
621
+
622
+ <Tip>
623
+
624
+ Raises the following error:
625
+
626
+ - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
627
+ if an organization token (starts with "api_org") is passed. Use must use
628
+ your own personal access token (see https://hf.co/settings/tokens).
629
+
630
+ - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
631
+ if you are trying to clone the repository in a non-empty folder, or if the
632
+ `git` operations raise errors.
633
+
634
+ </Tip>
635
+ """
636
+ token = (
637
+ token # str -> use it
638
+ if isinstance(token, str)
639
+ else (
640
+ None # `False` -> explicit no token
641
+ if token is False
642
+ else self.huggingface_token # `None` or `True` -> use default
643
+ )
644
+ )
645
+ if token is not None and token.startswith("api_org"):
646
+ raise ValueError(
647
+ "You must use your personal access token, not an Organization token"
648
+ " (see https://hf.co/settings/tokens)."
649
+ )
650
+
651
+ hub_url = self.client.endpoint
652
+ if hub_url in repo_url or ("http" not in repo_url and len(repo_url.split("/")) <= 2):
653
+ repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(repo_url, hub_url=hub_url)
654
+ repo_id = f"{namespace}/{repo_name}" if namespace is not None else repo_name
655
+
656
+ if repo_type is not None:
657
+ self._repo_type = repo_type
658
+
659
+ repo_url = hub_url + "/"
660
+
661
+ if self._repo_type in REPO_TYPES_URL_PREFIXES:
662
+ repo_url += REPO_TYPES_URL_PREFIXES[self._repo_type]
663
+
664
+ if token is not None:
665
+ # Add token in git url when provided
666
+ scheme = urlparse(repo_url).scheme
667
+ repo_url = repo_url.replace(f"{scheme}://", f"{scheme}://user:{token}@")
668
+
669
+ repo_url += repo_id
670
+
671
+ # For error messages, it's cleaner to show the repo url without the token.
672
+ clean_repo_url = re.sub(r"(https?)://.*@", r"\1://", repo_url)
673
+ try:
674
+ run_subprocess("git lfs install", self.local_dir)
675
+
676
+ # checks if repository is initialized in a empty repository or in one with files
677
+ if len(os.listdir(self.local_dir)) == 0:
678
+ logger.warning(f"Cloning {clean_repo_url} into local empty directory.")
679
+
680
+ with _lfs_log_progress():
681
+ env = os.environ.copy()
682
+
683
+ if self.skip_lfs_files:
684
+ env.update({"GIT_LFS_SKIP_SMUDGE": "1"})
685
+
686
+ run_subprocess(
687
+ # 'git lfs clone' is deprecated (will display a warning in the terminal)
688
+ # but we still use it as it provides a nicer UX when downloading large
689
+ # files (shows progress).
690
+ f"{'git clone' if self.skip_lfs_files else 'git lfs clone'} {repo_url} .",
691
+ self.local_dir,
692
+ env=env,
693
+ )
694
+ else:
695
+ # Check if the folder is the root of a git repository
696
+ if not is_git_repo(self.local_dir):
697
+ raise EnvironmentError(
698
+ "Tried to clone a repository in a non-empty folder that isn't"
699
+ f" a git repository ('{self.local_dir}'). If you really want to"
700
+ f" do this, do it manually:\n cd {self.local_dir} && git init"
701
+ " && git remote add origin && git pull origin main\n or clone"
702
+ " repo to a new folder and move your existing files there"
703
+ " afterwards."
704
+ )
705
+
706
+ if is_local_clone(self.local_dir, repo_url):
707
+ logger.warning(
708
+ f"{self.local_dir} is already a clone of {clean_repo_url}."
709
+ " Make sure you pull the latest changes with"
710
+ " `repo.git_pull()`."
711
+ )
712
+ else:
713
+ output = run_subprocess("git remote get-url origin", self.local_dir, check=False)
714
+
715
+ error_msg = (
716
+ f"Tried to clone {clean_repo_url} in an unrelated git"
717
+ " repository.\nIf you believe this is an error, please add"
718
+ f" a remote with the following URL: {clean_repo_url}."
719
+ )
720
+ if output.returncode == 0:
721
+ clean_local_remote_url = re.sub(r"https://.*@", "https://", output.stdout)
722
+ error_msg += f"\nLocal path has its origin defined as: {clean_local_remote_url}"
723
+ raise EnvironmentError(error_msg)
724
+
725
+ except subprocess.CalledProcessError as exc:
726
+ raise EnvironmentError(exc.stderr)
727
+
728
+ def git_config_username_and_email(self, git_user: Optional[str] = None, git_email: Optional[str] = None):
729
+ """
730
+ Sets git username and email (only in the current repo).
731
+
732
+ Args:
733
+ git_user (`str`, *optional*):
734
+ The username to register through `git`.
735
+ git_email (`str`, *optional*):
736
+ The email to register through `git`.
737
+ """
738
+ try:
739
+ if git_user is not None:
740
+ run_subprocess("git config user.name".split() + [git_user], self.local_dir)
741
+
742
+ if git_email is not None:
743
+ run_subprocess(f"git config user.email {git_email}".split(), self.local_dir)
744
+ except subprocess.CalledProcessError as exc:
745
+ raise EnvironmentError(exc.stderr)
746
+
747
+ def git_credential_helper_store(self):
748
+ """
749
+ Sets the git credential helper to `store`
750
+ """
751
+ try:
752
+ run_subprocess("git config credential.helper store", self.local_dir)
753
+ except subprocess.CalledProcessError as exc:
754
+ raise EnvironmentError(exc.stderr)
755
+
756
+ def git_head_hash(self) -> str:
757
+ """
758
+ Get commit sha on top of HEAD.
759
+
760
+ Returns:
761
+ `str`: The current checked out commit SHA.
762
+ """
763
+ try:
764
+ p = run_subprocess("git rev-parse HEAD", self.local_dir)
765
+ return p.stdout.strip()
766
+ except subprocess.CalledProcessError as exc:
767
+ raise EnvironmentError(exc.stderr)
768
+
769
+ def git_remote_url(self) -> str:
770
+ """
771
+ Get URL to origin remote.
772
+
773
+ Returns:
774
+ `str`: The URL of the `origin` remote.
775
+ """
776
+ try:
777
+ p = run_subprocess("git config --get remote.origin.url", self.local_dir)
778
+ url = p.stdout.strip()
779
+ # Strip basic auth info.
780
+ return re.sub(r"https://.*@", "https://", url)
781
+ except subprocess.CalledProcessError as exc:
782
+ raise EnvironmentError(exc.stderr)
783
+
784
+ def git_head_commit_url(self) -> str:
785
+ """
786
+ Get URL to last commit on HEAD. We assume it's been pushed, and the url
787
+ scheme is the same one as for GitHub or HuggingFace.
788
+
789
+ Returns:
790
+ `str`: The URL to the current checked-out commit.
791
+ """
792
+ sha = self.git_head_hash()
793
+ url = self.git_remote_url()
794
+ if url.endswith("/"):
795
+ url = url[:-1]
796
+ return f"{url}/commit/{sha}"
797
+
798
+ def list_deleted_files(self) -> List[str]:
799
+ """
800
+ Returns a list of the files that are deleted in the working directory or
801
+ index.
802
+
803
+ Returns:
804
+ `List[str]`: A list of files that have been deleted in the working
805
+ directory or index.
806
+ """
807
+ try:
808
+ git_status = run_subprocess("git status -s", self.local_dir).stdout.strip()
809
+ except subprocess.CalledProcessError as exc:
810
+ raise EnvironmentError(exc.stderr)
811
+
812
+ if len(git_status) == 0:
813
+ return []
814
+
815
+ # Receives a status like the following
816
+ # D .gitignore
817
+ # D new_file.json
818
+ # AD new_file1.json
819
+ # ?? new_file2.json
820
+ # ?? new_file4.json
821
+
822
+ # Strip each line of whitespaces
823
+ modified_files_statuses = [status.strip() for status in git_status.split("\n")]
824
+
825
+ # Only keep files that are deleted using the D prefix
826
+ deleted_files_statuses = [status for status in modified_files_statuses if "D" in status.split()[0]]
827
+
828
+ # Remove the D prefix and strip to keep only the relevant filename
829
+ deleted_files = [status.split()[-1].strip() for status in deleted_files_statuses]
830
+
831
+ return deleted_files
832
+
833
+ def lfs_track(self, patterns: Union[str, List[str]], filename: bool = False):
834
+ """
835
+ Tell git-lfs to track files according to a pattern.
836
+
837
+ Setting the `filename` argument to `True` will treat the arguments as
838
+ literal filenames, not as patterns. Any special glob characters in the
839
+ filename will be escaped when writing to the `.gitattributes` file.
840
+
841
+ Args:
842
+ patterns (`Union[str, List[str]]`):
843
+ The pattern, or list of patterns, to track with git-lfs.
844
+ filename (`bool`, *optional*, defaults to `False`):
845
+ Whether to use the patterns as literal filenames.
846
+ """
847
+ if isinstance(patterns, str):
848
+ patterns = [patterns]
849
+ try:
850
+ for pattern in patterns:
851
+ run_subprocess(
852
+ f"git lfs track {'--filename' if filename else ''} {pattern}",
853
+ self.local_dir,
854
+ )
855
+ except subprocess.CalledProcessError as exc:
856
+ raise EnvironmentError(exc.stderr)
857
+
858
+ def lfs_untrack(self, patterns: Union[str, List[str]]):
859
+ """
860
+ Tell git-lfs to untrack those files.
861
+
862
+ Args:
863
+ patterns (`Union[str, List[str]]`):
864
+ The pattern, or list of patterns, to untrack with git-lfs.
865
+ """
866
+ if isinstance(patterns, str):
867
+ patterns = [patterns]
868
+ try:
869
+ for pattern in patterns:
870
+ run_subprocess("git lfs untrack".split() + [pattern], self.local_dir)
871
+ except subprocess.CalledProcessError as exc:
872
+ raise EnvironmentError(exc.stderr)
873
+
874
+ def lfs_enable_largefiles(self):
875
+ """
876
+ HF-specific. This enables upload support of files >5GB.
877
+ """
878
+ try:
879
+ lfs_config = "git config lfs.customtransfer.multipart"
880
+ run_subprocess(f"{lfs_config}.path huggingface-cli", self.local_dir)
881
+ run_subprocess(
882
+ f"{lfs_config}.args {LFS_MULTIPART_UPLOAD_COMMAND}",
883
+ self.local_dir,
884
+ )
885
+ except subprocess.CalledProcessError as exc:
886
+ raise EnvironmentError(exc.stderr)
887
+
888
+ def auto_track_binary_files(self, pattern: str = ".") -> List[str]:
889
+ """
890
+ Automatically track binary files with git-lfs.
891
+
892
+ Args:
893
+ pattern (`str`, *optional*, defaults to "."):
894
+ The pattern with which to track files that are binary.
895
+
896
+ Returns:
897
+ `List[str]`: List of filenames that are now tracked due to being
898
+ binary files
899
+ """
900
+ files_to_be_tracked_with_lfs = []
901
+
902
+ deleted_files = self.list_deleted_files()
903
+
904
+ for filename in files_to_be_staged(pattern, folder=self.local_dir):
905
+ if filename in deleted_files:
906
+ continue
907
+
908
+ path_to_file = os.path.join(os.getcwd(), self.local_dir, filename)
909
+
910
+ if not (is_tracked_with_lfs(path_to_file) or is_git_ignored(path_to_file)):
911
+ size_in_mb = os.path.getsize(path_to_file) / (1024 * 1024)
912
+
913
+ if size_in_mb >= 10:
914
+ logger.warning(
915
+ "Parsing a large file to check if binary or not. Tracking large"
916
+ " files using `repository.auto_track_large_files` is"
917
+ " recommended so as to not load the full file in memory."
918
+ )
919
+
920
+ is_binary = is_binary_file(path_to_file)
921
+
922
+ if is_binary:
923
+ self.lfs_track(filename)
924
+ files_to_be_tracked_with_lfs.append(filename)
925
+
926
+ # Cleanup the .gitattributes if files were deleted
927
+ self.lfs_untrack(deleted_files)
928
+
929
+ return files_to_be_tracked_with_lfs
930
+
931
+ def auto_track_large_files(self, pattern: str = ".") -> List[str]:
932
+ """
933
+ Automatically track large files (files that weigh more than 10MBs) with
934
+ git-lfs.
935
+
936
+ Args:
937
+ pattern (`str`, *optional*, defaults to "."):
938
+ The pattern with which to track files that are above 10MBs.
939
+
940
+ Returns:
941
+ `List[str]`: List of filenames that are now tracked due to their
942
+ size.
943
+ """
944
+ files_to_be_tracked_with_lfs = []
945
+
946
+ deleted_files = self.list_deleted_files()
947
+
948
+ for filename in files_to_be_staged(pattern, folder=self.local_dir):
949
+ if filename in deleted_files:
950
+ continue
951
+
952
+ path_to_file = os.path.join(os.getcwd(), self.local_dir, filename)
953
+ size_in_mb = os.path.getsize(path_to_file) / (1024 * 1024)
954
+
955
+ if size_in_mb >= 10 and not is_tracked_with_lfs(path_to_file) and not is_git_ignored(path_to_file):
956
+ self.lfs_track(filename)
957
+ files_to_be_tracked_with_lfs.append(filename)
958
+
959
+ # Cleanup the .gitattributes if files were deleted
960
+ self.lfs_untrack(deleted_files)
961
+
962
+ return files_to_be_tracked_with_lfs
963
+
964
+ def lfs_prune(self, recent=False):
965
+ """
966
+ git lfs prune
967
+
968
+ Args:
969
+ recent (`bool`, *optional*, defaults to `False`):
970
+ Whether to prune files even if they were referenced by recent
971
+ commits. See the following
972
+ [link](https://github.com/git-lfs/git-lfs/blob/f3d43f0428a84fc4f1e5405b76b5a73ec2437e65/docs/man/git-lfs-prune.1.ronn#recent-files)
973
+ for more information.
974
+ """
975
+ try:
976
+ with _lfs_log_progress():
977
+ result = run_subprocess(f"git lfs prune {'--recent' if recent else ''}", self.local_dir)
978
+ logger.info(result.stdout)
979
+ except subprocess.CalledProcessError as exc:
980
+ raise EnvironmentError(exc.stderr)
981
+
982
+ def git_pull(self, rebase: bool = False, lfs: bool = False):
983
+ """
984
+ git pull
985
+
986
+ Args:
987
+ rebase (`bool`, *optional*, defaults to `False`):
988
+ Whether to rebase the current branch on top of the upstream
989
+ branch after fetching.
990
+ lfs (`bool`, *optional*, defaults to `False`):
991
+ Whether to fetch the LFS files too. This option only changes the
992
+ behavior when a repository was cloned without fetching the LFS
993
+ files; calling `repo.git_pull(lfs=True)` will then fetch the LFS
994
+ file from the remote repository.
995
+ """
996
+ command = "git pull" if not lfs else "git lfs pull"
997
+ if rebase:
998
+ command += " --rebase"
999
+ try:
1000
+ with _lfs_log_progress():
1001
+ result = run_subprocess(command, self.local_dir)
1002
+ logger.info(result.stdout)
1003
+ except subprocess.CalledProcessError as exc:
1004
+ raise EnvironmentError(exc.stderr)
1005
+
1006
+ def git_add(self, pattern: str = ".", auto_lfs_track: bool = False):
1007
+ """
1008
+ git add
1009
+
1010
+ Setting the `auto_lfs_track` parameter to `True` will automatically
1011
+ track files that are larger than 10MB with `git-lfs`.
1012
+
1013
+ Args:
1014
+ pattern (`str`, *optional*, defaults to "."):
1015
+ The pattern with which to add files to staging.
1016
+ auto_lfs_track (`bool`, *optional*, defaults to `False`):
1017
+ Whether to automatically track large and binary files with
1018
+ git-lfs. Any file over 10MB in size, or in binary format, will
1019
+ be automatically tracked.
1020
+ """
1021
+ if auto_lfs_track:
1022
+ # Track files according to their size (>=10MB)
1023
+ tracked_files = self.auto_track_large_files(pattern)
1024
+
1025
+ # Read the remaining files and track them if they're binary
1026
+ tracked_files.extend(self.auto_track_binary_files(pattern))
1027
+
1028
+ if tracked_files:
1029
+ logger.warning(
1030
+ f"Adding files tracked by Git LFS: {tracked_files}. This may take a"
1031
+ " bit of time if the files are large."
1032
+ )
1033
+
1034
+ try:
1035
+ result = run_subprocess("git add -v".split() + [pattern], self.local_dir)
1036
+ logger.info(f"Adding to index:\n{result.stdout}\n")
1037
+ except subprocess.CalledProcessError as exc:
1038
+ raise EnvironmentError(exc.stderr)
1039
+
1040
+ def git_commit(self, commit_message: str = "commit files to HF hub"):
1041
+ """
1042
+ git commit
1043
+
1044
+ Args:
1045
+ commit_message (`str`, *optional*, defaults to "commit files to HF hub"):
1046
+ The message attributed to the commit.
1047
+ """
1048
+ try:
1049
+ result = run_subprocess("git commit -v -m".split() + [commit_message], self.local_dir)
1050
+ logger.info(f"Committed:\n{result.stdout}\n")
1051
+ except subprocess.CalledProcessError as exc:
1052
+ if len(exc.stderr) > 0:
1053
+ raise EnvironmentError(exc.stderr)
1054
+ else:
1055
+ raise EnvironmentError(exc.stdout)
1056
+
1057
+ def git_push(
1058
+ self,
1059
+ upstream: Optional[str] = None,
1060
+ blocking: bool = True,
1061
+ auto_lfs_prune: bool = False,
1062
+ ) -> Union[str, Tuple[str, CommandInProgress]]:
1063
+ """
1064
+ git push
1065
+
1066
+ If used without setting `blocking`, will return url to commit on remote
1067
+ repo. If used with `blocking=True`, will return a tuple containing the
1068
+ url to commit and the command object to follow for information about the
1069
+ process.
1070
+
1071
+ Args:
1072
+ upstream (`str`, *optional*):
1073
+ Upstream to which this should push. If not specified, will push
1074
+ to the lastly defined upstream or to the default one (`origin
1075
+ main`).
1076
+ blocking (`bool`, *optional*, defaults to `True`):
1077
+ Whether the function should return only when the push has
1078
+ finished. Setting this to `False` will return an
1079
+ `CommandInProgress` object which has an `is_done` property. This
1080
+ property will be set to `True` when the push is finished.
1081
+ auto_lfs_prune (`bool`, *optional*, defaults to `False`):
1082
+ Whether to automatically prune files once they have been pushed
1083
+ to the remote.
1084
+ """
1085
+ command = "git push"
1086
+
1087
+ if upstream:
1088
+ command += f" --set-upstream {upstream}"
1089
+
1090
+ number_of_commits = commits_to_push(self.local_dir, upstream)
1091
+
1092
+ if number_of_commits > 1:
1093
+ logger.warning(f"Several commits ({number_of_commits}) will be pushed upstream.")
1094
+ if blocking:
1095
+ logger.warning("The progress bars may be unreliable.")
1096
+
1097
+ try:
1098
+ with _lfs_log_progress():
1099
+ process = subprocess.Popen(
1100
+ command.split(),
1101
+ stderr=subprocess.PIPE,
1102
+ stdout=subprocess.PIPE,
1103
+ encoding="utf-8",
1104
+ cwd=self.local_dir,
1105
+ )
1106
+
1107
+ if blocking:
1108
+ stdout, stderr = process.communicate()
1109
+ return_code = process.poll()
1110
+ process.kill()
1111
+
1112
+ if len(stderr):
1113
+ logger.warning(stderr)
1114
+
1115
+ if return_code:
1116
+ raise subprocess.CalledProcessError(return_code, process.args, output=stdout, stderr=stderr)
1117
+
1118
+ except subprocess.CalledProcessError as exc:
1119
+ raise EnvironmentError(exc.stderr)
1120
+
1121
+ if not blocking:
1122
+
1123
+ def status_method():
1124
+ status = process.poll()
1125
+ if status is None:
1126
+ return -1
1127
+ else:
1128
+ return status
1129
+
1130
+ command_in_progress = CommandInProgress(
1131
+ "push",
1132
+ is_done_method=lambda: process.poll() is not None,
1133
+ status_method=status_method,
1134
+ process=process,
1135
+ post_method=self.lfs_prune if auto_lfs_prune else None,
1136
+ )
1137
+
1138
+ self.command_queue.append(command_in_progress)
1139
+
1140
+ return self.git_head_commit_url(), command_in_progress
1141
+
1142
+ if auto_lfs_prune:
1143
+ self.lfs_prune()
1144
+
1145
+ return self.git_head_commit_url()
1146
+
1147
+ def git_checkout(self, revision: str, create_branch_ok: bool = False):
1148
+ """
1149
+ git checkout a given revision
1150
+
1151
+ Specifying `create_branch_ok` to `True` will create the branch to the
1152
+ given revision if that revision doesn't exist.
1153
+
1154
+ Args:
1155
+ revision (`str`):
1156
+ The revision to checkout.
1157
+ create_branch_ok (`str`, *optional*, defaults to `False`):
1158
+ Whether creating a branch named with the `revision` passed at
1159
+ the current checked-out reference if `revision` isn't an
1160
+ existing revision is allowed.
1161
+ """
1162
+ try:
1163
+ result = run_subprocess(f"git checkout {revision}", self.local_dir)
1164
+ logger.warning(f"Checked out {revision} from {self.current_branch}.")
1165
+ logger.warning(result.stdout)
1166
+ except subprocess.CalledProcessError as exc:
1167
+ if not create_branch_ok:
1168
+ raise EnvironmentError(exc.stderr)
1169
+ else:
1170
+ try:
1171
+ result = run_subprocess(f"git checkout -b {revision}", self.local_dir)
1172
+ logger.warning(
1173
+ f"Revision `{revision}` does not exist. Created and checked out branch `{revision}`."
1174
+ )
1175
+ logger.warning(result.stdout)
1176
+ except subprocess.CalledProcessError as exc:
1177
+ raise EnvironmentError(exc.stderr)
1178
+
1179
+ def tag_exists(self, tag_name: str, remote: Optional[str] = None) -> bool:
1180
+ """
1181
+ Check if a tag exists or not.
1182
+
1183
+ Args:
1184
+ tag_name (`str`):
1185
+ The name of the tag to check.
1186
+ remote (`str`, *optional*):
1187
+ Whether to check if the tag exists on a remote. This parameter
1188
+ should be the identifier of the remote.
1189
+
1190
+ Returns:
1191
+ `bool`: Whether the tag exists.
1192
+ """
1193
+ if remote:
1194
+ try:
1195
+ result = run_subprocess(f"git ls-remote origin refs/tags/{tag_name}", self.local_dir).stdout.strip()
1196
+ except subprocess.CalledProcessError as exc:
1197
+ raise EnvironmentError(exc.stderr)
1198
+
1199
+ return len(result) != 0
1200
+ else:
1201
+ try:
1202
+ git_tags = run_subprocess("git tag", self.local_dir).stdout.strip()
1203
+ except subprocess.CalledProcessError as exc:
1204
+ raise EnvironmentError(exc.stderr)
1205
+
1206
+ git_tags = git_tags.split("\n")
1207
+ return tag_name in git_tags
1208
+
1209
+ def delete_tag(self, tag_name: str, remote: Optional[str] = None) -> bool:
1210
+ """
1211
+ Delete a tag, both local and remote, if it exists
1212
+
1213
+ Args:
1214
+ tag_name (`str`):
1215
+ The tag name to delete.
1216
+ remote (`str`, *optional*):
1217
+ The remote on which to delete the tag.
1218
+
1219
+ Returns:
1220
+ `bool`: `True` if deleted, `False` if the tag didn't exist.
1221
+ If remote is not passed, will just be updated locally
1222
+ """
1223
+ delete_locally = True
1224
+ delete_remotely = True
1225
+
1226
+ if not self.tag_exists(tag_name):
1227
+ delete_locally = False
1228
+
1229
+ if not self.tag_exists(tag_name, remote=remote):
1230
+ delete_remotely = False
1231
+
1232
+ if delete_locally:
1233
+ try:
1234
+ run_subprocess(["git", "tag", "-d", tag_name], self.local_dir).stdout.strip()
1235
+ except subprocess.CalledProcessError as exc:
1236
+ raise EnvironmentError(exc.stderr)
1237
+
1238
+ if remote and delete_remotely:
1239
+ try:
1240
+ run_subprocess(f"git push {remote} --delete {tag_name}", self.local_dir).stdout.strip()
1241
+ except subprocess.CalledProcessError as exc:
1242
+ raise EnvironmentError(exc.stderr)
1243
+
1244
+ return True
1245
+
1246
+ def add_tag(self, tag_name: str, message: Optional[str] = None, remote: Optional[str] = None):
1247
+ """
1248
+ Add a tag at the current head and push it
1249
+
1250
+ If remote is None, will just be updated locally
1251
+
1252
+ If no message is provided, the tag will be lightweight. if a message is
1253
+ provided, the tag will be annotated.
1254
+
1255
+ Args:
1256
+ tag_name (`str`):
1257
+ The name of the tag to be added.
1258
+ message (`str`, *optional*):
1259
+ The message that accompanies the tag. The tag will turn into an
1260
+ annotated tag if a message is passed.
1261
+ remote (`str`, *optional*):
1262
+ The remote on which to add the tag.
1263
+ """
1264
+ if message:
1265
+ tag_args = ["git", "tag", "-a", tag_name, "-m", message]
1266
+ else:
1267
+ tag_args = ["git", "tag", tag_name]
1268
+
1269
+ try:
1270
+ run_subprocess(tag_args, self.local_dir).stdout.strip()
1271
+ except subprocess.CalledProcessError as exc:
1272
+ raise EnvironmentError(exc.stderr)
1273
+
1274
+ if remote:
1275
+ try:
1276
+ run_subprocess(f"git push {remote} {tag_name}", self.local_dir).stdout.strip()
1277
+ except subprocess.CalledProcessError as exc:
1278
+ raise EnvironmentError(exc.stderr)
1279
+
1280
+ def is_repo_clean(self) -> bool:
1281
+ """
1282
+ Return whether or not the git status is clean or not
1283
+
1284
+ Returns:
1285
+ `bool`: `True` if the git status is clean, `False` otherwise.
1286
+ """
1287
+ try:
1288
+ git_status = run_subprocess("git status --porcelain", self.local_dir).stdout.strip()
1289
+ except subprocess.CalledProcessError as exc:
1290
+ raise EnvironmentError(exc.stderr)
1291
+
1292
+ return len(git_status) == 0
1293
+
1294
+ def push_to_hub(
1295
+ self,
1296
+ commit_message: str = "commit files to HF hub",
1297
+ blocking: bool = True,
1298
+ clean_ok: bool = True,
1299
+ auto_lfs_prune: bool = False,
1300
+ ) -> Union[None, str, Tuple[str, CommandInProgress]]:
1301
+ """
1302
+ Helper to add, commit, and push files to remote repository on the
1303
+ HuggingFace Hub. Will automatically track large files (>10MB).
1304
+
1305
+ Args:
1306
+ commit_message (`str`):
1307
+ Message to use for the commit.
1308
+ blocking (`bool`, *optional*, defaults to `True`):
1309
+ Whether the function should return only when the `git push` has
1310
+ finished.
1311
+ clean_ok (`bool`, *optional*, defaults to `True`):
1312
+ If True, this function will return None if the repo is
1313
+ untouched. Default behavior is to fail because the git command
1314
+ fails.
1315
+ auto_lfs_prune (`bool`, *optional*, defaults to `False`):
1316
+ Whether to automatically prune files once they have been pushed
1317
+ to the remote.
1318
+ """
1319
+ if clean_ok and self.is_repo_clean():
1320
+ logger.info("Repo currently clean. Ignoring push_to_hub")
1321
+ return None
1322
+ self.git_add(auto_lfs_track=True)
1323
+ self.git_commit(commit_message)
1324
+ return self.git_push(
1325
+ upstream=f"origin {self.current_branch}",
1326
+ blocking=blocking,
1327
+ auto_lfs_prune=auto_lfs_prune,
1328
+ )
1329
+
1330
+ @contextmanager
1331
+ def commit(
1332
+ self,
1333
+ commit_message: str,
1334
+ branch: Optional[str] = None,
1335
+ track_large_files: bool = True,
1336
+ blocking: bool = True,
1337
+ auto_lfs_prune: bool = False,
1338
+ ):
1339
+ """
1340
+ Context manager utility to handle committing to a repository. This
1341
+ automatically tracks large files (>10Mb) with git-lfs. Set the
1342
+ `track_large_files` argument to `False` if you wish to ignore that
1343
+ behavior.
1344
+
1345
+ Args:
1346
+ commit_message (`str`):
1347
+ Message to use for the commit.
1348
+ branch (`str`, *optional*):
1349
+ The branch on which the commit will appear. This branch will be
1350
+ checked-out before any operation.
1351
+ track_large_files (`bool`, *optional*, defaults to `True`):
1352
+ Whether to automatically track large files or not. Will do so by
1353
+ default.
1354
+ blocking (`bool`, *optional*, defaults to `True`):
1355
+ Whether the function should return only when the `git push` has
1356
+ finished.
1357
+ auto_lfs_prune (`bool`, defaults to `True`):
1358
+ Whether to automatically prune files once they have been pushed
1359
+ to the remote.
1360
+
1361
+ Examples:
1362
+
1363
+ ```python
1364
+ >>> with Repository(
1365
+ ... "text-files",
1366
+ ... clone_from="<user>/text-files",
1367
+ ... token=True,
1368
+ >>> ).commit("My first file :)"):
1369
+ ... with open("file.txt", "w+") as f:
1370
+ ... f.write(json.dumps({"hey": 8}))
1371
+
1372
+ >>> import torch
1373
+
1374
+ >>> model = torch.nn.Transformer()
1375
+ >>> with Repository(
1376
+ ... "torch-model",
1377
+ ... clone_from="<user>/torch-model",
1378
+ ... token=True,
1379
+ >>> ).commit("My cool model :)"):
1380
+ ... torch.save(model.state_dict(), "model.pt")
1381
+ ```
1382
+
1383
+ """
1384
+
1385
+ files_to_stage = files_to_be_staged(".", folder=self.local_dir)
1386
+
1387
+ if len(files_to_stage):
1388
+ files_in_msg = str(files_to_stage[:5])[:-1] + ", ...]" if len(files_to_stage) > 5 else str(files_to_stage)
1389
+ logger.error(
1390
+ "There exists some updated files in the local repository that are not"
1391
+ f" committed: {files_in_msg}. This may lead to errors if checking out"
1392
+ " a branch. These files and their modifications will be added to the"
1393
+ " current commit."
1394
+ )
1395
+
1396
+ if branch is not None:
1397
+ self.git_checkout(branch, create_branch_ok=True)
1398
+
1399
+ if is_tracked_upstream(self.local_dir):
1400
+ logger.warning("Pulling changes ...")
1401
+ self.git_pull(rebase=True)
1402
+ else:
1403
+ logger.warning(f"The current branch has no upstream branch. Will push to 'origin {self.current_branch}'")
1404
+
1405
+ current_working_directory = os.getcwd()
1406
+ os.chdir(os.path.join(current_working_directory, self.local_dir))
1407
+
1408
+ try:
1409
+ yield self
1410
+ finally:
1411
+ self.git_add(auto_lfs_track=track_large_files)
1412
+
1413
+ try:
1414
+ self.git_commit(commit_message)
1415
+ except OSError as e:
1416
+ # If no changes are detected, there is nothing to commit.
1417
+ if "nothing to commit" not in str(e):
1418
+ raise e
1419
+
1420
+ try:
1421
+ self.git_push(
1422
+ upstream=f"origin {self.current_branch}",
1423
+ blocking=blocking,
1424
+ auto_lfs_prune=auto_lfs_prune,
1425
+ )
1426
+ except OSError as e:
1427
+ # If no changes are detected, there is nothing to commit.
1428
+ if "could not read Username" in str(e):
1429
+ raise OSError("Couldn't authenticate user for push. Did you set `token` to `True`?") from e
1430
+ else:
1431
+ raise e
1432
+
1433
+ os.chdir(current_working_directory)
1434
+
1435
+ def repocard_metadata_load(self) -> Optional[Dict]:
1436
+ filepath = os.path.join(self.local_dir, REPOCARD_NAME)
1437
+ if os.path.isfile(filepath):
1438
+ return metadata_load(filepath)
1439
+ return None
1440
+
1441
+ def repocard_metadata_save(self, data: Dict) -> None:
1442
+ return metadata_save(os.path.join(self.local_dir, REPOCARD_NAME), data)
1443
+
1444
+ @property
1445
+ def commands_failed(self):
1446
+ """
1447
+ Returns the asynchronous commands that failed.
1448
+ """
1449
+ return [c for c in self.command_queue if c.status > 0]
1450
+
1451
+ @property
1452
+ def commands_in_progress(self):
1453
+ """
1454
+ Returns the asynchronous commands that are currently in progress.
1455
+ """
1456
+ return [c for c in self.command_queue if not c.is_done]
1457
+
1458
+ def wait_for_commands(self):
1459
+ """
1460
+ Blocking method: blocks all subsequent execution until all commands have
1461
+ been processed.
1462
+ """
1463
+ index = 0
1464
+ for command_failed in self.commands_failed:
1465
+ logger.error(f"The {command_failed.title} command with PID {command_failed._process.pid} failed.")
1466
+ logger.error(command_failed.stderr)
1467
+
1468
+ while self.commands_in_progress:
1469
+ if index % 10 == 0:
1470
+ logger.warning(
1471
+ f"Waiting for the following commands to finish before shutting down: {self.commands_in_progress}."
1472
+ )
1473
+
1474
+ index += 1
1475
+
1476
+ time.sleep(1)
env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/datasetcard_template.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ # For reference on dataset card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1
3
+ # Doc / guide: https://huggingface.co/docs/hub/datasets-cards
4
+ {{ card_data }}
5
+ ---
6
+
7
+ # Dataset Card for {{ pretty_name | default("Dataset Name", true) }}
8
+
9
+ <!-- Provide a quick summary of the dataset. -->
10
+
11
+ {{ dataset_summary | default("", true) }}
12
+
13
+ ## Dataset Details
14
+
15
+ ### Dataset Description
16
+
17
+ <!-- Provide a longer summary of what this dataset is. -->
18
+
19
+ {{ dataset_description | default("", true) }}
20
+
21
+ - **Curated by:** {{ curators | default("[More Information Needed]", true)}}
22
+ - **Funded by [optional]:** {{ funded_by | default("[More Information Needed]", true)}}
23
+ - **Shared by [optional]:** {{ shared_by | default("[More Information Needed]", true)}}
24
+ - **Language(s) (NLP):** {{ language | default("[More Information Needed]", true)}}
25
+ - **License:** {{ license | default("[More Information Needed]", true)}}
26
+
27
+ ### Dataset Sources [optional]
28
+
29
+ <!-- Provide the basic links for the dataset. -->
30
+
31
+ - **Repository:** {{ repo | default("[More Information Needed]", true)}}
32
+ - **Paper [optional]:** {{ paper | default("[More Information Needed]", true)}}
33
+ - **Demo [optional]:** {{ demo | default("[More Information Needed]", true)}}
34
+
35
+ ## Uses
36
+
37
+ <!-- Address questions around how the dataset is intended to be used. -->
38
+
39
+ ### Direct Use
40
+
41
+ <!-- This section describes suitable use cases for the dataset. -->
42
+
43
+ {{ direct_use | default("[More Information Needed]", true)}}
44
+
45
+ ### Out-of-Scope Use
46
+
47
+ <!-- This section addresses misuse, malicious use, and uses that the dataset will not work well for. -->
48
+
49
+ {{ out_of_scope_use | default("[More Information Needed]", true)}}
50
+
51
+ ## Dataset Structure
52
+
53
+ <!-- This section provides a description of the dataset fields, and additional information about the dataset structure such as criteria used to create the splits, relationships between data points, etc. -->
54
+
55
+ {{ dataset_structure | default("[More Information Needed]", true)}}
56
+
57
+ ## Dataset Creation
58
+
59
+ ### Curation Rationale
60
+
61
+ <!-- Motivation for the creation of this dataset. -->
62
+
63
+ {{ curation_rationale_section | default("[More Information Needed]", true)}}
64
+
65
+ ### Source Data
66
+
67
+ <!-- This section describes the source data (e.g. news text and headlines, social media posts, translated sentences, ...). -->
68
+
69
+ #### Data Collection and Processing
70
+
71
+ <!-- This section describes the data collection and processing process such as data selection criteria, filtering and normalization methods, tools and libraries used, etc. -->
72
+
73
+ {{ data_collection_and_processing_section | default("[More Information Needed]", true)}}
74
+
75
+ #### Who are the source data producers?
76
+
77
+ <!-- This section describes the people or systems who originally created the data. It should also include self-reported demographic or identity information for the source data creators if this information is available. -->
78
+
79
+ {{ source_data_producers_section | default("[More Information Needed]", true)}}
80
+
81
+ ### Annotations [optional]
82
+
83
+ <!-- If the dataset contains annotations which are not part of the initial data collection, use this section to describe them. -->
84
+
85
+ #### Annotation process
86
+
87
+ <!-- This section describes the annotation process such as annotation tools used in the process, the amount of data annotated, annotation guidelines provided to the annotators, interannotator statistics, annotation validation, etc. -->
88
+
89
+ {{ annotation_process_section | default("[More Information Needed]", true)}}
90
+
91
+ #### Who are the annotators?
92
+
93
+ <!-- This section describes the people or systems who created the annotations. -->
94
+
95
+ {{ who_are_annotators_section | default("[More Information Needed]", true)}}
96
+
97
+ #### Personal and Sensitive Information
98
+
99
+ <!-- State whether the dataset contains data that might be considered personal, sensitive, or private (e.g., data that reveals addresses, uniquely identifiable names or aliases, racial or ethnic origins, sexual orientations, religious beliefs, political opinions, financial or health data, etc.). If efforts were made to anonymize the data, describe the anonymization process. -->
100
+
101
+ {{ personal_and_sensitive_information | default("[More Information Needed]", true)}}
102
+
103
+ ## Bias, Risks, and Limitations
104
+
105
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
106
+
107
+ {{ bias_risks_limitations | default("[More Information Needed]", true)}}
108
+
109
+ ### Recommendations
110
+
111
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
112
+
113
+ {{ bias_recommendations | default("Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.", true)}}
114
+
115
+ ## Citation [optional]
116
+
117
+ <!-- If there is a paper or blog post introducing the dataset, the APA and Bibtex information for that should go in this section. -->
118
+
119
+ **BibTeX:**
120
+
121
+ {{ citation_bibtex | default("[More Information Needed]", true)}}
122
+
123
+ **APA:**
124
+
125
+ {{ citation_apa | default("[More Information Needed]", true)}}
126
+
127
+ ## Glossary [optional]
128
+
129
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the dataset or dataset card. -->
130
+
131
+ {{ glossary | default("[More Information Needed]", true)}}
132
+
133
+ ## More Information [optional]
134
+
135
+ {{ more_information | default("[More Information Needed]", true)}}
136
+
137
+ ## Dataset Card Authors [optional]
138
+
139
+ {{ dataset_card_authors | default("[More Information Needed]", true)}}
140
+
141
+ ## Dataset Card Contact
142
+
143
+ {{ dataset_card_contact | default("[More Information Needed]", true)}}
env-llmeval/lib/python3.10/site-packages/huggingface_hub/templates/modelcard_template.md ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ # For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
3
+ # Doc / guide: https://huggingface.co/docs/hub/model-cards
4
+ {{ card_data }}
5
+ ---
6
+
7
+ # Model Card for {{ model_id | default("Model ID", true) }}
8
+
9
+ <!-- Provide a quick summary of what the model is/does. -->
10
+
11
+ {{ model_summary | default("", true) }}
12
+
13
+ ## Model Details
14
+
15
+ ### Model Description
16
+
17
+ <!-- Provide a longer summary of what this model is. -->
18
+
19
+ {{ model_description | default("", true) }}
20
+
21
+ - **Developed by:** {{ developers | default("[More Information Needed]", true)}}
22
+ - **Funded by [optional]:** {{ funded_by | default("[More Information Needed]", true)}}
23
+ - **Shared by [optional]:** {{ shared_by | default("[More Information Needed]", true)}}
24
+ - **Model type:** {{ model_type | default("[More Information Needed]", true)}}
25
+ - **Language(s) (NLP):** {{ language | default("[More Information Needed]", true)}}
26
+ - **License:** {{ license | default("[More Information Needed]", true)}}
27
+ - **Finetuned from model [optional]:** {{ base_model | default("[More Information Needed]", true)}}
28
+
29
+ ### Model Sources [optional]
30
+
31
+ <!-- Provide the basic links for the model. -->
32
+
33
+ - **Repository:** {{ repo | default("[More Information Needed]", true)}}
34
+ - **Paper [optional]:** {{ paper | default("[More Information Needed]", true)}}
35
+ - **Demo [optional]:** {{ demo | default("[More Information Needed]", true)}}
36
+
37
+ ## Uses
38
+
39
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
40
+
41
+ ### Direct Use
42
+
43
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
44
+
45
+ {{ direct_use | default("[More Information Needed]", true)}}
46
+
47
+ ### Downstream Use [optional]
48
+
49
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
50
+
51
+ {{ downstream_use | default("[More Information Needed]", true)}}
52
+
53
+ ### Out-of-Scope Use
54
+
55
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
56
+
57
+ {{ out_of_scope_use | default("[More Information Needed]", true)}}
58
+
59
+ ## Bias, Risks, and Limitations
60
+
61
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
62
+
63
+ {{ bias_risks_limitations | default("[More Information Needed]", true)}}
64
+
65
+ ### Recommendations
66
+
67
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
68
+
69
+ {{ bias_recommendations | default("Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.", true)}}
70
+
71
+ ## How to Get Started with the Model
72
+
73
+ Use the code below to get started with the model.
74
+
75
+ {{ get_started_code | default("[More Information Needed]", true)}}
76
+
77
+ ## Training Details
78
+
79
+ ### Training Data
80
+
81
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
82
+
83
+ {{ training_data | default("[More Information Needed]", true)}}
84
+
85
+ ### Training Procedure
86
+
87
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
88
+
89
+ #### Preprocessing [optional]
90
+
91
+ {{ preprocessing | default("[More Information Needed]", true)}}
92
+
93
+
94
+ #### Training Hyperparameters
95
+
96
+ - **Training regime:** {{ training_regime | default("[More Information Needed]", true)}} <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
97
+
98
+ #### Speeds, Sizes, Times [optional]
99
+
100
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
101
+
102
+ {{ speeds_sizes_times | default("[More Information Needed]", true)}}
103
+
104
+ ## Evaluation
105
+
106
+ <!-- This section describes the evaluation protocols and provides the results. -->
107
+
108
+ ### Testing Data, Factors & Metrics
109
+
110
+ #### Testing Data
111
+
112
+ <!-- This should link to a Dataset Card if possible. -->
113
+
114
+ {{ testing_data | default("[More Information Needed]", true)}}
115
+
116
+ #### Factors
117
+
118
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
119
+
120
+ {{ testing_factors | default("[More Information Needed]", true)}}
121
+
122
+ #### Metrics
123
+
124
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
125
+
126
+ {{ testing_metrics | default("[More Information Needed]", true)}}
127
+
128
+ ### Results
129
+
130
+ {{ results | default("[More Information Needed]", true)}}
131
+
132
+ #### Summary
133
+
134
+ {{ results_summary | default("", true) }}
135
+
136
+ ## Model Examination [optional]
137
+
138
+ <!-- Relevant interpretability work for the model goes here -->
139
+
140
+ {{ model_examination | default("[More Information Needed]", true)}}
141
+
142
+ ## Environmental Impact
143
+
144
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
145
+
146
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
147
+
148
+ - **Hardware Type:** {{ hardware_type | default("[More Information Needed]", true)}}
149
+ - **Hours used:** {{ hours_used | default("[More Information Needed]", true)}}
150
+ - **Cloud Provider:** {{ cloud_provider | default("[More Information Needed]", true)}}
151
+ - **Compute Region:** {{ cloud_region | default("[More Information Needed]", true)}}
152
+ - **Carbon Emitted:** {{ co2_emitted | default("[More Information Needed]", true)}}
153
+
154
+ ## Technical Specifications [optional]
155
+
156
+ ### Model Architecture and Objective
157
+
158
+ {{ model_specs | default("[More Information Needed]", true)}}
159
+
160
+ ### Compute Infrastructure
161
+
162
+ {{ compute_infrastructure | default("[More Information Needed]", true)}}
163
+
164
+ #### Hardware
165
+
166
+ {{ hardware_requirements | default("[More Information Needed]", true)}}
167
+
168
+ #### Software
169
+
170
+ {{ software | default("[More Information Needed]", true)}}
171
+
172
+ ## Citation [optional]
173
+
174
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
175
+
176
+ **BibTeX:**
177
+
178
+ {{ citation_bibtex | default("[More Information Needed]", true)}}
179
+
180
+ **APA:**
181
+
182
+ {{ citation_apa | default("[More Information Needed]", true)}}
183
+
184
+ ## Glossary [optional]
185
+
186
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
187
+
188
+ {{ glossary | default("[More Information Needed]", true)}}
189
+
190
+ ## More Information [optional]
191
+
192
+ {{ more_information | default("[More Information Needed]", true)}}
193
+
194
+ ## Model Card Authors [optional]
195
+
196
+ {{ model_card_authors | default("[More Information Needed]", true)}}
197
+
198
+ ## Model Card Contact
199
+
200
+ {{ model_card_contact | default("[More Information Needed]", true)}}
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License
16
+
17
+ # ruff: noqa: F401
18
+
19
+ from . import tqdm as _tqdm # _tqdm is the module
20
+ from ._cache_assets import cached_assets_path
21
+ from ._cache_manager import (
22
+ CachedFileInfo,
23
+ CachedRepoInfo,
24
+ CachedRevisionInfo,
25
+ CacheNotFound,
26
+ CorruptedCacheException,
27
+ DeleteCacheStrategy,
28
+ HFCacheInfo,
29
+ scan_cache_dir,
30
+ )
31
+ from ._chunk_utils import chunk_iterable
32
+ from ._datetime import parse_datetime
33
+ from ._errors import (
34
+ BadRequestError,
35
+ DisabledRepoError,
36
+ EntryNotFoundError,
37
+ FileMetadataError,
38
+ GatedRepoError,
39
+ HfHubHTTPError,
40
+ LocalEntryNotFoundError,
41
+ RepositoryNotFoundError,
42
+ RevisionNotFoundError,
43
+ hf_raise_for_status,
44
+ )
45
+ from ._experimental import experimental
46
+ from ._fixes import SoftTemporaryDirectory, WeakFileLock, yaml_dump
47
+ from ._git_credential import list_credential_helpers, set_git_credential, unset_git_credential
48
+ from ._headers import LocalTokenNotFoundError, build_hf_headers, get_token_to_send
49
+ from ._hf_folder import HfFolder
50
+ from ._http import (
51
+ OfflineModeIsEnabled,
52
+ configure_http_backend,
53
+ fix_hf_endpoint_in_url,
54
+ get_session,
55
+ http_backoff,
56
+ reset_sessions,
57
+ )
58
+ from ._pagination import paginate
59
+ from ._paths import IGNORE_GIT_FOLDER_PATTERNS, filter_repo_objects
60
+ from ._runtime import (
61
+ dump_environment_info,
62
+ get_aiohttp_version,
63
+ get_fastai_version,
64
+ get_fastcore_version,
65
+ get_gradio_version,
66
+ get_graphviz_version,
67
+ get_hf_hub_version,
68
+ get_hf_transfer_version,
69
+ get_jinja_version,
70
+ get_minijinja_version,
71
+ get_numpy_version,
72
+ get_pillow_version,
73
+ get_pydantic_version,
74
+ get_pydot_version,
75
+ get_python_version,
76
+ get_tensorboard_version,
77
+ get_tf_version,
78
+ get_torch_version,
79
+ is_aiohttp_available,
80
+ is_fastai_available,
81
+ is_fastcore_available,
82
+ is_google_colab,
83
+ is_gradio_available,
84
+ is_graphviz_available,
85
+ is_hf_transfer_available,
86
+ is_jinja_available,
87
+ is_minijinja_available,
88
+ is_notebook,
89
+ is_numpy_available,
90
+ is_package_available,
91
+ is_pillow_available,
92
+ is_pydantic_available,
93
+ is_pydot_available,
94
+ is_safetensors_available,
95
+ is_tensorboard_available,
96
+ is_tf_available,
97
+ is_torch_available,
98
+ )
99
+ from ._safetensors import (
100
+ NotASafetensorsRepoError,
101
+ SafetensorsFileMetadata,
102
+ SafetensorsParsingError,
103
+ SafetensorsRepoMetadata,
104
+ TensorInfo,
105
+ )
106
+ from ._subprocess import capture_output, run_interactive_subprocess, run_subprocess
107
+ from ._telemetry import send_telemetry
108
+ from ._token import get_token
109
+ from ._typing import is_jsonable
110
+ from ._validators import (
111
+ HFValidationError,
112
+ smoothly_deprecate_use_auth_token,
113
+ validate_hf_hub_args,
114
+ validate_repo_id,
115
+ )
116
+ from .tqdm import (
117
+ are_progress_bars_disabled,
118
+ disable_progress_bars,
119
+ enable_progress_bars,
120
+ tqdm,
121
+ tqdm_stream_file,
122
+ )
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-310.pyc ADDED
Binary file (2.33 kB). View file
 
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-310.pyc ADDED
Binary file (3.93 kB). View file
 
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-310.pyc ADDED
Binary file (4.65 kB). View file
 
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_assets.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-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
+ from pathlib import Path
16
+ from typing import Union
17
+
18
+ from ..constants import HF_ASSETS_CACHE
19
+
20
+
21
+ def cached_assets_path(
22
+ library_name: str,
23
+ namespace: str = "default",
24
+ subfolder: str = "default",
25
+ *,
26
+ assets_dir: Union[str, Path, None] = None,
27
+ ):
28
+ """Return a folder path to cache arbitrary files.
29
+
30
+ `huggingface_hub` provides a canonical folder path to store assets. This is the
31
+ recommended way to integrate cache in a downstream library as it will benefit from
32
+ the builtins tools to scan and delete the cache properly.
33
+
34
+ The distinction is made between files cached from the Hub and assets. Files from the
35
+ Hub are cached in a git-aware manner and entirely managed by `huggingface_hub`. See
36
+ [related documentation](https://huggingface.co/docs/huggingface_hub/how-to-cache).
37
+ All other files that a downstream library caches are considered to be "assets"
38
+ (files downloaded from external sources, extracted from a .tar archive, preprocessed
39
+ for training,...).
40
+
41
+ Once the folder path is generated, it is guaranteed to exist and to be a directory.
42
+ The path is based on 3 levels of depth: the library name, a namespace and a
43
+ subfolder. Those 3 levels grants flexibility while allowing `huggingface_hub` to
44
+ expect folders when scanning/deleting parts of the assets cache. Within a library,
45
+ it is expected that all namespaces share the same subset of subfolder names but this
46
+ is not a mandatory rule. The downstream library has then full control on which file
47
+ structure to adopt within its cache. Namespace and subfolder are optional (would
48
+ default to a `"default/"` subfolder) but library name is mandatory as we want every
49
+ downstream library to manage its own cache.
50
+
51
+ Expected tree:
52
+ ```text
53
+ assets/
54
+ └── datasets/
55
+ │ ├── SQuAD/
56
+ │ │ ├── downloaded/
57
+ │ │ ├── extracted/
58
+ │ │ └── processed/
59
+ │ ├── Helsinki-NLP--tatoeba_mt/
60
+ │ ├── downloaded/
61
+ │ ├── extracted/
62
+ │ └── processed/
63
+ └── transformers/
64
+ ├── default/
65
+ │ ├── something/
66
+ ├── bert-base-cased/
67
+ │ ├── default/
68
+ │ └── training/
69
+ hub/
70
+ └── models--julien-c--EsperBERTo-small/
71
+ ├── blobs/
72
+ │ ├── (...)
73
+ │ ├── (...)
74
+ ├── refs/
75
+ │ └── (...)
76
+ └── [ 128] snapshots/
77
+ ├── 2439f60ef33a0d46d85da5001d52aeda5b00ce9f/
78
+ │ ├── (...)
79
+ └── bbc77c8132af1cc5cf678da3f1ddf2de43606d48/
80
+ └── (...)
81
+ ```
82
+
83
+
84
+ Args:
85
+ library_name (`str`):
86
+ Name of the library that will manage the cache folder. Example: `"dataset"`.
87
+ namespace (`str`, *optional*, defaults to "default"):
88
+ Namespace to which the data belongs. Example: `"SQuAD"`.
89
+ subfolder (`str`, *optional*, defaults to "default"):
90
+ Subfolder in which the data will be stored. Example: `extracted`.
91
+ assets_dir (`str`, `Path`, *optional*):
92
+ Path to the folder where assets are cached. This must not be the same folder
93
+ where Hub files are cached. Defaults to `HF_HOME / "assets"` if not provided.
94
+ Can also be set with `HF_ASSETS_CACHE` environment variable.
95
+
96
+ Returns:
97
+ Path to the cache folder (`Path`).
98
+
99
+ Example:
100
+ ```py
101
+ >>> from huggingface_hub import cached_assets_path
102
+
103
+ >>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="download")
104
+ PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/download')
105
+
106
+ >>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="extracted")
107
+ PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/extracted')
108
+
109
+ >>> cached_assets_path(library_name="datasets", namespace="Helsinki-NLP/tatoeba_mt")
110
+ PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/Helsinki-NLP--tatoeba_mt/default')
111
+
112
+ >>> cached_assets_path(library_name="datasets", assets_dir="/tmp/tmp123456")
113
+ PosixPath('/tmp/tmp123456/datasets/default/default')
114
+ ```
115
+ """
116
+ # Resolve assets_dir
117
+ if assets_dir is None:
118
+ assets_dir = HF_ASSETS_CACHE
119
+ assets_dir = Path(assets_dir).expanduser().resolve()
120
+
121
+ # Avoid names that could create path issues
122
+ for part in (" ", "/", "\\"):
123
+ library_name = library_name.replace(part, "--")
124
+ namespace = namespace.replace(part, "--")
125
+ subfolder = subfolder.replace(part, "--")
126
+
127
+ # Path to subfolder is created
128
+ path = assets_dir / library_name / namespace / subfolder
129
+ try:
130
+ path.mkdir(exist_ok=True, parents=True)
131
+ except (FileExistsError, NotADirectoryError):
132
+ raise ValueError(f"Corrupted assets folder: cannot create directory because of an existing file ({path}).")
133
+
134
+ # Return
135
+ return path
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_cache_manager.py ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 manage the HF cache directory."""
16
+
17
+ import os
18
+ import shutil
19
+ import time
20
+ from collections import defaultdict
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Dict, FrozenSet, List, Literal, Optional, Set, Union
24
+
25
+ from ..constants import HF_HUB_CACHE
26
+ from . import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ REPO_TYPE_T = Literal["model", "dataset", "space"]
32
+
33
+ # List of OS-created helper files that need to be ignored
34
+ FILES_TO_IGNORE = [".DS_Store"]
35
+
36
+
37
+ class CacheNotFound(Exception):
38
+ """Exception thrown when the Huggingface cache is not found."""
39
+
40
+ cache_dir: Union[str, Path]
41
+
42
+ def __init__(self, msg: str, cache_dir: Union[str, Path], *args, **kwargs):
43
+ super().__init__(msg, *args, **kwargs)
44
+ self.cache_dir = cache_dir
45
+
46
+
47
+ class CorruptedCacheException(Exception):
48
+ """Exception for any unexpected structure in the Huggingface cache-system."""
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class CachedFileInfo:
53
+ """Frozen data structure holding information about a single cached file.
54
+
55
+ Args:
56
+ file_name (`str`):
57
+ Name of the file. Example: `config.json`.
58
+ file_path (`Path`):
59
+ Path of the file in the `snapshots` directory. The file path is a symlink
60
+ referring to a blob in the `blobs` folder.
61
+ blob_path (`Path`):
62
+ Path of the blob file. This is equivalent to `file_path.resolve()`.
63
+ size_on_disk (`int`):
64
+ Size of the blob file in bytes.
65
+ blob_last_accessed (`float`):
66
+ Timestamp of the last time the blob file has been accessed (from any
67
+ revision).
68
+ blob_last_modified (`float`):
69
+ Timestamp of the last time the blob file has been modified/created.
70
+
71
+ <Tip warning={true}>
72
+
73
+ `blob_last_accessed` and `blob_last_modified` reliability can depend on the OS you
74
+ are using. See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result)
75
+ for more details.
76
+
77
+ </Tip>
78
+ """
79
+
80
+ file_name: str
81
+ file_path: Path
82
+ blob_path: Path
83
+ size_on_disk: int
84
+
85
+ blob_last_accessed: float
86
+ blob_last_modified: float
87
+
88
+ @property
89
+ def blob_last_accessed_str(self) -> str:
90
+ """
91
+ (property) Timestamp of the last time the blob file has been accessed (from any
92
+ revision), returned as a human-readable string.
93
+
94
+ Example: "2 weeks ago".
95
+ """
96
+ return _format_timesince(self.blob_last_accessed)
97
+
98
+ @property
99
+ def blob_last_modified_str(self) -> str:
100
+ """
101
+ (property) Timestamp of the last time the blob file has been modified, returned
102
+ as a human-readable string.
103
+
104
+ Example: "2 weeks ago".
105
+ """
106
+ return _format_timesince(self.blob_last_modified)
107
+
108
+ @property
109
+ def size_on_disk_str(self) -> str:
110
+ """
111
+ (property) Size of the blob file as a human-readable string.
112
+
113
+ Example: "42.2K".
114
+ """
115
+ return _format_size(self.size_on_disk)
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class CachedRevisionInfo:
120
+ """Frozen data structure holding information about a revision.
121
+
122
+ A revision correspond to a folder in the `snapshots` folder and is populated with
123
+ the exact tree structure as the repo on the Hub but contains only symlinks. A
124
+ revision can be either referenced by 1 or more `refs` or be "detached" (no refs).
125
+
126
+ Args:
127
+ commit_hash (`str`):
128
+ Hash of the revision (unique).
129
+ Example: `"9338f7b671827df886678df2bdd7cc7b4f36dffd"`.
130
+ snapshot_path (`Path`):
131
+ Path to the revision directory in the `snapshots` folder. It contains the
132
+ exact tree structure as the repo on the Hub.
133
+ files: (`FrozenSet[CachedFileInfo]`):
134
+ Set of [`~CachedFileInfo`] describing all files contained in the snapshot.
135
+ refs (`FrozenSet[str]`):
136
+ Set of `refs` pointing to this revision. If the revision has no `refs`, it
137
+ is considered detached.
138
+ Example: `{"main", "2.4.0"}` or `{"refs/pr/1"}`.
139
+ size_on_disk (`int`):
140
+ Sum of the blob file sizes that are symlink-ed by the revision.
141
+ last_modified (`float`):
142
+ Timestamp of the last time the revision has been created/modified.
143
+
144
+ <Tip warning={true}>
145
+
146
+ `last_accessed` cannot be determined correctly on a single revision as blob files
147
+ are shared across revisions.
148
+
149
+ </Tip>
150
+
151
+ <Tip warning={true}>
152
+
153
+ `size_on_disk` is not necessarily the sum of all file sizes because of possible
154
+ duplicated files. Besides, only blobs are taken into account, not the (negligible)
155
+ size of folders and symlinks.
156
+
157
+ </Tip>
158
+ """
159
+
160
+ commit_hash: str
161
+ snapshot_path: Path
162
+ size_on_disk: int
163
+ files: FrozenSet[CachedFileInfo]
164
+ refs: FrozenSet[str]
165
+
166
+ last_modified: float
167
+
168
+ @property
169
+ def last_modified_str(self) -> str:
170
+ """
171
+ (property) Timestamp of the last time the revision has been modified, returned
172
+ as a human-readable string.
173
+
174
+ Example: "2 weeks ago".
175
+ """
176
+ return _format_timesince(self.last_modified)
177
+
178
+ @property
179
+ def size_on_disk_str(self) -> str:
180
+ """
181
+ (property) Sum of the blob file sizes as a human-readable string.
182
+
183
+ Example: "42.2K".
184
+ """
185
+ return _format_size(self.size_on_disk)
186
+
187
+ @property
188
+ def nb_files(self) -> int:
189
+ """
190
+ (property) Total number of files in the revision.
191
+ """
192
+ return len(self.files)
193
+
194
+
195
+ @dataclass(frozen=True)
196
+ class CachedRepoInfo:
197
+ """Frozen data structure holding information about a cached repository.
198
+
199
+ Args:
200
+ repo_id (`str`):
201
+ Repo id of the repo on the Hub. Example: `"google/fleurs"`.
202
+ repo_type (`Literal["dataset", "model", "space"]`):
203
+ Type of the cached repo.
204
+ repo_path (`Path`):
205
+ Local path to the cached repo.
206
+ size_on_disk (`int`):
207
+ Sum of the blob file sizes in the cached repo.
208
+ nb_files (`int`):
209
+ Total number of blob files in the cached repo.
210
+ revisions (`FrozenSet[CachedRevisionInfo]`):
211
+ Set of [`~CachedRevisionInfo`] describing all revisions cached in the repo.
212
+ last_accessed (`float`):
213
+ Timestamp of the last time a blob file of the repo has been accessed.
214
+ last_modified (`float`):
215
+ Timestamp of the last time a blob file of the repo has been modified/created.
216
+
217
+ <Tip warning={true}>
218
+
219
+ `size_on_disk` is not necessarily the sum of all revisions sizes because of
220
+ duplicated files. Besides, only blobs are taken into account, not the (negligible)
221
+ size of folders and symlinks.
222
+
223
+ </Tip>
224
+
225
+ <Tip warning={true}>
226
+
227
+ `last_accessed` and `last_modified` reliability can depend on the OS you are using.
228
+ See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result)
229
+ for more details.
230
+
231
+ </Tip>
232
+ """
233
+
234
+ repo_id: str
235
+ repo_type: REPO_TYPE_T
236
+ repo_path: Path
237
+ size_on_disk: int
238
+ nb_files: int
239
+ revisions: FrozenSet[CachedRevisionInfo]
240
+
241
+ last_accessed: float
242
+ last_modified: float
243
+
244
+ @property
245
+ def last_accessed_str(self) -> str:
246
+ """
247
+ (property) Last time a blob file of the repo has been accessed, returned as a
248
+ human-readable string.
249
+
250
+ Example: "2 weeks ago".
251
+ """
252
+ return _format_timesince(self.last_accessed)
253
+
254
+ @property
255
+ def last_modified_str(self) -> str:
256
+ """
257
+ (property) Last time a blob file of the repo has been modified, returned as a
258
+ human-readable string.
259
+
260
+ Example: "2 weeks ago".
261
+ """
262
+ return _format_timesince(self.last_modified)
263
+
264
+ @property
265
+ def size_on_disk_str(self) -> str:
266
+ """
267
+ (property) Sum of the blob file sizes as a human-readable string.
268
+
269
+ Example: "42.2K".
270
+ """
271
+ return _format_size(self.size_on_disk)
272
+
273
+ @property
274
+ def refs(self) -> Dict[str, CachedRevisionInfo]:
275
+ """
276
+ (property) Mapping between `refs` and revision data structures.
277
+ """
278
+ return {ref: revision for revision in self.revisions for ref in revision.refs}
279
+
280
+
281
+ @dataclass(frozen=True)
282
+ class DeleteCacheStrategy:
283
+ """Frozen data structure holding the strategy to delete cached revisions.
284
+
285
+ This object is not meant to be instantiated programmatically but to be returned by
286
+ [`~utils.HFCacheInfo.delete_revisions`]. See documentation for usage example.
287
+
288
+ Args:
289
+ expected_freed_size (`float`):
290
+ Expected freed size once strategy is executed.
291
+ blobs (`FrozenSet[Path]`):
292
+ Set of blob file paths to be deleted.
293
+ refs (`FrozenSet[Path]`):
294
+ Set of reference file paths to be deleted.
295
+ repos (`FrozenSet[Path]`):
296
+ Set of entire repo paths to be deleted.
297
+ snapshots (`FrozenSet[Path]`):
298
+ Set of snapshots to be deleted (directory of symlinks).
299
+ """
300
+
301
+ expected_freed_size: int
302
+ blobs: FrozenSet[Path]
303
+ refs: FrozenSet[Path]
304
+ repos: FrozenSet[Path]
305
+ snapshots: FrozenSet[Path]
306
+
307
+ @property
308
+ def expected_freed_size_str(self) -> str:
309
+ """
310
+ (property) Expected size that will be freed as a human-readable string.
311
+
312
+ Example: "42.2K".
313
+ """
314
+ return _format_size(self.expected_freed_size)
315
+
316
+ def execute(self) -> None:
317
+ """Execute the defined strategy.
318
+
319
+ <Tip warning={true}>
320
+
321
+ If this method is interrupted, the cache might get corrupted. Deletion order is
322
+ implemented so that references and symlinks are deleted before the actual blob
323
+ files.
324
+
325
+ </Tip>
326
+
327
+ <Tip warning={true}>
328
+
329
+ This method is irreversible. If executed, cached files are erased and must be
330
+ downloaded again.
331
+
332
+ </Tip>
333
+ """
334
+ # Deletion order matters. Blobs are deleted in last so that the user can't end
335
+ # up in a state where a `ref`` refers to a missing snapshot or a snapshot
336
+ # symlink refers to a deleted blob.
337
+
338
+ # Delete entire repos
339
+ for path in self.repos:
340
+ _try_delete_path(path, path_type="repo")
341
+
342
+ # Delete snapshot directories
343
+ for path in self.snapshots:
344
+ _try_delete_path(path, path_type="snapshot")
345
+
346
+ # Delete refs files
347
+ for path in self.refs:
348
+ _try_delete_path(path, path_type="ref")
349
+
350
+ # Delete blob files
351
+ for path in self.blobs:
352
+ _try_delete_path(path, path_type="blob")
353
+
354
+ logger.info(f"Cache deletion done. Saved {self.expected_freed_size_str}.")
355
+
356
+
357
+ @dataclass(frozen=True)
358
+ class HFCacheInfo:
359
+ """Frozen data structure holding information about the entire cache-system.
360
+
361
+ This data structure is returned by [`scan_cache_dir`] and is immutable.
362
+
363
+ Args:
364
+ size_on_disk (`int`):
365
+ Sum of all valid repo sizes in the cache-system.
366
+ repos (`FrozenSet[CachedRepoInfo]`):
367
+ Set of [`~CachedRepoInfo`] describing all valid cached repos found on the
368
+ cache-system while scanning.
369
+ warnings (`List[CorruptedCacheException]`):
370
+ List of [`~CorruptedCacheException`] that occurred while scanning the cache.
371
+ Those exceptions are captured so that the scan can continue. Corrupted repos
372
+ are skipped from the scan.
373
+
374
+ <Tip warning={true}>
375
+
376
+ Here `size_on_disk` is equal to the sum of all repo sizes (only blobs). However if
377
+ some cached repos are corrupted, their sizes are not taken into account.
378
+
379
+ </Tip>
380
+ """
381
+
382
+ size_on_disk: int
383
+ repos: FrozenSet[CachedRepoInfo]
384
+ warnings: List[CorruptedCacheException]
385
+
386
+ @property
387
+ def size_on_disk_str(self) -> str:
388
+ """
389
+ (property) Sum of all valid repo sizes in the cache-system as a human-readable
390
+ string.
391
+
392
+ Example: "42.2K".
393
+ """
394
+ return _format_size(self.size_on_disk)
395
+
396
+ def delete_revisions(self, *revisions: str) -> DeleteCacheStrategy:
397
+ """Prepare the strategy to delete one or more revisions cached locally.
398
+
399
+ Input revisions can be any revision hash. If a revision hash is not found in the
400
+ local cache, a warning is thrown but no error is raised. Revisions can be from
401
+ different cached repos since hashes are unique across repos,
402
+
403
+ Examples:
404
+ ```py
405
+ >>> from huggingface_hub import scan_cache_dir
406
+ >>> cache_info = scan_cache_dir()
407
+ >>> delete_strategy = cache_info.delete_revisions(
408
+ ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa"
409
+ ... )
410
+ >>> print(f"Will free {delete_strategy.expected_freed_size_str}.")
411
+ Will free 7.9K.
412
+ >>> delete_strategy.execute()
413
+ Cache deletion done. Saved 7.9K.
414
+ ```
415
+
416
+ ```py
417
+ >>> from huggingface_hub import scan_cache_dir
418
+ >>> scan_cache_dir().delete_revisions(
419
+ ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa",
420
+ ... "e2983b237dccf3ab4937c97fa717319a9ca1a96d",
421
+ ... "6c0e6080953db56375760c0471a8c5f2929baf11",
422
+ ... ).execute()
423
+ Cache deletion done. Saved 8.6G.
424
+ ```
425
+
426
+ <Tip warning={true}>
427
+
428
+ `delete_revisions` returns a [`~utils.DeleteCacheStrategy`] object that needs to
429
+ be executed. The [`~utils.DeleteCacheStrategy`] is not meant to be modified but
430
+ allows having a dry run before actually executing the deletion.
431
+
432
+ </Tip>
433
+ """
434
+ hashes_to_delete: Set[str] = set(revisions)
435
+
436
+ repos_with_revisions: Dict[CachedRepoInfo, Set[CachedRevisionInfo]] = defaultdict(set)
437
+
438
+ for repo in self.repos:
439
+ for revision in repo.revisions:
440
+ if revision.commit_hash in hashes_to_delete:
441
+ repos_with_revisions[repo].add(revision)
442
+ hashes_to_delete.remove(revision.commit_hash)
443
+
444
+ if len(hashes_to_delete) > 0:
445
+ logger.warning(f"Revision(s) not found - cannot delete them: {', '.join(hashes_to_delete)}")
446
+
447
+ delete_strategy_blobs: Set[Path] = set()
448
+ delete_strategy_refs: Set[Path] = set()
449
+ delete_strategy_repos: Set[Path] = set()
450
+ delete_strategy_snapshots: Set[Path] = set()
451
+ delete_strategy_expected_freed_size = 0
452
+
453
+ for affected_repo, revisions_to_delete in repos_with_revisions.items():
454
+ other_revisions = affected_repo.revisions - revisions_to_delete
455
+
456
+ # If no other revisions, it means all revisions are deleted
457
+ # -> delete the entire cached repo
458
+ if len(other_revisions) == 0:
459
+ delete_strategy_repos.add(affected_repo.repo_path)
460
+ delete_strategy_expected_freed_size += affected_repo.size_on_disk
461
+ continue
462
+
463
+ # Some revisions of the repo will be deleted but not all. We need to filter
464
+ # which blob files will not be linked anymore.
465
+ for revision_to_delete in revisions_to_delete:
466
+ # Snapshot dir
467
+ delete_strategy_snapshots.add(revision_to_delete.snapshot_path)
468
+
469
+ # Refs dir
470
+ for ref in revision_to_delete.refs:
471
+ delete_strategy_refs.add(affected_repo.repo_path / "refs" / ref)
472
+
473
+ # Blobs dir
474
+ for file in revision_to_delete.files:
475
+ if file.blob_path not in delete_strategy_blobs:
476
+ is_file_alone = True
477
+ for revision in other_revisions:
478
+ for rev_file in revision.files:
479
+ if file.blob_path == rev_file.blob_path:
480
+ is_file_alone = False
481
+ break
482
+ if not is_file_alone:
483
+ break
484
+
485
+ # Blob file not referenced by remaining revisions -> delete
486
+ if is_file_alone:
487
+ delete_strategy_blobs.add(file.blob_path)
488
+ delete_strategy_expected_freed_size += file.size_on_disk
489
+
490
+ # Return the strategy instead of executing it.
491
+ return DeleteCacheStrategy(
492
+ blobs=frozenset(delete_strategy_blobs),
493
+ refs=frozenset(delete_strategy_refs),
494
+ repos=frozenset(delete_strategy_repos),
495
+ snapshots=frozenset(delete_strategy_snapshots),
496
+ expected_freed_size=delete_strategy_expected_freed_size,
497
+ )
498
+
499
+
500
+ def scan_cache_dir(cache_dir: Optional[Union[str, Path]] = None) -> HFCacheInfo:
501
+ """Scan the entire HF cache-system and return a [`~HFCacheInfo`] structure.
502
+
503
+ Use `scan_cache_dir` in order to programmatically scan your cache-system. The cache
504
+ will be scanned repo by repo. If a repo is corrupted, a [`~CorruptedCacheException`]
505
+ will be thrown internally but captured and returned in the [`~HFCacheInfo`]
506
+ structure. Only valid repos get a proper report.
507
+
508
+ ```py
509
+ >>> from huggingface_hub import scan_cache_dir
510
+
511
+ >>> hf_cache_info = scan_cache_dir()
512
+ HFCacheInfo(
513
+ size_on_disk=3398085269,
514
+ repos=frozenset({
515
+ CachedRepoInfo(
516
+ repo_id='t5-small',
517
+ repo_type='model',
518
+ repo_path=PosixPath(...),
519
+ size_on_disk=970726914,
520
+ nb_files=11,
521
+ revisions=frozenset({
522
+ CachedRevisionInfo(
523
+ commit_hash='d78aea13fa7ecd06c29e3e46195d6341255065d5',
524
+ size_on_disk=970726339,
525
+ snapshot_path=PosixPath(...),
526
+ files=frozenset({
527
+ CachedFileInfo(
528
+ file_name='config.json',
529
+ size_on_disk=1197
530
+ file_path=PosixPath(...),
531
+ blob_path=PosixPath(...),
532
+ ),
533
+ CachedFileInfo(...),
534
+ ...
535
+ }),
536
+ ),
537
+ CachedRevisionInfo(...),
538
+ ...
539
+ }),
540
+ ),
541
+ CachedRepoInfo(...),
542
+ ...
543
+ }),
544
+ warnings=[
545
+ CorruptedCacheException("Snapshots dir doesn't exist in cached repo: ..."),
546
+ CorruptedCacheException(...),
547
+ ...
548
+ ],
549
+ )
550
+ ```
551
+
552
+ You can also print a detailed report directly from the `huggingface-cli` using:
553
+ ```text
554
+ > huggingface-cli scan-cache
555
+ REPO ID REPO TYPE SIZE ON DISK NB FILES REFS LOCAL PATH
556
+ --------------------------- --------- ------------ -------- ------------------- -------------------------------------------------------------------------
557
+ glue dataset 116.3K 15 1.17.0, main, 2.4.0 /Users/lucain/.cache/huggingface/hub/datasets--glue
558
+ google/fleurs dataset 64.9M 6 main, refs/pr/1 /Users/lucain/.cache/huggingface/hub/datasets--google--fleurs
559
+ Jean-Baptiste/camembert-ner model 441.0M 7 main /Users/lucain/.cache/huggingface/hub/models--Jean-Baptiste--camembert-ner
560
+ bert-base-cased model 1.9G 13 main /Users/lucain/.cache/huggingface/hub/models--bert-base-cased
561
+ t5-base model 10.1K 3 main /Users/lucain/.cache/huggingface/hub/models--t5-base
562
+ t5-small model 970.7M 11 refs/pr/1, main /Users/lucain/.cache/huggingface/hub/models--t5-small
563
+
564
+ Done in 0.0s. Scanned 6 repo(s) for a total of 3.4G.
565
+ Got 1 warning(s) while scanning. Use -vvv to print details.
566
+ ```
567
+
568
+ Args:
569
+ cache_dir (`str` or `Path`, `optional`):
570
+ Cache directory to cache. Defaults to the default HF cache directory.
571
+
572
+ <Tip warning={true}>
573
+
574
+ Raises:
575
+
576
+ `CacheNotFound`
577
+ If the cache directory does not exist.
578
+
579
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
580
+ If the cache directory is a file, instead of a directory.
581
+
582
+ </Tip>
583
+
584
+ Returns: a [`~HFCacheInfo`] object.
585
+ """
586
+ if cache_dir is None:
587
+ cache_dir = HF_HUB_CACHE
588
+
589
+ cache_dir = Path(cache_dir).expanduser().resolve()
590
+ if not cache_dir.exists():
591
+ raise CacheNotFound(
592
+ f"Cache directory not found: {cache_dir}. Please use `cache_dir` argument or set `HF_HUB_CACHE` environment variable.",
593
+ cache_dir=cache_dir,
594
+ )
595
+
596
+ if cache_dir.is_file():
597
+ raise ValueError(
598
+ f"Scan cache expects a directory but found a file: {cache_dir}. Please use `cache_dir` argument or set `HF_HUB_CACHE` environment variable."
599
+ )
600
+
601
+ repos: Set[CachedRepoInfo] = set()
602
+ warnings: List[CorruptedCacheException] = []
603
+ for repo_path in cache_dir.iterdir():
604
+ if repo_path.name == ".locks": # skip './.locks/' folder
605
+ continue
606
+ try:
607
+ repos.add(_scan_cached_repo(repo_path))
608
+ except CorruptedCacheException as e:
609
+ warnings.append(e)
610
+
611
+ return HFCacheInfo(
612
+ repos=frozenset(repos),
613
+ size_on_disk=sum(repo.size_on_disk for repo in repos),
614
+ warnings=warnings,
615
+ )
616
+
617
+
618
+ def _scan_cached_repo(repo_path: Path) -> CachedRepoInfo:
619
+ """Scan a single cache repo and return information about it.
620
+
621
+ Any unexpected behavior will raise a [`~CorruptedCacheException`].
622
+ """
623
+ if not repo_path.is_dir():
624
+ raise CorruptedCacheException(f"Repo path is not a directory: {repo_path}")
625
+
626
+ if "--" not in repo_path.name:
627
+ raise CorruptedCacheException(f"Repo path is not a valid HuggingFace cache directory: {repo_path}")
628
+
629
+ repo_type, repo_id = repo_path.name.split("--", maxsplit=1)
630
+ repo_type = repo_type[:-1] # "models" -> "model"
631
+ repo_id = repo_id.replace("--", "/") # google/fleurs -> "google/fleurs"
632
+
633
+ if repo_type not in {"dataset", "model", "space"}:
634
+ raise CorruptedCacheException(
635
+ f"Repo type must be `dataset`, `model` or `space`, found `{repo_type}` ({repo_path})."
636
+ )
637
+
638
+ blob_stats: Dict[Path, os.stat_result] = {} # Key is blob_path, value is blob stats
639
+
640
+ snapshots_path = repo_path / "snapshots"
641
+ refs_path = repo_path / "refs"
642
+
643
+ if not snapshots_path.exists() or not snapshots_path.is_dir():
644
+ raise CorruptedCacheException(f"Snapshots dir doesn't exist in cached repo: {snapshots_path}")
645
+
646
+ # Scan over `refs` directory
647
+
648
+ # key is revision hash, value is set of refs
649
+ refs_by_hash: Dict[str, Set[str]] = defaultdict(set)
650
+ if refs_path.exists():
651
+ # Example of `refs` directory
652
+ # ── refs
653
+ # ├── main
654
+ # └── refs
655
+ # └── pr
656
+ # └── 1
657
+ if refs_path.is_file():
658
+ raise CorruptedCacheException(f"Refs directory cannot be a file: {refs_path}")
659
+
660
+ for ref_path in refs_path.glob("**/*"):
661
+ # glob("**/*") iterates over all files and directories -> skip directories
662
+ if ref_path.is_dir():
663
+ continue
664
+
665
+ ref_name = str(ref_path.relative_to(refs_path))
666
+ with ref_path.open() as f:
667
+ commit_hash = f.read()
668
+
669
+ refs_by_hash[commit_hash].add(ref_name)
670
+
671
+ # Scan snapshots directory
672
+ cached_revisions: Set[CachedRevisionInfo] = set()
673
+ for revision_path in snapshots_path.iterdir():
674
+ # Ignore OS-created helper files
675
+ if revision_path.name in FILES_TO_IGNORE:
676
+ continue
677
+ if revision_path.is_file():
678
+ raise CorruptedCacheException(f"Snapshots folder corrupted. Found a file: {revision_path}")
679
+
680
+ cached_files = set()
681
+ for file_path in revision_path.glob("**/*"):
682
+ # glob("**/*") iterates over all files and directories -> skip directories
683
+ if file_path.is_dir():
684
+ continue
685
+
686
+ blob_path = Path(file_path).resolve()
687
+ if not blob_path.exists():
688
+ raise CorruptedCacheException(f"Blob missing (broken symlink): {blob_path}")
689
+
690
+ if blob_path not in blob_stats:
691
+ blob_stats[blob_path] = blob_path.stat()
692
+
693
+ cached_files.add(
694
+ CachedFileInfo(
695
+ file_name=file_path.name,
696
+ file_path=file_path,
697
+ size_on_disk=blob_stats[blob_path].st_size,
698
+ blob_path=blob_path,
699
+ blob_last_accessed=blob_stats[blob_path].st_atime,
700
+ blob_last_modified=blob_stats[blob_path].st_mtime,
701
+ )
702
+ )
703
+
704
+ # Last modified is either the last modified blob file or the revision folder
705
+ # itself if it is empty
706
+ if len(cached_files) > 0:
707
+ revision_last_modified = max(blob_stats[file.blob_path].st_mtime for file in cached_files)
708
+ else:
709
+ revision_last_modified = revision_path.stat().st_mtime
710
+
711
+ cached_revisions.add(
712
+ CachedRevisionInfo(
713
+ commit_hash=revision_path.name,
714
+ files=frozenset(cached_files),
715
+ refs=frozenset(refs_by_hash.pop(revision_path.name, set())),
716
+ size_on_disk=sum(
717
+ blob_stats[blob_path].st_size for blob_path in set(file.blob_path for file in cached_files)
718
+ ),
719
+ snapshot_path=revision_path,
720
+ last_modified=revision_last_modified,
721
+ )
722
+ )
723
+
724
+ # Check that all refs referred to an existing revision
725
+ if len(refs_by_hash) > 0:
726
+ raise CorruptedCacheException(
727
+ f"Reference(s) refer to missing commit hashes: {dict(refs_by_hash)} ({repo_path})."
728
+ )
729
+
730
+ # Last modified is either the last modified blob file or the repo folder itself if
731
+ # no blob files has been found. Same for last accessed.
732
+ if len(blob_stats) > 0:
733
+ repo_last_accessed = max(stat.st_atime for stat in blob_stats.values())
734
+ repo_last_modified = max(stat.st_mtime for stat in blob_stats.values())
735
+ else:
736
+ repo_stats = repo_path.stat()
737
+ repo_last_accessed = repo_stats.st_atime
738
+ repo_last_modified = repo_stats.st_mtime
739
+
740
+ # Build and return frozen structure
741
+ return CachedRepoInfo(
742
+ nb_files=len(blob_stats),
743
+ repo_id=repo_id,
744
+ repo_path=repo_path,
745
+ repo_type=repo_type, # type: ignore
746
+ revisions=frozenset(cached_revisions),
747
+ size_on_disk=sum(stat.st_size for stat in blob_stats.values()),
748
+ last_accessed=repo_last_accessed,
749
+ last_modified=repo_last_modified,
750
+ )
751
+
752
+
753
+ def _format_size(num: int) -> str:
754
+ """Format size in bytes into a human-readable string.
755
+
756
+ Taken from https://stackoverflow.com/a/1094933
757
+ """
758
+ num_f = float(num)
759
+ for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
760
+ if abs(num_f) < 1000.0:
761
+ return f"{num_f:3.1f}{unit}"
762
+ num_f /= 1000.0
763
+ return f"{num_f:.1f}Y"
764
+
765
+
766
+ _TIMESINCE_CHUNKS = (
767
+ # Label, divider, max value
768
+ ("second", 1, 60),
769
+ ("minute", 60, 60),
770
+ ("hour", 60 * 60, 24),
771
+ ("day", 60 * 60 * 24, 6),
772
+ ("week", 60 * 60 * 24 * 7, 6),
773
+ ("month", 60 * 60 * 24 * 30, 11),
774
+ ("year", 60 * 60 * 24 * 365, None),
775
+ )
776
+
777
+
778
+ def _format_timesince(ts: float) -> str:
779
+ """Format timestamp in seconds into a human-readable string, relative to now.
780
+
781
+ Vaguely inspired by Django's `timesince` formatter.
782
+ """
783
+ delta = time.time() - ts
784
+ if delta < 20:
785
+ return "a few seconds ago"
786
+ for label, divider, max_value in _TIMESINCE_CHUNKS: # noqa: B007
787
+ value = round(delta / divider)
788
+ if max_value is not None and value <= max_value:
789
+ break
790
+ return f"{value} {label}{'s' if value > 1 else ''} ago"
791
+
792
+
793
+ def _try_delete_path(path: Path, path_type: str) -> None:
794
+ """Try to delete a local file or folder.
795
+
796
+ If the path does not exists, error is logged as a warning and then ignored.
797
+
798
+ Args:
799
+ path (`Path`)
800
+ Path to delete. Can be a file or a folder.
801
+ path_type (`str`)
802
+ What path are we deleting ? Only for logging purposes. Example: "snapshot".
803
+ """
804
+ logger.info(f"Delete {path_type}: {path}")
805
+ try:
806
+ if path.is_file():
807
+ os.remove(path)
808
+ else:
809
+ shutil.rmtree(path)
810
+ except FileNotFoundError:
811
+ logger.warning(f"Couldn't delete {path_type}: file not found ({path})", exc_info=True)
812
+ except PermissionError:
813
+ logger.warning(f"Couldn't delete {path_type}: permission denied ({path})", exc_info=True)
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_chunk_utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 a utility to iterate by chunks over an iterator."""
16
+
17
+ import itertools
18
+ from typing import Iterable, TypeVar
19
+
20
+
21
+ T = TypeVar("T")
22
+
23
+
24
+ def chunk_iterable(iterable: Iterable[T], chunk_size: int) -> Iterable[Iterable[T]]:
25
+ """Iterates over an iterator chunk by chunk.
26
+
27
+ Taken from https://stackoverflow.com/a/8998040.
28
+ See also https://github.com/huggingface/huggingface_hub/pull/920#discussion_r938793088.
29
+
30
+ Args:
31
+ iterable (`Iterable`):
32
+ The iterable on which we want to iterate.
33
+ chunk_size (`int`):
34
+ Size of the chunks. Must be a strictly positive integer (e.g. >0).
35
+
36
+ Example:
37
+
38
+ ```python
39
+ >>> from huggingface_hub.utils import chunk_iterable
40
+
41
+ >>> for items in chunk_iterable(range(17), chunk_size=8):
42
+ ... print(items)
43
+ # [0, 1, 2, 3, 4, 5, 6, 7]
44
+ # [8, 9, 10, 11, 12, 13, 14, 15]
45
+ # [16] # smaller last chunk
46
+ ```
47
+
48
+ Raises:
49
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
50
+ If `chunk_size` <= 0.
51
+
52
+ <Tip warning={true}>
53
+ The last chunk can be smaller than `chunk_size`.
54
+ </Tip>
55
+ """
56
+ if not isinstance(chunk_size, int) or chunk_size <= 0:
57
+ raise ValueError("`chunk_size` must be a strictly positive integer (>0).")
58
+
59
+ iterator = iter(iterable)
60
+ while True:
61
+ try:
62
+ next_item = next(iterator)
63
+ except StopIteration:
64
+ return
65
+ yield itertools.chain((next_item,), itertools.islice(iterator, chunk_size - 1))
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_datetime.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 datetimes in Huggingface Hub."""
16
+
17
+ from datetime import datetime, timezone
18
+
19
+
20
+ def parse_datetime(date_string: str) -> datetime:
21
+ """
22
+ Parses a date_string returned from the server to a datetime object.
23
+
24
+ This parser is a weak-parser is the sense that it handles only a single format of
25
+ date_string. It is expected that the server format will never change. The
26
+ implementation depends only on the standard lib to avoid an external dependency
27
+ (python-dateutil). See full discussion about this decision on PR:
28
+ https://github.com/huggingface/huggingface_hub/pull/999.
29
+
30
+ Example:
31
+ ```py
32
+ > parse_datetime('2022-08-19T07:19:38.123Z')
33
+ datetime.datetime(2022, 8, 19, 7, 19, 38, 123000, tzinfo=timezone.utc)
34
+ ```
35
+
36
+ Args:
37
+ date_string (`str`):
38
+ A string representing a datetime returned by the Hub server.
39
+ String is expected to follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern.
40
+
41
+ Returns:
42
+ A python datetime object.
43
+
44
+ Raises:
45
+ :class:`ValueError`:
46
+ If `date_string` cannot be parsed.
47
+ """
48
+ try:
49
+ # Datetime ending with a Z means "UTC". We parse the date and then explicitly
50
+ # set the timezone to UTC.
51
+ # See https://en.wikipedia.org/wiki/ISO_8601#Coordinated_Universal_Time_(UTC)
52
+ # Taken from https://stackoverflow.com/a/3168394.
53
+ if len(date_string) == 30:
54
+ # Means timezoned-timestamp with nanoseconds precision. We need to truncate the last 3 digits.
55
+ date_string = date_string[:-4] + "Z"
56
+ dt = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ")
57
+ return dt.replace(tzinfo=timezone.utc) # Set explicit timezone
58
+ except ValueError as e:
59
+ raise ValueError(
60
+ f"Cannot parse '{date_string}' as a datetime. Date string is expected to"
61
+ " follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern."
62
+ ) from e
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_deprecation.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from functools import wraps
3
+ from inspect import Parameter, signature
4
+ from typing import Iterable, Optional
5
+
6
+
7
+ def _deprecate_positional_args(*, version: str):
8
+ """Decorator for methods that issues warnings for positional arguments.
9
+ Using the keyword-only argument syntax in pep 3102, arguments after the
10
+ * will issue a warning when passed as a positional argument.
11
+
12
+ Args:
13
+ version (`str`):
14
+ The version when positional arguments will result in error.
15
+ """
16
+
17
+ def _inner_deprecate_positional_args(f):
18
+ sig = signature(f)
19
+ kwonly_args = []
20
+ all_args = []
21
+ for name, param in sig.parameters.items():
22
+ if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
23
+ all_args.append(name)
24
+ elif param.kind == Parameter.KEYWORD_ONLY:
25
+ kwonly_args.append(name)
26
+
27
+ @wraps(f)
28
+ def inner_f(*args, **kwargs):
29
+ extra_args = len(args) - len(all_args)
30
+ if extra_args <= 0:
31
+ return f(*args, **kwargs)
32
+ # extra_args > 0
33
+ args_msg = [
34
+ f"{name}='{arg}'" if isinstance(arg, str) else f"{name}={arg}"
35
+ for name, arg in zip(kwonly_args[:extra_args], args[-extra_args:])
36
+ ]
37
+ args_msg = ", ".join(args_msg)
38
+ warnings.warn(
39
+ f"Deprecated positional argument(s) used in '{f.__name__}': pass"
40
+ f" {args_msg} as keyword args. From version {version} passing these"
41
+ " as positional arguments will result in an error,",
42
+ FutureWarning,
43
+ )
44
+ kwargs.update(zip(sig.parameters, args))
45
+ return f(**kwargs)
46
+
47
+ return inner_f
48
+
49
+ return _inner_deprecate_positional_args
50
+
51
+
52
+ def _deprecate_arguments(
53
+ *,
54
+ version: str,
55
+ deprecated_args: Iterable[str],
56
+ custom_message: Optional[str] = None,
57
+ ):
58
+ """Decorator to issue warnings when using deprecated arguments.
59
+
60
+ TODO: could be useful to be able to set a custom error message.
61
+
62
+ Args:
63
+ version (`str`):
64
+ The version when deprecated arguments will result in error.
65
+ deprecated_args (`List[str]`):
66
+ List of the arguments to be deprecated.
67
+ custom_message (`str`, *optional*):
68
+ Warning message that is raised. If not passed, a default warning message
69
+ will be created.
70
+ """
71
+
72
+ def _inner_deprecate_positional_args(f):
73
+ sig = signature(f)
74
+
75
+ @wraps(f)
76
+ def inner_f(*args, **kwargs):
77
+ # Check for used deprecated arguments
78
+ used_deprecated_args = []
79
+ for _, parameter in zip(args, sig.parameters.values()):
80
+ if parameter.name in deprecated_args:
81
+ used_deprecated_args.append(parameter.name)
82
+ for kwarg_name, kwarg_value in kwargs.items():
83
+ if (
84
+ # If argument is deprecated but still used
85
+ kwarg_name in deprecated_args
86
+ # And then the value is not the default value
87
+ and kwarg_value != sig.parameters[kwarg_name].default
88
+ ):
89
+ used_deprecated_args.append(kwarg_name)
90
+
91
+ # Warn and proceed
92
+ if len(used_deprecated_args) > 0:
93
+ message = (
94
+ f"Deprecated argument(s) used in '{f.__name__}':"
95
+ f" {', '.join(used_deprecated_args)}. Will not be supported from"
96
+ f" version '{version}'."
97
+ )
98
+ if custom_message is not None:
99
+ message += "\n\n" + custom_message
100
+ warnings.warn(message, FutureWarning)
101
+ return f(*args, **kwargs)
102
+
103
+ return inner_f
104
+
105
+ return _inner_deprecate_positional_args
106
+
107
+
108
+ def _deprecate_method(*, version: str, message: Optional[str] = None):
109
+ """Decorator to issue warnings when using a deprecated method.
110
+
111
+ Args:
112
+ version (`str`):
113
+ The version when deprecated arguments will result in error.
114
+ message (`str`, *optional*):
115
+ Warning message that is raised. If not passed, a default warning message
116
+ will be created.
117
+ """
118
+
119
+ def _inner_deprecate_method(f):
120
+ name = f.__name__
121
+ if name == "__init__":
122
+ name = f.__qualname__.split(".")[0] # class name instead of method name
123
+
124
+ @wraps(f)
125
+ def inner_f(*args, **kwargs):
126
+ warning_message = (
127
+ f"'{name}' (from '{f.__module__}') is deprecated and will be removed from version '{version}'."
128
+ )
129
+ if message is not None:
130
+ warning_message += " " + message
131
+ warnings.warn(warning_message, FutureWarning)
132
+ return f(*args, **kwargs)
133
+
134
+ return inner_f
135
+
136
+ return _inner_deprecate_method
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Optional
3
+
4
+ from requests import HTTPError, Response
5
+
6
+ from ._fixes import JSONDecodeError
7
+
8
+
9
+ REPO_API_REGEX = re.compile(
10
+ r"""
11
+ # staging or production endpoint
12
+ ^https://[^/]+
13
+ (
14
+ # on /api/repo_type/repo_id
15
+ /api/(models|datasets|spaces)/(.+)
16
+ |
17
+ # or /repo_id/resolve/revision/...
18
+ /(.+)/resolve/(.+)
19
+ )
20
+ """,
21
+ flags=re.VERBOSE,
22
+ )
23
+
24
+
25
+ class FileMetadataError(OSError):
26
+ """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).
27
+
28
+ Inherits from `OSError` for backward compatibility.
29
+ """
30
+
31
+
32
+ class HfHubHTTPError(HTTPError):
33
+ """
34
+ HTTPError to inherit from for any custom HTTP Error raised in HF Hub.
35
+
36
+ Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is
37
+ sent back by the server, it will be added to the error message.
38
+
39
+ Added details:
40
+ - Request id from "X-Request-Id" header if exists.
41
+ - Server error message from the header "X-Error-Message".
42
+ - Server error message if we can found one in the response body.
43
+
44
+ Example:
45
+ ```py
46
+ import requests
47
+ from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
48
+
49
+ response = get_session().post(...)
50
+ try:
51
+ hf_raise_for_status(response)
52
+ except HfHubHTTPError as e:
53
+ print(str(e)) # formatted message
54
+ e.request_id, e.server_message # details returned by server
55
+
56
+ # Complete the error message with additional information once it's raised
57
+ e.append_to_message("\n`create_commit` expects the repository to exist.")
58
+ raise
59
+ ```
60
+ """
61
+
62
+ request_id: Optional[str] = None
63
+ server_message: Optional[str] = None
64
+
65
+ def __init__(self, message: str, response: Optional[Response] = None):
66
+ # Parse server information if any.
67
+ if response is not None:
68
+ self.request_id = response.headers.get("X-Request-Id")
69
+ try:
70
+ server_data = response.json()
71
+ except JSONDecodeError:
72
+ server_data = {}
73
+
74
+ # Retrieve server error message from multiple sources
75
+ server_message_from_headers = response.headers.get("X-Error-Message")
76
+ server_message_from_body = server_data.get("error")
77
+ server_multiple_messages_from_body = "\n".join(
78
+ error["message"] for error in server_data.get("errors", []) if "message" in error
79
+ )
80
+
81
+ # Concatenate error messages
82
+ _server_message = ""
83
+ if server_message_from_headers is not None: # from headers
84
+ _server_message += server_message_from_headers + "\n"
85
+ if server_message_from_body is not None: # from body "error"
86
+ if isinstance(server_message_from_body, list):
87
+ server_message_from_body = "\n".join(server_message_from_body)
88
+ if server_message_from_body not in _server_message:
89
+ _server_message += server_message_from_body + "\n"
90
+ if server_multiple_messages_from_body is not None: # from body "errors"
91
+ if server_multiple_messages_from_body not in _server_message:
92
+ _server_message += server_multiple_messages_from_body + "\n"
93
+ _server_message = _server_message.strip()
94
+
95
+ # Set message to `HfHubHTTPError` (if any)
96
+ if _server_message != "":
97
+ self.server_message = _server_message
98
+
99
+ super().__init__(
100
+ _format_error_message(
101
+ message,
102
+ request_id=self.request_id,
103
+ server_message=self.server_message,
104
+ ),
105
+ response=response, # type: ignore
106
+ request=response.request if response is not None else None, # type: ignore
107
+ )
108
+
109
+ def append_to_message(self, additional_message: str) -> None:
110
+ """Append additional information to the `HfHubHTTPError` initial message."""
111
+ self.args = (self.args[0] + additional_message,) + self.args[1:]
112
+
113
+
114
+ class RepositoryNotFoundError(HfHubHTTPError):
115
+ """
116
+ Raised when trying to access a hf.co URL with an invalid repository name, or
117
+ with a private repo name the user does not have access to.
118
+
119
+ Example:
120
+
121
+ ```py
122
+ >>> from huggingface_hub import model_info
123
+ >>> model_info("<non_existent_repository>")
124
+ (...)
125
+ huggingface_hub.utils._errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
126
+
127
+ Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
128
+ Please make sure you specified the correct `repo_id` and `repo_type`.
129
+ If the repo is private, make sure you are authenticated.
130
+ Invalid username or password.
131
+ ```
132
+ """
133
+
134
+
135
+ class GatedRepoError(RepositoryNotFoundError):
136
+ """
137
+ Raised when trying to access a gated repository for which the user is not on the
138
+ authorized list.
139
+
140
+ Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.
141
+
142
+ Example:
143
+
144
+ ```py
145
+ >>> from huggingface_hub import model_info
146
+ >>> model_info("<gated_repository>")
147
+ (...)
148
+ huggingface_hub.utils._errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
149
+
150
+ Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
151
+ Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
152
+ Visit https://huggingface.co/ardent-figment/gated-model to ask for access.
153
+ ```
154
+ """
155
+
156
+
157
+ class DisabledRepoError(HfHubHTTPError):
158
+ """
159
+ Raised when trying to access a repository that has been disabled by its author.
160
+
161
+ Example:
162
+
163
+ ```py
164
+ >>> from huggingface_hub import dataset_info
165
+ >>> dataset_info("laion/laion-art")
166
+ (...)
167
+ huggingface_hub.utils._errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)
168
+
169
+ Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.
170
+ Access to this resource is disabled.
171
+ ```
172
+ """
173
+
174
+
175
+ class RevisionNotFoundError(HfHubHTTPError):
176
+ """
177
+ Raised when trying to access a hf.co URL with a valid repository but an invalid
178
+ revision.
179
+
180
+ Example:
181
+
182
+ ```py
183
+ >>> from huggingface_hub import hf_hub_download
184
+ >>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
185
+ (...)
186
+ huggingface_hub.utils._errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
187
+
188
+ Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.
189
+ ```
190
+ """
191
+
192
+
193
+ class EntryNotFoundError(HfHubHTTPError):
194
+ """
195
+ Raised when trying to access a hf.co URL with a valid repository and revision
196
+ but an invalid filename.
197
+
198
+ Example:
199
+
200
+ ```py
201
+ >>> from huggingface_hub import hf_hub_download
202
+ >>> hf_hub_download('bert-base-cased', '<non-existent-file>')
203
+ (...)
204
+ huggingface_hub.utils._errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
205
+
206
+ Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.
207
+ ```
208
+ """
209
+
210
+
211
+ class LocalEntryNotFoundError(EntryNotFoundError, FileNotFoundError, ValueError):
212
+ """
213
+ Raised when trying to access a file or snapshot that is not on the disk when network is
214
+ disabled or unavailable (connection issue). The entry may exist on the Hub.
215
+
216
+ Note: `ValueError` type is to ensure backward compatibility.
217
+ Note: `LocalEntryNotFoundError` derives from `HTTPError` because of `EntryNotFoundError`
218
+ even when it is not a network issue.
219
+
220
+ Example:
221
+
222
+ ```py
223
+ >>> from huggingface_hub import hf_hub_download
224
+ >>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
225
+ (...)
226
+ huggingface_hub.utils._errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False.
227
+ ```
228
+ """
229
+
230
+ def __init__(self, message: str):
231
+ super().__init__(message, response=None)
232
+
233
+
234
+ class BadRequestError(HfHubHTTPError, ValueError):
235
+ """
236
+ Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.
237
+
238
+ Example:
239
+
240
+ ```py
241
+ >>> resp = requests.post("hf.co/api/check", ...)
242
+ >>> hf_raise_for_status(resp, endpoint_name="check")
243
+ huggingface_hub.utils._errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)
244
+ ```
245
+ """
246
+
247
+
248
+ def hf_raise_for_status(response: Response, endpoint_name: Optional[str] = None) -> None:
249
+ """
250
+ Internal version of `response.raise_for_status()` that will refine a
251
+ potential HTTPError. Raised exception will be an instance of `HfHubHTTPError`.
252
+
253
+ This helper is meant to be the unique method to raise_for_status when making a call
254
+ to the Hugging Face Hub.
255
+
256
+ Example:
257
+ ```py
258
+ import requests
259
+ from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
260
+
261
+ response = get_session().post(...)
262
+ try:
263
+ hf_raise_for_status(response)
264
+ except HfHubHTTPError as e:
265
+ print(str(e)) # formatted message
266
+ e.request_id, e.server_message # details returned by server
267
+
268
+ # Complete the error message with additional information once it's raised
269
+ e.append_to_message("\n`create_commit` expects the repository to exist.")
270
+ raise
271
+ ```
272
+
273
+ Args:
274
+ response (`Response`):
275
+ Response from the server.
276
+ endpoint_name (`str`, *optional*):
277
+ Name of the endpoint that has been called. If provided, the error message
278
+ will be more complete.
279
+
280
+ <Tip warning={true}>
281
+
282
+ Raises when the request has failed:
283
+
284
+ - [`~utils.RepositoryNotFoundError`]
285
+ If the repository to download from cannot be found. This may be because it
286
+ doesn't exist, because `repo_type` is not set correctly, or because the repo
287
+ is `private` and you do not have access.
288
+ - [`~utils.GatedRepoError`]
289
+ If the repository exists but is gated and the user is not on the authorized
290
+ list.
291
+ - [`~utils.RevisionNotFoundError`]
292
+ If the repository exists but the revision couldn't be find.
293
+ - [`~utils.EntryNotFoundError`]
294
+ If the repository exists but the entry (e.g. the requested file) couldn't be
295
+ find.
296
+ - [`~utils.BadRequestError`]
297
+ If request failed with a HTTP 400 BadRequest error.
298
+ - [`~utils.HfHubHTTPError`]
299
+ If request failed for a reason not listed above.
300
+
301
+ </Tip>
302
+ """
303
+ try:
304
+ response.raise_for_status()
305
+ except HTTPError as e:
306
+ error_code = response.headers.get("X-Error-Code")
307
+ error_message = response.headers.get("X-Error-Message")
308
+
309
+ if error_code == "RevisionNotFound":
310
+ message = f"{response.status_code} Client Error." + "\n\n" + f"Revision Not Found for url: {response.url}."
311
+ raise RevisionNotFoundError(message, response) from e
312
+
313
+ elif error_code == "EntryNotFound":
314
+ message = f"{response.status_code} Client Error." + "\n\n" + f"Entry Not Found for url: {response.url}."
315
+ raise EntryNotFoundError(message, response) from e
316
+
317
+ elif error_code == "GatedRepo":
318
+ message = (
319
+ f"{response.status_code} Client Error." + "\n\n" + f"Cannot access gated repo for url {response.url}."
320
+ )
321
+ raise GatedRepoError(message, response) from e
322
+
323
+ elif error_message == "Access to this resource is disabled.":
324
+ message = (
325
+ f"{response.status_code} Client Error."
326
+ + "\n\n"
327
+ + f"Cannot access repository for url {response.url}."
328
+ + "\n"
329
+ + "Access to this resource is disabled."
330
+ )
331
+ raise DisabledRepoError(message, response) from e
332
+
333
+ elif error_code == "RepoNotFound" or (
334
+ response.status_code == 401
335
+ and response.request is not None
336
+ and response.request.url is not None
337
+ and REPO_API_REGEX.search(response.request.url) is not None
338
+ ):
339
+ # 401 is misleading as it is returned for:
340
+ # - private and gated repos if user is not authenticated
341
+ # - missing repos
342
+ # => for now, we process them as `RepoNotFound` anyway.
343
+ # See https://gist.github.com/Wauplin/46c27ad266b15998ce56a6603796f0b9
344
+ message = (
345
+ f"{response.status_code} Client Error."
346
+ + "\n\n"
347
+ + f"Repository Not Found for url: {response.url}."
348
+ + "\nPlease make sure you specified the correct `repo_id` and"
349
+ " `repo_type`.\nIf you are trying to access a private or gated repo,"
350
+ " make sure you are authenticated."
351
+ )
352
+ raise RepositoryNotFoundError(message, response) from e
353
+
354
+ elif response.status_code == 400:
355
+ message = (
356
+ f"\n\nBad request for {endpoint_name} endpoint:" if endpoint_name is not None else "\n\nBad request:"
357
+ )
358
+ raise BadRequestError(message, response=response) from e
359
+
360
+ elif response.status_code == 403:
361
+ message = (
362
+ f"\n\n{response.status_code} Forbidden: {error_message}."
363
+ + f"\nCannot access content at: {response.url}."
364
+ + "\nIf you are trying to create or update content,"
365
+ + "make sure you have a token with the `write` role."
366
+ )
367
+ raise HfHubHTTPError(message, response=response) from e
368
+
369
+ # Convert `HTTPError` into a `HfHubHTTPError` to display request information
370
+ # as well (request id and/or server error message)
371
+ raise HfHubHTTPError(str(e), response=response) from e
372
+
373
+
374
+ def _format_error_message(message: str, request_id: Optional[str], server_message: Optional[str]) -> str:
375
+ """
376
+ Format the `HfHubHTTPError` error message based on initial message and information
377
+ returned by the server.
378
+
379
+ Used when initializing `HfHubHTTPError`.
380
+ """
381
+ # Add message from response body
382
+ if server_message is not None and len(server_message) > 0 and server_message.lower() not in message.lower():
383
+ if "\n\n" in message:
384
+ message += "\n" + server_message
385
+ else:
386
+ message += "\n\n" + server_message
387
+
388
+ # Add Request ID
389
+ if request_id is not None and str(request_id).lower() not in message.lower():
390
+ request_id_message = f" (Request ID: {request_id})"
391
+ if "\n" in message:
392
+ newline_index = message.index("\n")
393
+ message = message[:newline_index] + request_id_message + message[newline_index:]
394
+ else:
395
+ message += request_id_message
396
+
397
+ return message
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 flag a feature as "experimental" in Huggingface Hub."""
16
+
17
+ import warnings
18
+ from functools import wraps
19
+ from typing import Callable
20
+
21
+ from .. import constants
22
+
23
+
24
+ def experimental(fn: Callable) -> Callable:
25
+ """Decorator to flag a feature as experimental.
26
+
27
+ An experimental feature trigger a warning when used as it might be subject to breaking changes in the future.
28
+ Warnings can be disabled by setting the environment variable `HF_EXPERIMENTAL_WARNING` to `0`.
29
+
30
+ Args:
31
+ fn (`Callable`):
32
+ The function to flag as experimental.
33
+
34
+ Returns:
35
+ `Callable`: The decorated function.
36
+
37
+ Example:
38
+
39
+ ```python
40
+ >>> from huggingface_hub.utils import experimental
41
+
42
+ >>> @experimental
43
+ ... def my_function():
44
+ ... print("Hello world!")
45
+
46
+ >>> my_function()
47
+ UserWarning: 'my_function' is experimental and might be subject to breaking changes in the future. You can disable
48
+ this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment variable.
49
+ Hello world!
50
+ ```
51
+ """
52
+ # For classes, put the "experimental" around the "__new__" method => __new__ will be removed in warning message
53
+ name = fn.__qualname__[: -len(".__new__")] if fn.__qualname__.endswith(".__new__") else fn.__qualname__
54
+
55
+ @wraps(fn)
56
+ def _inner_fn(*args, **kwargs):
57
+ if not constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING:
58
+ warnings.warn(
59
+ f"'{name}' is experimental and might be subject to breaking changes in the future."
60
+ " You can disable this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment"
61
+ " variable.",
62
+ UserWarning,
63
+ )
64
+ return fn(*args, **kwargs)
65
+
66
+ return _inner_fn
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_fixes.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # JSONDecodeError was introduced in requests=2.27 released in 2022.
2
+ # This allows us to support older requests for users
3
+ # More information: https://github.com/psf/requests/pull/5856
4
+ try:
5
+ from requests import JSONDecodeError # type: ignore # noqa: F401
6
+ except ImportError:
7
+ try:
8
+ from simplejson import JSONDecodeError # type: ignore # noqa: F401
9
+ except ImportError:
10
+ from json import JSONDecodeError # type: ignore # noqa: F401
11
+ import contextlib
12
+ import os
13
+ import shutil
14
+ import stat
15
+ import tempfile
16
+ from functools import partial
17
+ from pathlib import Path
18
+ from typing import Callable, Generator, Optional, Union
19
+
20
+ import yaml
21
+ from filelock import BaseFileLock, FileLock
22
+
23
+
24
+ # Wrap `yaml.dump` to set `allow_unicode=True` by default.
25
+ #
26
+ # Example:
27
+ # ```py
28
+ # >>> yaml.dump({"emoji": "👀", "some unicode": "日本か"})
29
+ # 'emoji: "\\U0001F440"\nsome unicode: "\\u65E5\\u672C\\u304B"\n'
30
+ #
31
+ # >>> yaml_dump({"emoji": "👀", "some unicode": "日本か"})
32
+ # 'emoji: "👀"\nsome unicode: "日本か"\n'
33
+ # ```
34
+ yaml_dump: Callable[..., str] = partial(yaml.dump, stream=None, allow_unicode=True) # type: ignore
35
+
36
+
37
+ @contextlib.contextmanager
38
+ def SoftTemporaryDirectory(
39
+ suffix: Optional[str] = None,
40
+ prefix: Optional[str] = None,
41
+ dir: Optional[Union[Path, str]] = None,
42
+ **kwargs,
43
+ ) -> Generator[Path, None, None]:
44
+ """
45
+ Context manager to create a temporary directory and safely delete it.
46
+
47
+ If tmp directory cannot be deleted normally, we set the WRITE permission and retry.
48
+ If cleanup still fails, we give up but don't raise an exception. This is equivalent
49
+ to `tempfile.TemporaryDirectory(..., ignore_cleanup_errors=True)` introduced in
50
+ Python 3.10.
51
+
52
+ See https://www.scivision.dev/python-tempfile-permission-error-windows/.
53
+ """
54
+ tmpdir = tempfile.TemporaryDirectory(prefix=prefix, suffix=suffix, dir=dir, **kwargs)
55
+ yield Path(tmpdir.name).resolve()
56
+
57
+ try:
58
+ # First once with normal cleanup
59
+ shutil.rmtree(tmpdir.name)
60
+ except Exception:
61
+ # If failed, try to set write permission and retry
62
+ try:
63
+ shutil.rmtree(tmpdir.name, onerror=_set_write_permission_and_retry)
64
+ except Exception:
65
+ pass
66
+
67
+ # And finally, cleanup the tmpdir.
68
+ # If it fails again, give up but do not throw error
69
+ try:
70
+ tmpdir.cleanup()
71
+ except Exception:
72
+ pass
73
+
74
+
75
+ def _set_write_permission_and_retry(func, path, excinfo):
76
+ os.chmod(path, stat.S_IWRITE)
77
+ func(path)
78
+
79
+
80
+ @contextlib.contextmanager
81
+ def WeakFileLock(lock_file: Union[str, Path]) -> Generator[BaseFileLock, None, None]:
82
+ lock = FileLock(lock_file)
83
+ lock.acquire()
84
+
85
+ yield lock
86
+
87
+ try:
88
+ return lock.release()
89
+ except OSError:
90
+ try:
91
+ Path(lock_file).unlink()
92
+ except OSError:
93
+ pass
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_git_credential.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 manage Git credentials."""
16
+
17
+ import re
18
+ import subprocess
19
+ from typing import List, Optional
20
+
21
+ from ..constants import ENDPOINT
22
+ from ._subprocess import run_interactive_subprocess, run_subprocess
23
+
24
+
25
+ GIT_CREDENTIAL_REGEX = re.compile(
26
+ r"""
27
+ ^\s* # start of line
28
+ credential\.helper # credential.helper value
29
+ \s*=\s* # separator
30
+ (\w+) # the helper name (group 1)
31
+ (\s|$) # whitespace or end of line
32
+ """,
33
+ flags=re.MULTILINE | re.IGNORECASE | re.VERBOSE,
34
+ )
35
+
36
+
37
+ def list_credential_helpers(folder: Optional[str] = None) -> List[str]:
38
+ """Return the list of git credential helpers configured.
39
+
40
+ See https://git-scm.com/docs/gitcredentials.
41
+
42
+ Credentials are saved in all configured helpers (store, cache, macOS keychain,...).
43
+ Calls "`git credential approve`" internally. See https://git-scm.com/docs/git-credential.
44
+
45
+ Args:
46
+ folder (`str`, *optional*):
47
+ The folder in which to check the configured helpers.
48
+ """
49
+ try:
50
+ output = run_subprocess("git config --list", folder=folder).stdout
51
+ parsed = _parse_credential_output(output)
52
+ return parsed
53
+ except subprocess.CalledProcessError as exc:
54
+ raise EnvironmentError(exc.stderr)
55
+
56
+
57
+ def set_git_credential(token: str, username: str = "hf_user", folder: Optional[str] = None) -> None:
58
+ """Save a username/token pair in git credential for HF Hub registry.
59
+
60
+ Credentials are saved in all configured helpers (store, cache, macOS keychain,...).
61
+ Calls "`git credential approve`" internally. See https://git-scm.com/docs/git-credential.
62
+
63
+ Args:
64
+ username (`str`, defaults to `"hf_user"`):
65
+ A git username. Defaults to `"hf_user"`, the default user used in the Hub.
66
+ token (`str`, defaults to `"hf_user"`):
67
+ A git password. In practice, the User Access Token for the Hub.
68
+ See https://huggingface.co/settings/tokens.
69
+ folder (`str`, *optional*):
70
+ The folder in which to check the configured helpers.
71
+ """
72
+ with run_interactive_subprocess("git credential approve", folder=folder) as (
73
+ stdin,
74
+ _,
75
+ ):
76
+ stdin.write(f"url={ENDPOINT}\nusername={username.lower()}\npassword={token}\n\n")
77
+ stdin.flush()
78
+
79
+
80
+ def unset_git_credential(username: str = "hf_user", folder: Optional[str] = None) -> None:
81
+ """Erase credentials from git credential for HF Hub registry.
82
+
83
+ Credentials are erased from the configured helpers (store, cache, macOS
84
+ keychain,...), if any. If `username` is not provided, any credential configured for
85
+ HF Hub endpoint is erased.
86
+ Calls "`git credential erase`" internally. See https://git-scm.com/docs/git-credential.
87
+
88
+ Args:
89
+ username (`str`, defaults to `"hf_user"`):
90
+ A git username. Defaults to `"hf_user"`, the default user used in the Hub.
91
+ folder (`str`, *optional*):
92
+ The folder in which to check the configured helpers.
93
+ """
94
+ with run_interactive_subprocess("git credential reject", folder=folder) as (
95
+ stdin,
96
+ _,
97
+ ):
98
+ standard_input = f"url={ENDPOINT}\n"
99
+ if username is not None:
100
+ standard_input += f"username={username.lower()}\n"
101
+ standard_input += "\n"
102
+
103
+ stdin.write(standard_input)
104
+ stdin.flush()
105
+
106
+
107
+ def _parse_credential_output(output: str) -> List[str]:
108
+ """Parse the output of `git credential fill` to extract the password.
109
+
110
+ Args:
111
+ output (`str`):
112
+ The output of `git credential fill`.
113
+ """
114
+ # NOTE: If user has set an helper for a custom URL, it will not we caught here.
115
+ # Example: `credential.https://huggingface.co.helper=store`
116
+ # See: https://github.com/huggingface/huggingface_hub/pull/1138#discussion_r1013324508
117
+ return sorted( # Sort for nice printing
118
+ set( # Might have some duplicates
119
+ match[0] for match in GIT_CREDENTIAL_REGEX.findall(output)
120
+ )
121
+ )
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 headers to send in calls to Huggingface Hub."""
16
+
17
+ from typing import Dict, Optional, Union
18
+
19
+ from .. import constants
20
+ from ._runtime import (
21
+ get_fastai_version,
22
+ get_fastcore_version,
23
+ get_hf_hub_version,
24
+ get_python_version,
25
+ get_tf_version,
26
+ get_torch_version,
27
+ is_fastai_available,
28
+ is_fastcore_available,
29
+ is_tf_available,
30
+ is_torch_available,
31
+ )
32
+ from ._token import get_token
33
+ from ._validators import validate_hf_hub_args
34
+
35
+
36
+ class LocalTokenNotFoundError(EnvironmentError):
37
+ """Raised if local token is required but not found."""
38
+
39
+
40
+ @validate_hf_hub_args
41
+ def build_hf_headers(
42
+ *,
43
+ token: Optional[Union[bool, str]] = None,
44
+ is_write_action: bool = False,
45
+ library_name: Optional[str] = None,
46
+ library_version: Optional[str] = None,
47
+ user_agent: Union[Dict, str, None] = None,
48
+ headers: Optional[Dict[str, str]] = None,
49
+ ) -> Dict[str, str]:
50
+ """
51
+ Build headers dictionary to send in a HF Hub call.
52
+
53
+ By default, authorization token is always provided either from argument (explicit
54
+ use) or retrieved from the cache (implicit use). To explicitly avoid sending the
55
+ token to the Hub, set `token=False` or set the `HF_HUB_DISABLE_IMPLICIT_TOKEN`
56
+ environment variable.
57
+
58
+ In case of an API call that requires write access, an error is thrown if token is
59
+ `None` or token is an organization token (starting with `"api_org***"`).
60
+
61
+ In addition to the auth header, a user-agent is added to provide information about
62
+ the installed packages (versions of python, huggingface_hub, torch, tensorflow,
63
+ fastai and fastcore).
64
+
65
+ Args:
66
+ token (`str`, `bool`, *optional*):
67
+ The token to be sent in authorization header for the Hub call:
68
+ - if a string, it is used as the Hugging Face token
69
+ - if `True`, the token is read from the machine (cache or env variable)
70
+ - if `False`, authorization header is not set
71
+ - if `None`, the token is read from the machine only except if
72
+ `HF_HUB_DISABLE_IMPLICIT_TOKEN` env variable is set.
73
+ is_write_action (`bool`, default to `False`):
74
+ Set to True if the API call requires a write access. If `True`, the token
75
+ will be validated (cannot be `None`, cannot start by `"api_org***"`).
76
+ library_name (`str`, *optional*):
77
+ The name of the library that is making the HTTP request. Will be added to
78
+ the user-agent header.
79
+ library_version (`str`, *optional*):
80
+ The version of the library that is making the HTTP request. Will be added
81
+ to the user-agent header.
82
+ user_agent (`str`, `dict`, *optional*):
83
+ The user agent info in the form of a dictionary or a single string. It will
84
+ be completed with information about the installed packages.
85
+ headers (`dict`, *optional*):
86
+ Additional headers to include in the request. Those headers take precedence
87
+ over the ones generated by this function.
88
+
89
+ Returns:
90
+ A `Dict` of headers to pass in your API call.
91
+
92
+ Example:
93
+ ```py
94
+ >>> build_hf_headers(token="hf_***") # explicit token
95
+ {"authorization": "Bearer hf_***", "user-agent": ""}
96
+
97
+ >>> build_hf_headers(token=True) # explicitly use cached token
98
+ {"authorization": "Bearer hf_***",...}
99
+
100
+ >>> build_hf_headers(token=False) # explicitly don't use cached token
101
+ {"user-agent": ...}
102
+
103
+ >>> build_hf_headers() # implicit use of the cached token
104
+ {"authorization": "Bearer hf_***",...}
105
+
106
+ # HF_HUB_DISABLE_IMPLICIT_TOKEN=True # to set as env variable
107
+ >>> build_hf_headers() # token is not sent
108
+ {"user-agent": ...}
109
+
110
+ >>> build_hf_headers(token="api_org_***", is_write_action=True)
111
+ ValueError: You must use your personal account token for write-access methods.
112
+
113
+ >>> build_hf_headers(library_name="transformers", library_version="1.2.3")
114
+ {"authorization": ..., "user-agent": "transformers/1.2.3; hf_hub/0.10.2; python/3.10.4; tensorflow/1.55"}
115
+ ```
116
+
117
+ Raises:
118
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
119
+ If organization token is passed and "write" access is required.
120
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
121
+ If "write" access is required but token is not passed and not saved locally.
122
+ [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
123
+ If `token=True` but token is not saved locally.
124
+ """
125
+ # Get auth token to send
126
+ token_to_send = get_token_to_send(token)
127
+ _validate_token_to_send(token_to_send, is_write_action=is_write_action)
128
+
129
+ # Combine headers
130
+ hf_headers = {
131
+ "user-agent": _http_user_agent(
132
+ library_name=library_name,
133
+ library_version=library_version,
134
+ user_agent=user_agent,
135
+ )
136
+ }
137
+ if token_to_send is not None:
138
+ hf_headers["authorization"] = f"Bearer {token_to_send}"
139
+ if headers is not None:
140
+ hf_headers.update(headers)
141
+ return hf_headers
142
+
143
+
144
+ def get_token_to_send(token: Optional[Union[bool, str]]) -> Optional[str]:
145
+ """Select the token to send from either `token` or the cache."""
146
+ # Case token is explicitly provided
147
+ if isinstance(token, str):
148
+ return token
149
+
150
+ # Case token is explicitly forbidden
151
+ if token is False:
152
+ return None
153
+
154
+ # Token is not provided: we get it from local cache
155
+ cached_token = get_token()
156
+
157
+ # Case token is explicitly required
158
+ if token is True:
159
+ if cached_token is None:
160
+ raise LocalTokenNotFoundError(
161
+ "Token is required (`token=True`), but no token found. You"
162
+ " need to provide a token or be logged in to Hugging Face with"
163
+ " `huggingface-cli login` or `huggingface_hub.login`. See"
164
+ " https://huggingface.co/settings/tokens."
165
+ )
166
+ return cached_token
167
+
168
+ # Case implicit use of the token is forbidden by env variable
169
+ if constants.HF_HUB_DISABLE_IMPLICIT_TOKEN:
170
+ return None
171
+
172
+ # Otherwise: we use the cached token as the user has not explicitly forbidden it
173
+ return cached_token
174
+
175
+
176
+ def _validate_token_to_send(token: Optional[str], is_write_action: bool) -> None:
177
+ if is_write_action:
178
+ if token is None:
179
+ raise ValueError(
180
+ "Token is required (write-access action) but no token found. You need"
181
+ " to provide a token or be logged in to Hugging Face with"
182
+ " `huggingface-cli login` or `huggingface_hub.login`. See"
183
+ " https://huggingface.co/settings/tokens."
184
+ )
185
+ if token.startswith("api_org"):
186
+ raise ValueError(
187
+ "You must use your personal account token for write-access methods. To"
188
+ " generate a write-access token, go to"
189
+ " https://huggingface.co/settings/tokens"
190
+ )
191
+
192
+
193
+ def _http_user_agent(
194
+ *,
195
+ library_name: Optional[str] = None,
196
+ library_version: Optional[str] = None,
197
+ user_agent: Union[Dict, str, None] = None,
198
+ ) -> str:
199
+ """Format a user-agent string containing information about the installed packages.
200
+
201
+ Args:
202
+ library_name (`str`, *optional*):
203
+ The name of the library that is making the HTTP request.
204
+ library_version (`str`, *optional*):
205
+ The version of the library that is making the HTTP request.
206
+ user_agent (`str`, `dict`, *optional*):
207
+ The user agent info in the form of a dictionary or a single string.
208
+
209
+ Returns:
210
+ The formatted user-agent string.
211
+ """
212
+ if library_name is not None:
213
+ ua = f"{library_name}/{library_version}"
214
+ else:
215
+ ua = "unknown/None"
216
+ ua += f"; hf_hub/{get_hf_hub_version()}"
217
+ ua += f"; python/{get_python_version()}"
218
+
219
+ if not constants.HF_HUB_DISABLE_TELEMETRY:
220
+ if is_torch_available():
221
+ ua += f"; torch/{get_torch_version()}"
222
+ if is_tf_available():
223
+ ua += f"; tensorflow/{get_tf_version()}"
224
+ if is_fastai_available():
225
+ ua += f"; fastai/{get_fastai_version()}"
226
+ if is_fastcore_available():
227
+ ua += f"; fastcore/{get_fastcore_version()}"
228
+
229
+ if isinstance(user_agent, dict):
230
+ ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items())
231
+ elif isinstance(user_agent, str):
232
+ ua += "; " + user_agent
233
+
234
+ return _deduplicate_user_agent(ua)
235
+
236
+
237
+ def _deduplicate_user_agent(user_agent: str) -> str:
238
+ """Deduplicate redundant information in the generated user-agent."""
239
+ # Split around ";" > Strip whitespaces > Store as dict keys (ensure unicity) > format back as string
240
+ # Order is implicitly preserved by dictionary structure (see https://stackoverflow.com/a/53657523).
241
+ return "; ".join({key.strip(): None for key in user_agent.split(";")}.keys())
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_hf_folder.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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
+ """Contain helper class to retrieve/store token from/to local cache."""
16
+
17
+ import warnings
18
+ from pathlib import Path
19
+ from typing import Optional
20
+
21
+ from .. import constants
22
+ from ._token import get_token
23
+
24
+
25
+ class HfFolder:
26
+ path_token = Path(constants.HF_TOKEN_PATH)
27
+ # Private attribute. Will be removed in v0.15
28
+ _old_path_token = Path(constants._OLD_HF_TOKEN_PATH)
29
+
30
+ # TODO: deprecate when adapted in transformers/datasets/gradio
31
+ # @_deprecate_method(version="1.0", message="Use `huggingface_hub.login` instead.")
32
+ @classmethod
33
+ def save_token(cls, token: str) -> None:
34
+ """
35
+ Save token, creating folder as needed.
36
+
37
+ Token is saved in the huggingface home folder. You can configure it by setting
38
+ the `HF_HOME` environment variable.
39
+
40
+ Args:
41
+ token (`str`):
42
+ The token to save to the [`HfFolder`]
43
+ """
44
+ cls.path_token.parent.mkdir(parents=True, exist_ok=True)
45
+ cls.path_token.write_text(token)
46
+
47
+ # TODO: deprecate when adapted in transformers/datasets/gradio
48
+ # @_deprecate_method(version="1.0", message="Use `huggingface_hub.get_token` instead.")
49
+ @classmethod
50
+ def get_token(cls) -> Optional[str]:
51
+ """
52
+ Get token or None if not existent.
53
+
54
+ This method is deprecated in favor of [`huggingface_hub.get_token`] but is kept for backward compatibility.
55
+ Its behavior is the same as [`huggingface_hub.get_token`].
56
+
57
+ Returns:
58
+ `str` or `None`: The token, `None` if it doesn't exist.
59
+ """
60
+ # 0. Check if token exist in old path but not new location
61
+ try:
62
+ cls._copy_to_new_path_and_warn()
63
+ except Exception: # if not possible (e.g. PermissionError), do not raise
64
+ pass
65
+
66
+ return get_token()
67
+
68
+ # TODO: deprecate when adapted in transformers/datasets/gradio
69
+ # @_deprecate_method(version="1.0", message="Use `huggingface_hub.logout` instead.")
70
+ @classmethod
71
+ def delete_token(cls) -> None:
72
+ """
73
+ Deletes the token from storage. Does not fail if token does not exist.
74
+ """
75
+ try:
76
+ cls.path_token.unlink()
77
+ except FileNotFoundError:
78
+ pass
79
+
80
+ try:
81
+ cls._old_path_token.unlink()
82
+ except FileNotFoundError:
83
+ pass
84
+
85
+ @classmethod
86
+ def _copy_to_new_path_and_warn(cls):
87
+ if cls._old_path_token.exists() and not cls.path_token.exists():
88
+ cls.save_token(cls._old_path_token.read_text())
89
+ warnings.warn(
90
+ f"A token has been found in `{cls._old_path_token}`. This is the old"
91
+ " path where tokens were stored. The new location is"
92
+ f" `{cls.path_token}` which is configurable using `HF_HOME` environment"
93
+ " variable. Your token has been copied to this new location. You can"
94
+ " now safely delete the old token file manually or use"
95
+ " `huggingface-cli logout`."
96
+ )
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_http.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 HTTP requests in Huggingface Hub."""
16
+
17
+ import io
18
+ import os
19
+ import threading
20
+ import time
21
+ import uuid
22
+ from functools import lru_cache
23
+ from http import HTTPStatus
24
+ from typing import Callable, Optional, Tuple, Type, Union
25
+
26
+ import requests
27
+ from requests import Response
28
+ from requests.adapters import HTTPAdapter
29
+ from requests.models import PreparedRequest
30
+
31
+ from .. import constants
32
+ from . import logging
33
+ from ._typing import HTTP_METHOD_T
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ # Both headers are used by the Hub to debug failed requests.
39
+ # `X_AMZN_TRACE_ID` is better as it also works to debug on Cloudfront and ALB.
40
+ # If `X_AMZN_TRACE_ID` is set, the Hub will use it as well.
41
+ X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"
42
+ X_REQUEST_ID = "x-request-id"
43
+
44
+
45
+ class OfflineModeIsEnabled(ConnectionError):
46
+ """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""
47
+
48
+
49
+ class UniqueRequestIdAdapter(HTTPAdapter):
50
+ X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"
51
+
52
+ def add_headers(self, request, **kwargs):
53
+ super().add_headers(request, **kwargs)
54
+
55
+ # Add random request ID => easier for server-side debug
56
+ if X_AMZN_TRACE_ID not in request.headers:
57
+ request.headers[X_AMZN_TRACE_ID] = request.headers.get(X_REQUEST_ID) or str(uuid.uuid4())
58
+
59
+ # Add debug log
60
+ has_token = str(request.headers.get("authorization", "")).startswith("Bearer hf_")
61
+ logger.debug(
62
+ f"Request {request.headers[X_AMZN_TRACE_ID]}: {request.method} {request.url} (authenticated: {has_token})"
63
+ )
64
+
65
+ def send(self, request: PreparedRequest, *args, **kwargs) -> Response:
66
+ """Catch any RequestException to append request id to the error message for debugging."""
67
+ try:
68
+ return super().send(request, *args, **kwargs)
69
+ except requests.RequestException as e:
70
+ request_id = request.headers.get(X_AMZN_TRACE_ID)
71
+ if request_id is not None:
72
+ # Taken from https://stackoverflow.com/a/58270258
73
+ e.args = (*e.args, f"(Request ID: {request_id})")
74
+ raise
75
+
76
+
77
+ class OfflineAdapter(HTTPAdapter):
78
+ def send(self, request: PreparedRequest, *args, **kwargs) -> Response:
79
+ raise OfflineModeIsEnabled(
80
+ f"Cannot reach {request.url}: offline mode is enabled. To disable it, please unset the `HF_HUB_OFFLINE` environment variable."
81
+ )
82
+
83
+
84
+ def _default_backend_factory() -> requests.Session:
85
+ session = requests.Session()
86
+ if constants.HF_HUB_OFFLINE:
87
+ session.mount("http://", OfflineAdapter())
88
+ session.mount("https://", OfflineAdapter())
89
+ else:
90
+ session.mount("http://", UniqueRequestIdAdapter())
91
+ session.mount("https://", UniqueRequestIdAdapter())
92
+ return session
93
+
94
+
95
+ BACKEND_FACTORY_T = Callable[[], requests.Session]
96
+ _GLOBAL_BACKEND_FACTORY: BACKEND_FACTORY_T = _default_backend_factory
97
+
98
+
99
+ def configure_http_backend(backend_factory: BACKEND_FACTORY_T = _default_backend_factory) -> None:
100
+ """
101
+ Configure the HTTP backend by providing a `backend_factory`. Any HTTP calls made by `huggingface_hub` will use a
102
+ Session object instantiated by this factory. This can be useful if you are running your scripts in a specific
103
+ environment requiring custom configuration (e.g. custom proxy or certifications).
104
+
105
+ Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe,
106
+ `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory`
107
+ set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between
108
+ calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned.
109
+
110
+ See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`.
111
+
112
+ Example:
113
+ ```py
114
+ import requests
115
+ from huggingface_hub import configure_http_backend, get_session
116
+
117
+ # Create a factory function that returns a Session with configured proxies
118
+ def backend_factory() -> requests.Session:
119
+ session = requests.Session()
120
+ session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
121
+ return session
122
+
123
+ # Set it as the default session factory
124
+ configure_http_backend(backend_factory=backend_factory)
125
+
126
+ # In practice, this is mostly done internally in `huggingface_hub`
127
+ session = get_session()
128
+ ```
129
+ """
130
+ global _GLOBAL_BACKEND_FACTORY
131
+ _GLOBAL_BACKEND_FACTORY = backend_factory
132
+ reset_sessions()
133
+
134
+
135
+ def get_session() -> requests.Session:
136
+ """
137
+ Get a `requests.Session` object, using the session factory from the user.
138
+
139
+ Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe,
140
+ `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory`
141
+ set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between
142
+ calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned.
143
+
144
+ See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`.
145
+
146
+ Example:
147
+ ```py
148
+ import requests
149
+ from huggingface_hub import configure_http_backend, get_session
150
+
151
+ # Create a factory function that returns a Session with configured proxies
152
+ def backend_factory() -> requests.Session:
153
+ session = requests.Session()
154
+ session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
155
+ return session
156
+
157
+ # Set it as the default session factory
158
+ configure_http_backend(backend_factory=backend_factory)
159
+
160
+ # In practice, this is mostly done internally in `huggingface_hub`
161
+ session = get_session()
162
+ ```
163
+ """
164
+ return _get_session_from_cache(process_id=os.getpid(), thread_id=threading.get_ident())
165
+
166
+
167
+ def reset_sessions() -> None:
168
+ """Reset the cache of sessions.
169
+
170
+ Mostly used internally when sessions are reconfigured or an SSLError is raised.
171
+ See [`configure_http_backend`] for more details.
172
+ """
173
+ _get_session_from_cache.cache_clear()
174
+
175
+
176
+ @lru_cache
177
+ def _get_session_from_cache(process_id: int, thread_id: int) -> requests.Session:
178
+ """
179
+ Create a new session per thread using global factory. Using LRU cache (maxsize 128) to avoid memory leaks when
180
+ using thousands of threads. Cache is cleared when `configure_http_backend` is called.
181
+ """
182
+ return _GLOBAL_BACKEND_FACTORY()
183
+
184
+
185
+ def http_backoff(
186
+ method: HTTP_METHOD_T,
187
+ url: str,
188
+ *,
189
+ max_retries: int = 5,
190
+ base_wait_time: float = 1,
191
+ max_wait_time: float = 8,
192
+ retry_on_exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = (
193
+ requests.Timeout,
194
+ requests.ConnectionError,
195
+ ),
196
+ retry_on_status_codes: Union[int, Tuple[int, ...]] = HTTPStatus.SERVICE_UNAVAILABLE,
197
+ **kwargs,
198
+ ) -> Response:
199
+ """Wrapper around requests to retry calls on an endpoint, with exponential backoff.
200
+
201
+ Endpoint call is retried on exceptions (ex: connection timeout, proxy error,...)
202
+ and/or on specific status codes (ex: service unavailable). If the call failed more
203
+ than `max_retries`, the exception is thrown or `raise_for_status` is called on the
204
+ response object.
205
+
206
+ Re-implement mechanisms from the `backoff` library to avoid adding an external
207
+ dependencies to `hugging_face_hub`. See https://github.com/litl/backoff.
208
+
209
+ Args:
210
+ method (`Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]`):
211
+ HTTP method to perform.
212
+ url (`str`):
213
+ The URL of the resource to fetch.
214
+ max_retries (`int`, *optional*, defaults to `5`):
215
+ Maximum number of retries, defaults to 5 (no retries).
216
+ base_wait_time (`float`, *optional*, defaults to `1`):
217
+ Duration (in seconds) to wait before retrying the first time.
218
+ Wait time between retries then grows exponentially, capped by
219
+ `max_wait_time`.
220
+ max_wait_time (`float`, *optional*, defaults to `8`):
221
+ Maximum duration (in seconds) to wait before retrying.
222
+ retry_on_exceptions (`Type[Exception]` or `Tuple[Type[Exception]]`, *optional*):
223
+ Define which exceptions must be caught to retry the request. Can be a single type or a tuple of types.
224
+ By default, retry on `requests.Timeout` and `requests.ConnectionError`.
225
+ retry_on_status_codes (`int` or `Tuple[int]`, *optional*, defaults to `503`):
226
+ Define on which status codes the request must be retried. By default, only
227
+ HTTP 503 Service Unavailable is retried.
228
+ **kwargs (`dict`, *optional*):
229
+ kwargs to pass to `requests.request`.
230
+
231
+ Example:
232
+ ```
233
+ >>> from huggingface_hub.utils import http_backoff
234
+
235
+ # Same usage as "requests.request".
236
+ >>> response = http_backoff("GET", "https://www.google.com")
237
+ >>> response.raise_for_status()
238
+
239
+ # If you expect a Gateway Timeout from time to time
240
+ >>> http_backoff("PUT", upload_url, data=data, retry_on_status_codes=504)
241
+ >>> response.raise_for_status()
242
+ ```
243
+
244
+ <Tip warning={true}>
245
+
246
+ When using `requests` it is possible to stream data by passing an iterator to the
247
+ `data` argument. On http backoff this is a problem as the iterator is not reset
248
+ after a failed call. This issue is mitigated for file objects or any IO streams
249
+ by saving the initial position of the cursor (with `data.tell()`) and resetting the
250
+ cursor between each call (with `data.seek()`). For arbitrary iterators, http backoff
251
+ will fail. If this is a hard constraint for you, please let us know by opening an
252
+ issue on [Github](https://github.com/huggingface/huggingface_hub).
253
+
254
+ </Tip>
255
+ """
256
+ if isinstance(retry_on_exceptions, type): # Tuple from single exception type
257
+ retry_on_exceptions = (retry_on_exceptions,)
258
+
259
+ if isinstance(retry_on_status_codes, int): # Tuple from single status code
260
+ retry_on_status_codes = (retry_on_status_codes,)
261
+
262
+ nb_tries = 0
263
+ sleep_time = base_wait_time
264
+
265
+ # If `data` is used and is a file object (or any IO), it will be consumed on the
266
+ # first HTTP request. We need to save the initial position so that the full content
267
+ # of the file is re-sent on http backoff. See warning tip in docstring.
268
+ io_obj_initial_pos = None
269
+ if "data" in kwargs and isinstance(kwargs["data"], io.IOBase):
270
+ io_obj_initial_pos = kwargs["data"].tell()
271
+
272
+ session = get_session()
273
+ while True:
274
+ nb_tries += 1
275
+ try:
276
+ # If `data` is used and is a file object (or any IO), set back cursor to
277
+ # initial position.
278
+ if io_obj_initial_pos is not None:
279
+ kwargs["data"].seek(io_obj_initial_pos)
280
+
281
+ # Perform request and return if status_code is not in the retry list.
282
+ response = session.request(method=method, url=url, **kwargs)
283
+ if response.status_code not in retry_on_status_codes:
284
+ return response
285
+
286
+ # Wrong status code returned (HTTP 503 for instance)
287
+ logger.warning(f"HTTP Error {response.status_code} thrown while requesting {method} {url}")
288
+ if nb_tries > max_retries:
289
+ response.raise_for_status() # Will raise uncaught exception
290
+ # We return response to avoid infinite loop in the corner case where the
291
+ # user ask for retry on a status code that doesn't raise_for_status.
292
+ return response
293
+
294
+ except retry_on_exceptions as err:
295
+ logger.warning(f"'{err}' thrown while requesting {method} {url}")
296
+
297
+ if isinstance(err, requests.ConnectionError):
298
+ reset_sessions() # In case of SSLError it's best to reset the shared requests.Session objects
299
+
300
+ if nb_tries > max_retries:
301
+ raise err
302
+
303
+ # Sleep for X seconds
304
+ logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].")
305
+ time.sleep(sleep_time)
306
+
307
+ # Update sleep time for next retry
308
+ sleep_time = min(max_wait_time, sleep_time * 2) # Exponential backoff
309
+
310
+
311
+ def fix_hf_endpoint_in_url(url: str, endpoint: Optional[str]) -> str:
312
+ """Replace the default endpoint in a URL by a custom one.
313
+
314
+ This is useful when using a proxy and the Hugging Face Hub returns a URL with the default endpoint.
315
+ """
316
+ endpoint = endpoint or constants.ENDPOINT
317
+ # check if a proxy has been set => if yes, update the returned URL to use the proxy
318
+ if endpoint not in (None, constants._HF_DEFAULT_ENDPOINT, constants._HF_DEFAULT_STAGING_ENDPOINT):
319
+ url = url.replace(constants._HF_DEFAULT_ENDPOINT, endpoint)
320
+ url = url.replace(constants._HF_DEFAULT_STAGING_ENDPOINT, endpoint)
321
+ return url
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 pagination on Huggingface Hub."""
16
+
17
+ from typing import Dict, Iterable, Optional
18
+
19
+ import requests
20
+
21
+ from . import get_session, hf_raise_for_status, logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ def paginate(path: str, params: Dict, headers: Dict) -> Iterable:
28
+ """Fetch a list of models/datasets/spaces and paginate through results.
29
+
30
+ This is using the same "Link" header format as GitHub.
31
+ See:
32
+ - https://requests.readthedocs.io/en/latest/api/#requests.Response.links
33
+ - https://docs.github.com/en/rest/guides/traversing-with-pagination#link-header
34
+ """
35
+ session = get_session()
36
+ r = session.get(path, params=params, headers=headers)
37
+ hf_raise_for_status(r)
38
+ yield from r.json()
39
+
40
+ # Follow pages
41
+ # Next link already contains query params
42
+ next_page = _get_next_page(r)
43
+ while next_page is not None:
44
+ logger.debug(f"Pagination detected. Requesting next page: {next_page}")
45
+ r = session.get(next_page, headers=headers)
46
+ hf_raise_for_status(r)
47
+ yield from r.json()
48
+ next_page = _get_next_page(r)
49
+
50
+
51
+ def _get_next_page(response: requests.Response) -> Optional[str]:
52
+ return response.links.get("next", {}).get("url")
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_paths.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 paths in Huggingface Hub."""
16
+
17
+ from fnmatch import fnmatch
18
+ from pathlib import Path
19
+ from typing import Callable, Generator, Iterable, List, Optional, TypeVar, Union
20
+
21
+
22
+ T = TypeVar("T")
23
+
24
+ IGNORE_GIT_FOLDER_PATTERNS = [".git", ".git/*", "*/.git", "**/.git/**"]
25
+
26
+
27
+ def filter_repo_objects(
28
+ items: Iterable[T],
29
+ *,
30
+ allow_patterns: Optional[Union[List[str], str]] = None,
31
+ ignore_patterns: Optional[Union[List[str], str]] = None,
32
+ key: Optional[Callable[[T], str]] = None,
33
+ ) -> Generator[T, None, None]:
34
+ """Filter repo objects based on an allowlist and a denylist.
35
+
36
+ Input must be a list of paths (`str` or `Path`) or a list of arbitrary objects.
37
+ In the later case, `key` must be provided and specifies a function of one argument
38
+ that is used to extract a path from each element in iterable.
39
+
40
+ Patterns are Unix shell-style wildcards which are NOT regular expressions. See
41
+ https://docs.python.org/3/library/fnmatch.html for more details.
42
+
43
+ Args:
44
+ items (`Iterable`):
45
+ List of items to filter.
46
+ allow_patterns (`str` or `List[str]`, *optional*):
47
+ Patterns constituting the allowlist. If provided, item paths must match at
48
+ least one pattern from the allowlist.
49
+ ignore_patterns (`str` or `List[str]`, *optional*):
50
+ Patterns constituting the denylist. If provided, item paths must not match
51
+ any patterns from the denylist.
52
+ key (`Callable[[T], str]`, *optional*):
53
+ Single-argument function to extract a path from each item. If not provided,
54
+ the `items` must already be `str` or `Path`.
55
+
56
+ Returns:
57
+ Filtered list of objects, as a generator.
58
+
59
+ Raises:
60
+ :class:`ValueError`:
61
+ If `key` is not provided and items are not `str` or `Path`.
62
+
63
+ Example usage with paths:
64
+ ```python
65
+ >>> # Filter only PDFs that are not hidden.
66
+ >>> list(filter_repo_objects(
67
+ ... ["aaa.PDF", "bbb.jpg", ".ccc.pdf", ".ddd.png"],
68
+ ... allow_patterns=["*.pdf"],
69
+ ... ignore_patterns=[".*"],
70
+ ... ))
71
+ ["aaa.pdf"]
72
+ ```
73
+
74
+ Example usage with objects:
75
+ ```python
76
+ >>> list(filter_repo_objects(
77
+ ... [
78
+ ... CommitOperationAdd(path_or_fileobj="/tmp/aaa.pdf", path_in_repo="aaa.pdf")
79
+ ... CommitOperationAdd(path_or_fileobj="/tmp/bbb.jpg", path_in_repo="bbb.jpg")
80
+ ... CommitOperationAdd(path_or_fileobj="/tmp/.ccc.pdf", path_in_repo=".ccc.pdf")
81
+ ... CommitOperationAdd(path_or_fileobj="/tmp/.ddd.png", path_in_repo=".ddd.png")
82
+ ... ],
83
+ ... allow_patterns=["*.pdf"],
84
+ ... ignore_patterns=[".*"],
85
+ ... key=lambda x: x.repo_in_path
86
+ ... ))
87
+ [CommitOperationAdd(path_or_fileobj="/tmp/aaa.pdf", path_in_repo="aaa.pdf")]
88
+ ```
89
+ """
90
+ if isinstance(allow_patterns, str):
91
+ allow_patterns = [allow_patterns]
92
+
93
+ if isinstance(ignore_patterns, str):
94
+ ignore_patterns = [ignore_patterns]
95
+
96
+ if key is None:
97
+
98
+ def _identity(item: T) -> str:
99
+ if isinstance(item, str):
100
+ return item
101
+ if isinstance(item, Path):
102
+ return str(item)
103
+ raise ValueError(f"Please provide `key` argument in `filter_repo_objects`: `{item}` is not a string.")
104
+
105
+ key = _identity # Items must be `str` or `Path`, otherwise raise ValueError
106
+
107
+ for item in items:
108
+ path = key(item)
109
+
110
+ # Skip if there's an allowlist and path doesn't match any
111
+ if allow_patterns is not None and not any(fnmatch(path, r) for r in allow_patterns):
112
+ continue
113
+
114
+ # Skip if there's a denylist and path matches any
115
+ if ignore_patterns is not None and any(fnmatch(path, r) for r in ignore_patterns):
116
+ continue
117
+
118
+ yield item
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_runtime.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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
+ """Check presence of installed packages at runtime."""
16
+
17
+ import importlib.metadata
18
+ import platform
19
+ import sys
20
+ import warnings
21
+ from typing import Any, Dict
22
+
23
+ from .. import __version__, constants
24
+
25
+
26
+ _PY_VERSION: str = sys.version.split()[0].rstrip("+")
27
+
28
+ _package_versions = {}
29
+
30
+ _CANDIDATES = {
31
+ "aiohttp": {"aiohttp"},
32
+ "fastai": {"fastai"},
33
+ "fastcore": {"fastcore"},
34
+ "gradio": {"gradio"},
35
+ "graphviz": {"graphviz"},
36
+ "hf_transfer": {"hf_transfer"},
37
+ "jinja": {"Jinja2"},
38
+ "keras": {"keras"},
39
+ "minijinja": {"minijinja"},
40
+ "numpy": {"numpy"},
41
+ "pillow": {"Pillow"},
42
+ "pydantic": {"pydantic"},
43
+ "pydot": {"pydot"},
44
+ "safetensors": {"safetensors"},
45
+ "tensorboard": {"tensorboardX"},
46
+ "tensorflow": (
47
+ "tensorflow",
48
+ "tensorflow-cpu",
49
+ "tensorflow-gpu",
50
+ "tf-nightly",
51
+ "tf-nightly-cpu",
52
+ "tf-nightly-gpu",
53
+ "intel-tensorflow",
54
+ "intel-tensorflow-avx512",
55
+ "tensorflow-rocm",
56
+ "tensorflow-macos",
57
+ ),
58
+ "torch": {"torch"},
59
+ }
60
+
61
+ # Check once at runtime
62
+ for candidate_name, package_names in _CANDIDATES.items():
63
+ _package_versions[candidate_name] = "N/A"
64
+ for name in package_names:
65
+ try:
66
+ _package_versions[candidate_name] = importlib.metadata.version(name)
67
+ break
68
+ except importlib.metadata.PackageNotFoundError:
69
+ pass
70
+
71
+
72
+ def _get_version(package_name: str) -> str:
73
+ return _package_versions.get(package_name, "N/A")
74
+
75
+
76
+ def is_package_available(package_name: str) -> bool:
77
+ return _get_version(package_name) != "N/A"
78
+
79
+
80
+ # Python
81
+ def get_python_version() -> str:
82
+ return _PY_VERSION
83
+
84
+
85
+ # Huggingface Hub
86
+ def get_hf_hub_version() -> str:
87
+ return __version__
88
+
89
+
90
+ # aiohttp
91
+ def is_aiohttp_available() -> bool:
92
+ return is_package_available("aiohttp")
93
+
94
+
95
+ def get_aiohttp_version() -> str:
96
+ return _get_version("aiohttp")
97
+
98
+
99
+ # FastAI
100
+ def is_fastai_available() -> bool:
101
+ return is_package_available("fastai")
102
+
103
+
104
+ def get_fastai_version() -> str:
105
+ return _get_version("fastai")
106
+
107
+
108
+ # Fastcore
109
+ def is_fastcore_available() -> bool:
110
+ return is_package_available("fastcore")
111
+
112
+
113
+ def get_fastcore_version() -> str:
114
+ return _get_version("fastcore")
115
+
116
+
117
+ # FastAI
118
+ def is_gradio_available() -> bool:
119
+ return is_package_available("gradio")
120
+
121
+
122
+ def get_gradio_version() -> str:
123
+ return _get_version("gradio")
124
+
125
+
126
+ # Graphviz
127
+ def is_graphviz_available() -> bool:
128
+ return is_package_available("graphviz")
129
+
130
+
131
+ def get_graphviz_version() -> str:
132
+ return _get_version("graphviz")
133
+
134
+
135
+ # hf_transfer
136
+ def is_hf_transfer_available() -> bool:
137
+ return is_package_available("hf_transfer")
138
+
139
+
140
+ def get_hf_transfer_version() -> str:
141
+ return _get_version("hf_transfer")
142
+
143
+
144
+ # keras
145
+ def is_keras_available() -> bool:
146
+ return is_package_available("keras")
147
+
148
+
149
+ def get_keras_version() -> str:
150
+ return _get_version("keras")
151
+
152
+
153
+ # Minijinja
154
+ def is_minijinja_available() -> bool:
155
+ return is_package_available("minijinja")
156
+
157
+
158
+ def get_minijinja_version() -> str:
159
+ return _get_version("minijinja")
160
+
161
+
162
+ # Numpy
163
+ def is_numpy_available() -> bool:
164
+ return is_package_available("numpy")
165
+
166
+
167
+ def get_numpy_version() -> str:
168
+ return _get_version("numpy")
169
+
170
+
171
+ # Jinja
172
+ def is_jinja_available() -> bool:
173
+ return is_package_available("jinja")
174
+
175
+
176
+ def get_jinja_version() -> str:
177
+ return _get_version("jinja")
178
+
179
+
180
+ # Pillow
181
+ def is_pillow_available() -> bool:
182
+ return is_package_available("pillow")
183
+
184
+
185
+ def get_pillow_version() -> str:
186
+ return _get_version("pillow")
187
+
188
+
189
+ # Pydantic
190
+ def is_pydantic_available() -> bool:
191
+ if not is_package_available("pydantic"):
192
+ return False
193
+ # For Pydantic, we add an extra check to test whether it is correctly installed or not. If both pydantic 2.x and
194
+ # typing_extensions<=4.5.0 are installed, then pydantic will fail at import time. This should not happen when
195
+ # it is installed with `pip install huggingface_hub[inference]` but it can happen when it is installed manually
196
+ # by the user in an environment that we don't control.
197
+ #
198
+ # Usually we won't need to do this kind of check on optional dependencies. However, pydantic is a special case
199
+ # as it is automatically imported when doing `from huggingface_hub import ...` even if the user doesn't use it.
200
+ #
201
+ # See https://github.com/huggingface/huggingface_hub/pull/1829 for more details.
202
+ try:
203
+ from pydantic import validator # noqa: F401
204
+ except ImportError:
205
+ # Example: "ImportError: cannot import name 'TypeAliasType' from 'typing_extensions'"
206
+ warnings.warn(
207
+ "Pydantic is installed but cannot be imported. Please check your installation. `huggingface_hub` will "
208
+ "default to not using Pydantic. Error message: '{e}'"
209
+ )
210
+ return False
211
+ return True
212
+
213
+
214
+ def get_pydantic_version() -> str:
215
+ return _get_version("pydantic")
216
+
217
+
218
+ # Pydot
219
+ def is_pydot_available() -> bool:
220
+ return is_package_available("pydot")
221
+
222
+
223
+ def get_pydot_version() -> str:
224
+ return _get_version("pydot")
225
+
226
+
227
+ # Tensorboard
228
+ def is_tensorboard_available() -> bool:
229
+ return is_package_available("tensorboard")
230
+
231
+
232
+ def get_tensorboard_version() -> str:
233
+ return _get_version("tensorboard")
234
+
235
+
236
+ # Tensorflow
237
+ def is_tf_available() -> bool:
238
+ return is_package_available("tensorflow")
239
+
240
+
241
+ def get_tf_version() -> str:
242
+ return _get_version("tensorflow")
243
+
244
+
245
+ # Torch
246
+ def is_torch_available() -> bool:
247
+ return is_package_available("torch")
248
+
249
+
250
+ def get_torch_version() -> str:
251
+ return _get_version("torch")
252
+
253
+
254
+ # Safetensors
255
+ def is_safetensors_available() -> bool:
256
+ return is_package_available("safetensors")
257
+
258
+
259
+ # Shell-related helpers
260
+ try:
261
+ # Set to `True` if script is running in a Google Colab notebook.
262
+ # If running in Google Colab, git credential store is set globally which makes the
263
+ # warning disappear. See https://github.com/huggingface/huggingface_hub/issues/1043
264
+ #
265
+ # Taken from https://stackoverflow.com/a/63519730.
266
+ _is_google_colab = "google.colab" in str(get_ipython()) # type: ignore # noqa: F821
267
+ except NameError:
268
+ _is_google_colab = False
269
+
270
+
271
+ def is_notebook() -> bool:
272
+ """Return `True` if code is executed in a notebook (Jupyter, Colab, QTconsole).
273
+
274
+ Taken from https://stackoverflow.com/a/39662359.
275
+ Adapted to make it work with Google colab as well.
276
+ """
277
+ try:
278
+ shell_class = get_ipython().__class__ # type: ignore # noqa: F821
279
+ for parent_class in shell_class.__mro__: # e.g. "is subclass of"
280
+ if parent_class.__name__ == "ZMQInteractiveShell":
281
+ return True # Jupyter notebook, Google colab or qtconsole
282
+ return False
283
+ except NameError:
284
+ return False # Probably standard Python interpreter
285
+
286
+
287
+ def is_google_colab() -> bool:
288
+ """Return `True` if code is executed in a Google colab.
289
+
290
+ Taken from https://stackoverflow.com/a/63519730.
291
+ """
292
+ return _is_google_colab
293
+
294
+
295
+ def dump_environment_info() -> Dict[str, Any]:
296
+ """Dump information about the machine to help debugging issues.
297
+
298
+ Similar helper exist in:
299
+ - `datasets` (https://github.com/huggingface/datasets/blob/main/src/datasets/commands/env.py)
300
+ - `diffusers` (https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/env.py)
301
+ - `transformers` (https://github.com/huggingface/transformers/blob/main/src/transformers/commands/env.py)
302
+ """
303
+ from huggingface_hub import get_token, whoami
304
+ from huggingface_hub.utils import list_credential_helpers
305
+
306
+ token = get_token()
307
+
308
+ # Generic machine info
309
+ info: Dict[str, Any] = {
310
+ "huggingface_hub version": get_hf_hub_version(),
311
+ "Platform": platform.platform(),
312
+ "Python version": get_python_version(),
313
+ }
314
+
315
+ # Interpreter info
316
+ try:
317
+ shell_class = get_ipython().__class__ # type: ignore # noqa: F821
318
+ info["Running in iPython ?"] = "Yes"
319
+ info["iPython shell"] = shell_class.__name__
320
+ except NameError:
321
+ info["Running in iPython ?"] = "No"
322
+ info["Running in notebook ?"] = "Yes" if is_notebook() else "No"
323
+ info["Running in Google Colab ?"] = "Yes" if is_google_colab() else "No"
324
+
325
+ # Login info
326
+ info["Token path ?"] = constants.HF_TOKEN_PATH
327
+ info["Has saved token ?"] = token is not None
328
+ if token is not None:
329
+ try:
330
+ info["Who am I ?"] = whoami()["name"]
331
+ except Exception:
332
+ pass
333
+
334
+ try:
335
+ info["Configured git credential helpers"] = ", ".join(list_credential_helpers())
336
+ except Exception:
337
+ pass
338
+
339
+ # Installed dependencies
340
+ info["FastAI"] = get_fastai_version()
341
+ info["Tensorflow"] = get_tf_version()
342
+ info["Torch"] = get_torch_version()
343
+ info["Jinja2"] = get_jinja_version()
344
+ info["Graphviz"] = get_graphviz_version()
345
+ info["keras"] = get_keras_version()
346
+ info["Pydot"] = get_pydot_version()
347
+ info["Pillow"] = get_pillow_version()
348
+ info["hf_transfer"] = get_hf_transfer_version()
349
+ info["gradio"] = get_gradio_version()
350
+ info["tensorboard"] = get_tensorboard_version()
351
+ info["numpy"] = get_numpy_version()
352
+ info["pydantic"] = get_pydantic_version()
353
+ info["aiohttp"] = get_aiohttp_version()
354
+
355
+ # Environment variables
356
+ info["ENDPOINT"] = constants.ENDPOINT
357
+ info["HF_HUB_CACHE"] = constants.HF_HUB_CACHE
358
+ info["HF_ASSETS_CACHE"] = constants.HF_ASSETS_CACHE
359
+ info["HF_TOKEN_PATH"] = constants.HF_TOKEN_PATH
360
+ info["HF_HUB_OFFLINE"] = constants.HF_HUB_OFFLINE
361
+ info["HF_HUB_DISABLE_TELEMETRY"] = constants.HF_HUB_DISABLE_TELEMETRY
362
+ info["HF_HUB_DISABLE_PROGRESS_BARS"] = constants.HF_HUB_DISABLE_PROGRESS_BARS
363
+ info["HF_HUB_DISABLE_SYMLINKS_WARNING"] = constants.HF_HUB_DISABLE_SYMLINKS_WARNING
364
+ info["HF_HUB_DISABLE_EXPERIMENTAL_WARNING"] = constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING
365
+ info["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = constants.HF_HUB_DISABLE_IMPLICIT_TOKEN
366
+ info["HF_HUB_ENABLE_HF_TRANSFER"] = constants.HF_HUB_ENABLE_HF_TRANSFER
367
+ info["HF_HUB_ETAG_TIMEOUT"] = constants.HF_HUB_ETAG_TIMEOUT
368
+ info["HF_HUB_DOWNLOAD_TIMEOUT"] = constants.HF_HUB_DOWNLOAD_TIMEOUT
369
+
370
+ print("\nCopy-and-paste the text below in your GitHub issue.\n")
371
+ print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]) + "\n")
372
+ return info
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_safetensors.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import operator
3
+ from collections import defaultdict
4
+ from dataclasses import dataclass, field
5
+ from typing import Dict, List, Literal, Optional, Tuple
6
+
7
+
8
+ FILENAME_T = str
9
+ TENSOR_NAME_T = str
10
+ DTYPE_T = Literal["F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL"]
11
+
12
+
13
+ class SafetensorsParsingError(Exception):
14
+ """Raised when failing to parse a safetensors file metadata.
15
+
16
+ This can be the case if the file is not a safetensors file or does not respect the specification.
17
+ """
18
+
19
+
20
+ class NotASafetensorsRepoError(Exception):
21
+ """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a
22
+ `model.safetensors.index.json` file.
23
+ """
24
+
25
+
26
+ @dataclass
27
+ class TensorInfo:
28
+ """Information about a tensor.
29
+
30
+ For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
31
+
32
+ Attributes:
33
+ dtype (`str`):
34
+ The data type of the tensor ("F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL").
35
+ shape (`List[int]`):
36
+ The shape of the tensor.
37
+ data_offsets (`Tuple[int, int]`):
38
+ The offsets of the data in the file as a tuple `[BEGIN, END]`.
39
+ parameter_count (`int`):
40
+ The number of parameters in the tensor.
41
+ """
42
+
43
+ dtype: DTYPE_T
44
+ shape: List[int]
45
+ data_offsets: Tuple[int, int]
46
+ parameter_count: int = field(init=False)
47
+
48
+ def __post_init__(self) -> None:
49
+ # Taken from https://stackoverflow.com/a/13840436
50
+ try:
51
+ self.parameter_count = functools.reduce(operator.mul, self.shape)
52
+ except TypeError:
53
+ self.parameter_count = 1 # scalar value has no shape
54
+
55
+
56
+ @dataclass
57
+ class SafetensorsFileMetadata:
58
+ """Metadata for a Safetensors file hosted on the Hub.
59
+
60
+ This class is returned by [`parse_safetensors_file_metadata`].
61
+
62
+ For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
63
+
64
+ Attributes:
65
+ metadata (`Dict`):
66
+ The metadata contained in the file.
67
+ tensors (`Dict[str, TensorInfo]`):
68
+ A map of all tensors. Keys are tensor names and values are information about the corresponding tensor, as a
69
+ [`TensorInfo`] object.
70
+ parameter_count (`Dict[str, int]`):
71
+ A map of the number of parameters per data type. Keys are data types and values are the number of parameters
72
+ of that data type.
73
+ """
74
+
75
+ metadata: Dict[str, str]
76
+ tensors: Dict[TENSOR_NAME_T, TensorInfo]
77
+ parameter_count: Dict[DTYPE_T, int] = field(init=False)
78
+
79
+ def __post_init__(self) -> None:
80
+ parameter_count: Dict[DTYPE_T, int] = defaultdict(int)
81
+ for tensor in self.tensors.values():
82
+ parameter_count[tensor.dtype] += tensor.parameter_count
83
+ self.parameter_count = dict(parameter_count)
84
+
85
+
86
+ @dataclass
87
+ class SafetensorsRepoMetadata:
88
+ """Metadata for a Safetensors repo.
89
+
90
+ A repo is considered to be a Safetensors repo if it contains either a 'model.safetensors' weight file (non-shared
91
+ model) or a 'model.safetensors.index.json' index file (sharded model) at its root.
92
+
93
+ This class is returned by [`get_safetensors_metadata`].
94
+
95
+ For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
96
+
97
+ Attributes:
98
+ metadata (`Dict`, *optional*):
99
+ The metadata contained in the 'model.safetensors.index.json' file, if it exists. Only populated for sharded
100
+ models.
101
+ sharded (`bool`):
102
+ Whether the repo contains a sharded model or not.
103
+ weight_map (`Dict[str, str]`):
104
+ A map of all weights. Keys are tensor names and values are filenames of the files containing the tensors.
105
+ files_metadata (`Dict[str, SafetensorsFileMetadata]`):
106
+ A map of all files metadata. Keys are filenames and values are the metadata of the corresponding file, as
107
+ a [`SafetensorsFileMetadata`] object.
108
+ parameter_count (`Dict[str, int]`):
109
+ A map of the number of parameters per data type. Keys are data types and values are the number of parameters
110
+ of that data type.
111
+ """
112
+
113
+ metadata: Optional[Dict]
114
+ sharded: bool
115
+ weight_map: Dict[TENSOR_NAME_T, FILENAME_T] # tensor name -> filename
116
+ files_metadata: Dict[FILENAME_T, SafetensorsFileMetadata] # filename -> metadata
117
+ parameter_count: Dict[DTYPE_T, int] = field(init=False)
118
+
119
+ def __post_init__(self) -> None:
120
+ parameter_count: Dict[DTYPE_T, int] = defaultdict(int)
121
+ for file_metadata in self.files_metadata.values():
122
+ for dtype, nb_parameters_ in file_metadata.parameter_count.items():
123
+ parameter_count[dtype] += nb_parameters_
124
+ self.parameter_count = dict(parameter_count)
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_subprocess.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License
16
+ """Contains utilities to easily handle subprocesses in `huggingface_hub`."""
17
+
18
+ import os
19
+ import subprocess
20
+ import sys
21
+ from contextlib import contextmanager
22
+ from io import StringIO
23
+ from pathlib import Path
24
+ from typing import IO, Generator, List, Optional, Tuple, Union
25
+
26
+ from .logging import get_logger
27
+
28
+
29
+ logger = get_logger(__name__)
30
+
31
+
32
+ @contextmanager
33
+ def capture_output() -> Generator[StringIO, None, None]:
34
+ """Capture output that is printed to terminal.
35
+
36
+ Taken from https://stackoverflow.com/a/34738440
37
+
38
+ Example:
39
+ ```py
40
+ >>> with capture_output() as output:
41
+ ... print("hello world")
42
+ >>> assert output.getvalue() == "hello world\n"
43
+ ```
44
+ """
45
+ output = StringIO()
46
+ previous_output = sys.stdout
47
+ sys.stdout = output
48
+ yield output
49
+ sys.stdout = previous_output
50
+
51
+
52
+ def run_subprocess(
53
+ command: Union[str, List[str]],
54
+ folder: Optional[Union[str, Path]] = None,
55
+ check=True,
56
+ **kwargs,
57
+ ) -> subprocess.CompletedProcess:
58
+ """
59
+ Method to run subprocesses. Calling this will capture the `stderr` and `stdout`,
60
+ please call `subprocess.run` manually in case you would like for them not to
61
+ be captured.
62
+
63
+ Args:
64
+ command (`str` or `List[str]`):
65
+ The command to execute as a string or list of strings.
66
+ folder (`str`, *optional*):
67
+ The folder in which to run the command. Defaults to current working
68
+ directory (from `os.getcwd()`).
69
+ check (`bool`, *optional*, defaults to `True`):
70
+ Setting `check` to `True` will raise a `subprocess.CalledProcessError`
71
+ when the subprocess has a non-zero exit code.
72
+ kwargs (`Dict[str]`):
73
+ Keyword arguments to be passed to the `subprocess.run` underlying command.
74
+
75
+ Returns:
76
+ `subprocess.CompletedProcess`: The completed process.
77
+ """
78
+ if isinstance(command, str):
79
+ command = command.split()
80
+
81
+ if isinstance(folder, Path):
82
+ folder = str(folder)
83
+
84
+ return subprocess.run(
85
+ command,
86
+ stderr=subprocess.PIPE,
87
+ stdout=subprocess.PIPE,
88
+ check=check,
89
+ encoding="utf-8",
90
+ errors="replace", # if not utf-8, replace char by �
91
+ cwd=folder or os.getcwd(),
92
+ **kwargs,
93
+ )
94
+
95
+
96
+ @contextmanager
97
+ def run_interactive_subprocess(
98
+ command: Union[str, List[str]],
99
+ folder: Optional[Union[str, Path]] = None,
100
+ **kwargs,
101
+ ) -> Generator[Tuple[IO[str], IO[str]], None, None]:
102
+ """Run a subprocess in an interactive mode in a context manager.
103
+
104
+ Args:
105
+ command (`str` or `List[str]`):
106
+ The command to execute as a string or list of strings.
107
+ folder (`str`, *optional*):
108
+ The folder in which to run the command. Defaults to current working
109
+ directory (from `os.getcwd()`).
110
+ kwargs (`Dict[str]`):
111
+ Keyword arguments to be passed to the `subprocess.run` underlying command.
112
+
113
+ Returns:
114
+ `Tuple[IO[str], IO[str]]`: A tuple with `stdin` and `stdout` to interact
115
+ with the process (input and output are utf-8 encoded).
116
+
117
+ Example:
118
+ ```python
119
+ with _interactive_subprocess("git credential-store get") as (stdin, stdout):
120
+ # Write to stdin
121
+ stdin.write("url=hf.co\nusername=obama\n".encode("utf-8"))
122
+ stdin.flush()
123
+
124
+ # Read from stdout
125
+ output = stdout.read().decode("utf-8")
126
+ ```
127
+ """
128
+ if isinstance(command, str):
129
+ command = command.split()
130
+
131
+ with subprocess.Popen(
132
+ command,
133
+ stdin=subprocess.PIPE,
134
+ stdout=subprocess.PIPE,
135
+ stderr=subprocess.STDOUT,
136
+ encoding="utf-8",
137
+ errors="replace", # if not utf-8, replace char by �
138
+ cwd=folder or os.getcwd(),
139
+ **kwargs,
140
+ ) as process:
141
+ assert process.stdin is not None, "subprocess is opened as subprocess.PIPE"
142
+ assert process.stdout is not None, "subprocess is opened as subprocess.PIPE"
143
+ yield process.stdin, process.stdout
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from queue import Queue
2
+ from threading import Lock, Thread
3
+ from typing import Dict, Optional, Union
4
+ from urllib.parse import quote
5
+
6
+ from .. import constants, logging
7
+ from . import build_hf_headers, get_session, hf_raise_for_status
8
+
9
+
10
+ logger = logging.get_logger(__name__)
11
+
12
+ # Telemetry is sent by a separate thread to avoid blocking the main thread.
13
+ # A daemon thread is started once and consume tasks from the _TELEMETRY_QUEUE.
14
+ # If the thread stops for some reason -shouldn't happen-, we restart a new one.
15
+ _TELEMETRY_THREAD: Optional[Thread] = None
16
+ _TELEMETRY_THREAD_LOCK = Lock() # Lock to avoid starting multiple threads in parallel
17
+ _TELEMETRY_QUEUE: Queue = Queue()
18
+
19
+
20
+ def send_telemetry(
21
+ topic: str,
22
+ *,
23
+ library_name: Optional[str] = None,
24
+ library_version: Optional[str] = None,
25
+ user_agent: Union[Dict, str, None] = None,
26
+ ) -> None:
27
+ """
28
+ Sends telemetry that helps tracking usage of different HF libraries.
29
+
30
+ This usage data helps us debug issues and prioritize new features. However, we understand that not everyone wants
31
+ to share additional information, and we respect your privacy. You can disable telemetry collection by setting the
32
+ `HF_HUB_DISABLE_TELEMETRY=1` as environment variable. Telemetry is also disabled in offline mode (i.e. when setting
33
+ `HF_HUB_OFFLINE=1`).
34
+
35
+ Telemetry collection is run in a separate thread to minimize impact for the user.
36
+
37
+ Args:
38
+ topic (`str`):
39
+ Name of the topic that is monitored. The topic is directly used to build the URL. If you want to monitor
40
+ subtopics, just use "/" separation. Examples: "gradio", "transformers/examples",...
41
+ library_name (`str`, *optional*):
42
+ The name of the library that is making the HTTP request. Will be added to the user-agent header.
43
+ library_version (`str`, *optional*):
44
+ The version of the library that is making the HTTP request. Will be added to the user-agent header.
45
+ user_agent (`str`, `dict`, *optional*):
46
+ The user agent info in the form of a dictionary or a single string. It will be completed with information about the installed packages.
47
+
48
+ Example:
49
+ ```py
50
+ >>> from huggingface_hub.utils import send_telemetry
51
+
52
+ # Send telemetry without library information
53
+ >>> send_telemetry("ping")
54
+
55
+ # Send telemetry to subtopic with library information
56
+ >>> send_telemetry("gradio/local_link", library_name="gradio", library_version="3.22.1")
57
+
58
+ # Send telemetry with additional data
59
+ >>> send_telemetry(
60
+ ... topic="examples",
61
+ ... library_name="transformers",
62
+ ... library_version="4.26.0",
63
+ ... user_agent={"pipeline": "text_classification", "framework": "flax"},
64
+ ... )
65
+ ```
66
+ """
67
+ if constants.HF_HUB_OFFLINE or constants.HF_HUB_DISABLE_TELEMETRY:
68
+ return
69
+
70
+ _start_telemetry_thread() # starts thread only if doesn't exist yet
71
+ _TELEMETRY_QUEUE.put(
72
+ {"topic": topic, "library_name": library_name, "library_version": library_version, "user_agent": user_agent}
73
+ )
74
+
75
+
76
+ def _start_telemetry_thread():
77
+ """Start a daemon thread to consume tasks from the telemetry queue.
78
+
79
+ If the thread is interrupted, start a new one.
80
+ """
81
+ with _TELEMETRY_THREAD_LOCK: # avoid to start multiple threads if called concurrently
82
+ global _TELEMETRY_THREAD
83
+ if _TELEMETRY_THREAD is None or not _TELEMETRY_THREAD.is_alive():
84
+ _TELEMETRY_THREAD = Thread(target=_telemetry_worker, daemon=True)
85
+ _TELEMETRY_THREAD.start()
86
+
87
+
88
+ def _telemetry_worker():
89
+ """Wait for a task and consume it."""
90
+ while True:
91
+ kwargs = _TELEMETRY_QUEUE.get()
92
+ _send_telemetry_in_thread(**kwargs)
93
+ _TELEMETRY_QUEUE.task_done()
94
+
95
+
96
+ def _send_telemetry_in_thread(
97
+ topic: str,
98
+ *,
99
+ library_name: Optional[str] = None,
100
+ library_version: Optional[str] = None,
101
+ user_agent: Union[Dict, str, None] = None,
102
+ ) -> None:
103
+ """Contains the actual data sending data to the Hub."""
104
+ path = "/".join(quote(part) for part in topic.split("/") if len(part) > 0)
105
+ try:
106
+ r = get_session().head(
107
+ f"{constants.ENDPOINT}/api/telemetry/{path}",
108
+ headers=build_hf_headers(
109
+ token=False, # no need to send a token for telemetry
110
+ library_name=library_name,
111
+ library_version=library_version,
112
+ user_agent=user_agent,
113
+ ),
114
+ )
115
+ hf_raise_for_status(r)
116
+ except Exception as e:
117
+ # We don't want to error in case of connection errors of any kind.
118
+ logger.debug(f"Error while sending telemetry: {e}")
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_token.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains an helper to get the token from machine (env variable, secret or config file)."""
15
+
16
+ import os
17
+ import warnings
18
+ from pathlib import Path
19
+ from threading import Lock
20
+ from typing import Optional
21
+
22
+ from .. import constants
23
+ from ._runtime import is_google_colab
24
+
25
+
26
+ _IS_GOOGLE_COLAB_CHECKED = False
27
+ _GOOGLE_COLAB_SECRET_LOCK = Lock()
28
+ _GOOGLE_COLAB_SECRET: Optional[str] = None
29
+
30
+
31
+ def get_token() -> Optional[str]:
32
+ """
33
+ Get token if user is logged in.
34
+
35
+ Note: in most cases, you should use [`huggingface_hub.utils.build_hf_headers`] instead. This method is only useful
36
+ if you want to retrieve the token for other purposes than sending an HTTP request.
37
+
38
+ Token is retrieved in priority from the `HF_TOKEN` environment variable. Otherwise, we read the token file located
39
+ in the Hugging Face home folder. Returns None if user is not logged in. To log in, use [`login`] or
40
+ `huggingface-cli login`.
41
+
42
+ Returns:
43
+ `str` or `None`: The token, `None` if it doesn't exist.
44
+ """
45
+ return _get_token_from_google_colab() or _get_token_from_environment() or _get_token_from_file()
46
+
47
+
48
+ def _get_token_from_google_colab() -> Optional[str]:
49
+ """Get token from Google Colab secrets vault using `google.colab.userdata.get(...)`.
50
+
51
+ Token is read from the vault only once per session and then stored in a global variable to avoid re-requesting
52
+ access to the vault.
53
+ """
54
+ if not is_google_colab():
55
+ return None
56
+
57
+ # `google.colab.userdata` is not thread-safe
58
+ # This can lead to a deadlock if multiple threads try to access it at the same time
59
+ # (typically when using `snapshot_download`)
60
+ # => use a lock
61
+ # See https://github.com/huggingface/huggingface_hub/issues/1952 for more details.
62
+ with _GOOGLE_COLAB_SECRET_LOCK:
63
+ global _GOOGLE_COLAB_SECRET
64
+ global _IS_GOOGLE_COLAB_CHECKED
65
+
66
+ if _IS_GOOGLE_COLAB_CHECKED: # request access only once
67
+ return _GOOGLE_COLAB_SECRET
68
+
69
+ try:
70
+ from google.colab import userdata
71
+ from google.colab.errors import Error as ColabError
72
+ except ImportError:
73
+ return None
74
+
75
+ try:
76
+ token = userdata.get("HF_TOKEN")
77
+ _GOOGLE_COLAB_SECRET = _clean_token(token)
78
+ except userdata.NotebookAccessError:
79
+ # Means the user has a secret call `HF_TOKEN` and got a popup "please grand access to HF_TOKEN" and refused it
80
+ # => warn user but ignore error => do not re-request access to user
81
+ warnings.warn(
82
+ "\nAccess to the secret `HF_TOKEN` has not been granted on this notebook."
83
+ "\nYou will not be requested again."
84
+ "\nPlease restart the session if you want to be prompted again."
85
+ )
86
+ _GOOGLE_COLAB_SECRET = None
87
+ except userdata.SecretNotFoundError:
88
+ # Means the user did not define a `HF_TOKEN` secret => warn
89
+ warnings.warn(
90
+ "\nThe secret `HF_TOKEN` does not exist in your Colab secrets."
91
+ "\nTo authenticate with the Hugging Face Hub, create a token in your settings tab "
92
+ "(https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session."
93
+ "\nYou will be able to reuse this secret in all of your notebooks."
94
+ "\nPlease note that authentication is recommended but still optional to access public models or datasets."
95
+ )
96
+ _GOOGLE_COLAB_SECRET = None
97
+ except ColabError as e:
98
+ # Something happen but we don't know what => recommend to open a GitHub issue
99
+ warnings.warn(
100
+ f"\nError while fetching `HF_TOKEN` secret value from your vault: '{str(e)}'."
101
+ "\nYou are not authenticated with the Hugging Face Hub in this notebook."
102
+ "\nIf the error persists, please let us know by opening an issue on GitHub "
103
+ "(https://github.com/huggingface/huggingface_hub/issues/new)."
104
+ )
105
+ _GOOGLE_COLAB_SECRET = None
106
+
107
+ _IS_GOOGLE_COLAB_CHECKED = True
108
+ return _GOOGLE_COLAB_SECRET
109
+
110
+
111
+ def _get_token_from_environment() -> Optional[str]:
112
+ # `HF_TOKEN` has priority (keep `HUGGING_FACE_HUB_TOKEN` for backward compatibility)
113
+ return _clean_token(os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN"))
114
+
115
+
116
+ def _get_token_from_file() -> Optional[str]:
117
+ try:
118
+ return _clean_token(Path(constants.HF_TOKEN_PATH).read_text())
119
+ except FileNotFoundError:
120
+ return None
121
+
122
+
123
+ def _clean_token(token: Optional[str]) -> Optional[str]:
124
+ """Clean token by removing trailing and leading spaces and newlines.
125
+
126
+ If token is an empty string, return None.
127
+ """
128
+ if token is None:
129
+ return None
130
+ return token.replace("\r", "").replace("\n", "").strip() or None
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_typing.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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
+ """Handle typing imports based on system compatibility."""
16
+
17
+ from typing import Any, Callable, Literal, TypeVar
18
+
19
+
20
+ HTTP_METHOD_T = Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]
21
+
22
+ # type hint meaning "function signature not changed by decorator"
23
+ CallableT = TypeVar("CallableT", bound=Callable)
24
+
25
+ _JSON_SERIALIZABLE_TYPES = (int, float, str, bool, type(None))
26
+
27
+
28
+ def is_jsonable(obj: Any) -> bool:
29
+ """Check if an object is JSON serializable.
30
+
31
+ This is a weak check, as it does not check for the actual JSON serialization, but only for the types of the object.
32
+ It works correctly for basic use cases but do not guarantee an exhaustive check.
33
+
34
+ Object is considered to be recursively json serializable if:
35
+ - it is an instance of int, float, str, bool, or NoneType
36
+ - it is a list or tuple and all its items are json serializable
37
+ - it is a dict and all its keys are strings and all its values are json serializable
38
+ """
39
+ try:
40
+ if isinstance(obj, _JSON_SERIALIZABLE_TYPES):
41
+ return True
42
+ if isinstance(obj, (list, tuple)):
43
+ return all(is_jsonable(item) for item in obj)
44
+ if isinstance(obj, dict):
45
+ return all(isinstance(key, str) and is_jsonable(value) for key, value in obj.items())
46
+ if hasattr(obj, "__json__"):
47
+ return True
48
+ return False
49
+ except RecursionError:
50
+ return False
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-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 validate argument values in `huggingface_hub`."""
16
+
17
+ import inspect
18
+ import re
19
+ import warnings
20
+ from functools import wraps
21
+ from itertools import chain
22
+ from typing import Any, Dict
23
+
24
+ from ._typing import CallableT
25
+
26
+
27
+ REPO_ID_REGEX = re.compile(
28
+ r"""
29
+ ^
30
+ (\b[\w\-.]+\b/)? # optional namespace (username or organization)
31
+ \b # starts with a word boundary
32
+ [\w\-.]{1,96} # repo_name: alphanumeric + . _ -
33
+ \b # ends with a word boundary
34
+ $
35
+ """,
36
+ flags=re.VERBOSE,
37
+ )
38
+
39
+
40
+ class HFValidationError(ValueError):
41
+ """Generic exception thrown by `huggingface_hub` validators.
42
+
43
+ Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).
44
+ """
45
+
46
+
47
+ def validate_hf_hub_args(fn: CallableT) -> CallableT:
48
+ """Validate values received as argument for any public method of `huggingface_hub`.
49
+
50
+ The goal of this decorator is to harmonize validation of arguments reused
51
+ everywhere. By default, all defined validators are tested.
52
+
53
+ Validators:
54
+ - [`~utils.validate_repo_id`]: `repo_id` must be `"repo_name"`
55
+ or `"namespace/repo_name"`. Namespace is a username or an organization.
56
+ - [`~utils.smoothly_deprecate_use_auth_token`]: Use `token` instead of
57
+ `use_auth_token` (only if `use_auth_token` is not expected by the decorated
58
+ function - in practice, always the case in `huggingface_hub`).
59
+
60
+ Example:
61
+ ```py
62
+ >>> from huggingface_hub.utils import validate_hf_hub_args
63
+
64
+ >>> @validate_hf_hub_args
65
+ ... def my_cool_method(repo_id: str):
66
+ ... print(repo_id)
67
+
68
+ >>> my_cool_method(repo_id="valid_repo_id")
69
+ valid_repo_id
70
+
71
+ >>> my_cool_method("other..repo..id")
72
+ huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.
73
+
74
+ >>> my_cool_method(repo_id="other..repo..id")
75
+ huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.
76
+
77
+ >>> @validate_hf_hub_args
78
+ ... def my_cool_auth_method(token: str):
79
+ ... print(token)
80
+
81
+ >>> my_cool_auth_method(token="a token")
82
+ "a token"
83
+
84
+ >>> my_cool_auth_method(use_auth_token="a use_auth_token")
85
+ "a use_auth_token"
86
+
87
+ >>> my_cool_auth_method(token="a token", use_auth_token="a use_auth_token")
88
+ UserWarning: Both `token` and `use_auth_token` are passed (...)
89
+ "a token"
90
+ ```
91
+
92
+ Raises:
93
+ [`~utils.HFValidationError`]:
94
+ If an input is not valid.
95
+ """
96
+ # TODO: add an argument to opt-out validation for specific argument?
97
+ signature = inspect.signature(fn)
98
+
99
+ # Should the validator switch `use_auth_token` values to `token`? In practice, always
100
+ # True in `huggingface_hub`. Might not be the case in a downstream library.
101
+ check_use_auth_token = "use_auth_token" not in signature.parameters and "token" in signature.parameters
102
+
103
+ @wraps(fn)
104
+ def _inner_fn(*args, **kwargs):
105
+ has_token = False
106
+ for arg_name, arg_value in chain(
107
+ zip(signature.parameters, args), # Args values
108
+ kwargs.items(), # Kwargs values
109
+ ):
110
+ if arg_name in ["repo_id", "from_id", "to_id"]:
111
+ validate_repo_id(arg_value)
112
+
113
+ elif arg_name == "token" and arg_value is not None:
114
+ has_token = True
115
+
116
+ if check_use_auth_token:
117
+ kwargs = smoothly_deprecate_use_auth_token(fn_name=fn.__name__, has_token=has_token, kwargs=kwargs)
118
+
119
+ return fn(*args, **kwargs)
120
+
121
+ return _inner_fn # type: ignore
122
+
123
+
124
+ def validate_repo_id(repo_id: str) -> None:
125
+ """Validate `repo_id` is valid.
126
+
127
+ This is not meant to replace the proper validation made on the Hub but rather to
128
+ avoid local inconsistencies whenever possible (example: passing `repo_type` in the
129
+ `repo_id` is forbidden).
130
+
131
+ Rules:
132
+ - Between 1 and 96 characters.
133
+ - Either "repo_name" or "namespace/repo_name"
134
+ - [a-zA-Z0-9] or "-", "_", "."
135
+ - "--" and ".." are forbidden
136
+
137
+ Valid: `"foo"`, `"foo/bar"`, `"123"`, `"Foo-BAR_foo.bar123"`
138
+
139
+ Not valid: `"datasets/foo/bar"`, `".repo_id"`, `"foo--bar"`, `"foo.git"`
140
+
141
+ Example:
142
+ ```py
143
+ >>> from huggingface_hub.utils import validate_repo_id
144
+ >>> validate_repo_id(repo_id="valid_repo_id")
145
+ >>> validate_repo_id(repo_id="other..repo..id")
146
+ huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.
147
+ ```
148
+
149
+ Discussed in https://github.com/huggingface/huggingface_hub/issues/1008.
150
+ In moon-landing (internal repository):
151
+ - https://github.com/huggingface/moon-landing/blob/main/server/lib/Names.ts#L27
152
+ - https://github.com/huggingface/moon-landing/blob/main/server/views/components/NewRepoForm/NewRepoForm.svelte#L138
153
+ """
154
+ if not isinstance(repo_id, str):
155
+ # Typically, a Path is not a repo_id
156
+ raise HFValidationError(f"Repo id must be a string, not {type(repo_id)}: '{repo_id}'.")
157
+
158
+ if repo_id.count("/") > 1:
159
+ raise HFValidationError(
160
+ "Repo id must be in the form 'repo_name' or 'namespace/repo_name':"
161
+ f" '{repo_id}'. Use `repo_type` argument if needed."
162
+ )
163
+
164
+ if not REPO_ID_REGEX.match(repo_id):
165
+ raise HFValidationError(
166
+ "Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are"
167
+ " forbidden, '-' and '.' cannot start or end the name, max length is 96:"
168
+ f" '{repo_id}'."
169
+ )
170
+
171
+ if "--" in repo_id or ".." in repo_id:
172
+ raise HFValidationError(f"Cannot have -- or .. in repo_id: '{repo_id}'.")
173
+
174
+ if repo_id.endswith(".git"):
175
+ raise HFValidationError(f"Repo_id cannot end by '.git': '{repo_id}'.")
176
+
177
+
178
+ def smoothly_deprecate_use_auth_token(fn_name: str, has_token: bool, kwargs: Dict[str, Any]) -> Dict[str, Any]:
179
+ """Smoothly deprecate `use_auth_token` in the `huggingface_hub` codebase.
180
+
181
+ The long-term goal is to remove any mention of `use_auth_token` in the codebase in
182
+ favor of a unique and less verbose `token` argument. This will be done a few steps:
183
+
184
+ 0. Step 0: methods that require a read-access to the Hub use the `use_auth_token`
185
+ argument (`str`, `bool` or `None`). Methods requiring write-access have a `token`
186
+ argument (`str`, `None`). This implicit rule exists to be able to not send the
187
+ token when not necessary (`use_auth_token=False`) even if logged in.
188
+
189
+ 1. Step 1: we want to harmonize everything and use `token` everywhere (supporting
190
+ `token=False` for read-only methods). In order not to break existing code, if
191
+ `use_auth_token` is passed to a function, the `use_auth_token` value is passed
192
+ as `token` instead, without any warning.
193
+ a. Corner case: if both `use_auth_token` and `token` values are passed, a warning
194
+ is thrown and the `use_auth_token` value is ignored.
195
+
196
+ 2. Step 2: Once it is release, we should push downstream libraries to switch from
197
+ `use_auth_token` to `token` as much as possible, but without throwing a warning
198
+ (e.g. manually create issues on the corresponding repos).
199
+
200
+ 3. Step 3: After a transitional period (6 months e.g. until April 2023?), we update
201
+ `huggingface_hub` to throw a warning on `use_auth_token`. Hopefully, very few
202
+ users will be impacted as it would have already been fixed.
203
+ In addition, unit tests in `huggingface_hub` must be adapted to expect warnings
204
+ to be thrown (but still use `use_auth_token` as before).
205
+
206
+ 4. Step 4: After a normal deprecation cycle (3 releases ?), remove this validator.
207
+ `use_auth_token` will definitely not be supported.
208
+ In addition, we update unit tests in `huggingface_hub` to use `token` everywhere.
209
+
210
+ This has been discussed in:
211
+ - https://github.com/huggingface/huggingface_hub/issues/1094.
212
+ - https://github.com/huggingface/huggingface_hub/pull/928
213
+ - (related) https://github.com/huggingface/huggingface_hub/pull/1064
214
+ """
215
+ new_kwargs = kwargs.copy() # do not mutate input !
216
+
217
+ use_auth_token = new_kwargs.pop("use_auth_token", None) # remove from kwargs
218
+ if use_auth_token is not None:
219
+ if has_token:
220
+ warnings.warn(
221
+ "Both `token` and `use_auth_token` are passed to"
222
+ f" `{fn_name}` with non-None values. `token` is now the"
223
+ " preferred argument to pass a User Access Token."
224
+ " `use_auth_token` value will be ignored."
225
+ )
226
+ else:
227
+ # `token` argument is not passed and a non-None value is passed in
228
+ # `use_auth_token` => use `use_auth_token` value as `token` kwarg.
229
+ new_kwargs["token"] = use_auth_token
230
+
231
+ return new_kwargs
env-llmeval/lib/python3.10/site-packages/huggingface_hub/utils/endpoint_helpers.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+ """
13
+ Helpful utility functions and classes in relation to exploring API endpoints
14
+ with the aim for a user-friendly interface.
15
+ """
16
+
17
+ import math
18
+ import re
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import TYPE_CHECKING, List, Optional, Union
22
+
23
+ from ..repocard_data import ModelCardData
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from ..hf_api import ModelInfo
28
+
29
+
30
+ def _is_emission_within_treshold(model_info: "ModelInfo", minimum_threshold: float, maximum_threshold: float) -> bool:
31
+ """Checks if a model's emission is within a given threshold.
32
+
33
+ Args:
34
+ model_info (`ModelInfo`):
35
+ A model info object containing the model's emission information.
36
+ minimum_threshold (`float`):
37
+ A minimum carbon threshold to filter by, such as 1.
38
+ maximum_threshold (`float`):
39
+ A maximum carbon threshold to filter by, such as 10.
40
+
41
+ Returns:
42
+ `bool`: Whether the model's emission is within the given threshold.
43
+ """
44
+ if minimum_threshold is None and maximum_threshold is None:
45
+ raise ValueError("Both `minimum_threshold` and `maximum_threshold` cannot both be `None`")
46
+ if minimum_threshold is None:
47
+ minimum_threshold = -1
48
+ if maximum_threshold is None:
49
+ maximum_threshold = math.inf
50
+
51
+ card_data = getattr(model_info, "card_data", None)
52
+ if card_data is None or not isinstance(card_data, (dict, ModelCardData)):
53
+ return False
54
+
55
+ # Get CO2 emission metadata
56
+ emission = card_data.get("co2_eq_emissions", None)
57
+ if isinstance(emission, dict):
58
+ emission = emission["emissions"]
59
+ if not emission:
60
+ return False
61
+
62
+ # Filter out if value is missing or out of range
63
+ matched = re.search(r"\d+\.\d+|\d+", str(emission))
64
+ if matched is None:
65
+ return False
66
+
67
+ emission_value = float(matched.group(0))
68
+ return minimum_threshold <= emission_value <= maximum_threshold
69
+
70
+
71
+ @dataclass
72
+ class DatasetFilter:
73
+ """
74
+ A class that converts human-readable dataset search parameters into ones
75
+ compatible with the REST API. For all parameters capitalization does not
76
+ matter.
77
+
78
+ <Tip warning={true}>
79
+
80
+ The `DatasetFilter` class is deprecated and will be removed in huggingface_hub>=0.24. Please pass the filter parameters as keyword arguments directly to [`list_datasets`].
81
+
82
+ </Tip>
83
+
84
+ Args:
85
+ author (`str`, *optional*):
86
+ A string that can be used to identify datasets on
87
+ the Hub by the original uploader (author or organization), such as
88
+ `facebook` or `huggingface`.
89
+ benchmark (`str` or `List`, *optional*):
90
+ A string or list of strings that can be used to identify datasets on
91
+ the Hub by their official benchmark.
92
+ dataset_name (`str`, *optional*):
93
+ A string or list of strings that can be used to identify datasets on
94
+ the Hub by its name, such as `SQAC` or `wikineural`
95
+ language_creators (`str` or `List`, *optional*):
96
+ A string or list of strings that can be used to identify datasets on
97
+ the Hub with how the data was curated, such as `crowdsourced` or
98
+ `machine_generated`.
99
+ language (`str` or `List`, *optional*):
100
+ A string or list of strings representing a two-character language to
101
+ filter datasets by on the Hub.
102
+ multilinguality (`str` or `List`, *optional*):
103
+ A string or list of strings representing a filter for datasets that
104
+ contain multiple languages.
105
+ size_categories (`str` or `List`, *optional*):
106
+ A string or list of strings that can be used to identify datasets on
107
+ the Hub by the size of the dataset such as `100K<n<1M` or
108
+ `1M<n<10M`.
109
+ task_categories (`str` or `List`, *optional*):
110
+ A string or list of strings that can be used to identify datasets on
111
+ the Hub by the designed task, such as `audio_classification` or
112
+ `named_entity_recognition`.
113
+ task_ids (`str` or `List`, *optional*):
114
+ A string or list of strings that can be used to identify datasets on
115
+ the Hub by the specific task such as `speech_emotion_recognition` or
116
+ `paraphrase`.
117
+
118
+ Examples:
119
+
120
+ ```py
121
+ >>> from huggingface_hub import DatasetFilter
122
+
123
+ >>> # Using author
124
+ >>> new_filter = DatasetFilter(author="facebook")
125
+
126
+ >>> # Using benchmark
127
+ >>> new_filter = DatasetFilter(benchmark="raft")
128
+
129
+ >>> # Using dataset_name
130
+ >>> new_filter = DatasetFilter(dataset_name="wikineural")
131
+
132
+ >>> # Using language_creator
133
+ >>> new_filter = DatasetFilter(language_creator="crowdsourced")
134
+
135
+ >>> # Using language
136
+ >>> new_filter = DatasetFilter(language="en")
137
+
138
+ >>> # Using multilinguality
139
+ >>> new_filter = DatasetFilter(multilinguality="multilingual")
140
+
141
+ >>> # Using size_categories
142
+ >>> new_filter = DatasetFilter(size_categories="100K<n<1M")
143
+
144
+ >>> # Using task_categories
145
+ >>> new_filter = DatasetFilter(task_categories="audio_classification")
146
+
147
+ >>> # Using task_ids
148
+ >>> new_filter = DatasetFilter(task_ids="paraphrase")
149
+ ```
150
+ """
151
+
152
+ author: Optional[str] = None
153
+ benchmark: Optional[Union[str, List[str]]] = None
154
+ dataset_name: Optional[str] = None
155
+ language_creators: Optional[Union[str, List[str]]] = None
156
+ language: Optional[Union[str, List[str]]] = None
157
+ multilinguality: Optional[Union[str, List[str]]] = None
158
+ size_categories: Optional[Union[str, List[str]]] = None
159
+ task_categories: Optional[Union[str, List[str]]] = None
160
+ task_ids: Optional[Union[str, List[str]]] = None
161
+
162
+ def __post_init__(self):
163
+ warnings.warn(
164
+ "'DatasetFilter' is deprecated and will be removed in huggingface_hub>=0.24. Please pass the filter parameters as keyword arguments directly to the `list_datasets` method.",
165
+ category=FutureWarning,
166
+ )
167
+
168
+
169
+ @dataclass
170
+ class ModelFilter:
171
+ """
172
+ A class that converts human-readable model search parameters into ones
173
+ compatible with the REST API. For all parameters capitalization does not
174
+ matter.
175
+
176
+ <Tip warning={true}>
177
+
178
+ The `ModelFilter` class is deprecated and will be removed in huggingface_hub>=0.24. Please pass the filter parameters as keyword arguments directly to [`list_models`].
179
+
180
+ </Tip>
181
+
182
+ Args:
183
+ author (`str`, *optional*):
184
+ A string that can be used to identify models on the Hub by the
185
+ original uploader (author or organization), such as `facebook` or
186
+ `huggingface`.
187
+ library (`str` or `List`, *optional*):
188
+ A string or list of strings of foundational libraries models were
189
+ originally trained from, such as pytorch, tensorflow, or allennlp.
190
+ language (`str` or `List`, *optional*):
191
+ A string or list of strings of languages, both by name and country
192
+ code, such as "en" or "English"
193
+ model_name (`str`, *optional*):
194
+ A string that contain complete or partial names for models on the
195
+ Hub, such as "bert" or "bert-base-cased"
196
+ task (`str` or `List`, *optional*):
197
+ A string or list of strings of tasks models were designed for, such
198
+ as: "fill-mask" or "automatic-speech-recognition"
199
+ tags (`str` or `List`, *optional*):
200
+ A string tag or a list of tags to filter models on the Hub by, such
201
+ as `text-generation` or `spacy`.
202
+ trained_dataset (`str` or `List`, *optional*):
203
+ A string tag or a list of string tags of the trained dataset for a
204
+ model on the Hub.
205
+
206
+ Examples:
207
+
208
+ ```python
209
+ >>> from huggingface_hub import ModelFilter
210
+
211
+ >>> # For the author_or_organization
212
+ >>> new_filter = ModelFilter(author_or_organization="facebook")
213
+
214
+ >>> # For the library
215
+ >>> new_filter = ModelFilter(library="pytorch")
216
+
217
+ >>> # For the language
218
+ >>> new_filter = ModelFilter(language="french")
219
+
220
+ >>> # For the model_name
221
+ >>> new_filter = ModelFilter(model_name="bert")
222
+
223
+ >>> # For the task
224
+ >>> new_filter = ModelFilter(task="text-classification")
225
+
226
+ >>> from huggingface_hub import HfApi
227
+
228
+ >>> api = HfApi()
229
+ # To list model tags
230
+
231
+ >>> new_filter = ModelFilter(tags="benchmark:raft")
232
+
233
+ >>> # Related to the dataset
234
+ >>> new_filter = ModelFilter(trained_dataset="common_voice")
235
+ ```
236
+ """
237
+
238
+ author: Optional[str] = None
239
+ library: Optional[Union[str, List[str]]] = None
240
+ language: Optional[Union[str, List[str]]] = None
241
+ model_name: Optional[str] = None
242
+ task: Optional[Union[str, List[str]]] = None
243
+ trained_dataset: Optional[Union[str, List[str]]] = None
244
+ tags: Optional[Union[str, List[str]]] = None
245
+
246
+ def __post_init__(self):
247
+ warnings.warn(
248
+ "'ModelFilter' is deprecated and will be removed in huggingface_hub>=0.24. Please pass the filter parameters as keyword arguments directly to the `list_models` method.",
249
+ FutureWarning,
250
+ )