Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_100_mp_rank_00_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_100_mp_rank_03_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_124_mp_rank_00_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_140_mp_rank_02_optim_states.pt +3 -0
- venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/INSTALLER +1 -0
- venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/LICENSE.rst +28 -0
- venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/METADATA +93 -0
- venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/RECORD +14 -0
- venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/WHEEL +6 -0
- venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/top_level.txt +1 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__init__.py +884 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_login.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_multi_commits.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_space_api.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_tensorboard_logger.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/community.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/constants.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/errors.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/file_download.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/hf_api.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/inference_api.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/keras_mixin.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/lfs.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/repocard_data.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/repository.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_commit_api.py +698 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py +327 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py +384 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_login.py +396 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py +306 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py +327 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_space_api.py +155 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_tensorboard_logger.py +169 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_webhooks_payload.py +116 -0
- venv/lib/python3.10/site-packages/huggingface_hub/_webhooks_server.py +380 -0
- venv/lib/python3.10/site-packages/huggingface_hub/community.py +355 -0
- venv/lib/python3.10/site-packages/huggingface_hub/constants.py +215 -0
- venv/lib/python3.10/site-packages/huggingface_hub/errors.py +38 -0
- venv/lib/python3.10/site-packages/huggingface_hub/fastai_utils.py +425 -0
- venv/lib/python3.10/site-packages/huggingface_hub/file_download.py +1770 -0
- venv/lib/python3.10/site-packages/huggingface_hub/hf_api.py +0 -0
- venv/lib/python3.10/site-packages/huggingface_hub/hf_file_system.py +867 -0
- venv/lib/python3.10/site-packages/huggingface_hub/hub_mixin.py +704 -0
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_100_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2f364227c7a3219fd056c103d9fd8dc0127cf306f1a7f77327864f6a98fa6a07
|
3 |
+
size 41830212
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_100_mp_rank_03_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:370e1a75c199b6f3bd4da245767de64060172245c1483ff9cf36d336bb23b032
|
3 |
+
size 41830404
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_124_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d653681a7c4312f17e4432664515fd1516b85f1b63ec843f319e95c832e35d6b
|
3 |
+
size 41830212
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_140_mp_rank_02_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b5a2d41e00f44f132695d5e0a0a7bae97b2f8cc4f8d43cf3f92a362f07f2f495
|
3 |
+
size 41830340
|
venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/LICENSE.rst
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright 2010 Pallets
|
2 |
+
|
3 |
+
Redistribution and use in source and binary forms, with or without
|
4 |
+
modification, are permitted provided that the following conditions are
|
5 |
+
met:
|
6 |
+
|
7 |
+
1. Redistributions of source code must retain the above copyright
|
8 |
+
notice, this list of conditions and the following disclaimer.
|
9 |
+
|
10 |
+
2. Redistributions in binary form must reproduce the above copyright
|
11 |
+
notice, this list of conditions and the following disclaimer in the
|
12 |
+
documentation and/or other materials provided with the distribution.
|
13 |
+
|
14 |
+
3. Neither the name of the copyright holder nor the names of its
|
15 |
+
contributors may be used to endorse or promote products derived from
|
16 |
+
this software without specific prior written permission.
|
17 |
+
|
18 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
19 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
20 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
21 |
+
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
22 |
+
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
23 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
24 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
25 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
26 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
27 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
28 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/METADATA
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: MarkupSafe
|
3 |
+
Version: 2.1.5
|
4 |
+
Summary: Safely add untrusted strings to HTML/XML markup.
|
5 |
+
Home-page: https://palletsprojects.com/p/markupsafe/
|
6 |
+
Maintainer: Pallets
|
7 |
+
Maintainer-email: [email protected]
|
8 |
+
License: BSD-3-Clause
|
9 |
+
Project-URL: Donate, https://palletsprojects.com/donate
|
10 |
+
Project-URL: Documentation, https://markupsafe.palletsprojects.com/
|
11 |
+
Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
|
12 |
+
Project-URL: Source Code, https://github.com/pallets/markupsafe/
|
13 |
+
Project-URL: Issue Tracker, https://github.com/pallets/markupsafe/issues/
|
14 |
+
Project-URL: Chat, https://discord.gg/pallets
|
15 |
+
Classifier: Development Status :: 5 - Production/Stable
|
16 |
+
Classifier: Environment :: Web Environment
|
17 |
+
Classifier: Intended Audience :: Developers
|
18 |
+
Classifier: License :: OSI Approved :: BSD License
|
19 |
+
Classifier: Operating System :: OS Independent
|
20 |
+
Classifier: Programming Language :: Python
|
21 |
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
22 |
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
23 |
+
Requires-Python: >=3.7
|
24 |
+
Description-Content-Type: text/x-rst
|
25 |
+
License-File: LICENSE.rst
|
26 |
+
|
27 |
+
MarkupSafe
|
28 |
+
==========
|
29 |
+
|
30 |
+
MarkupSafe implements a text object that escapes characters so it is
|
31 |
+
safe to use in HTML and XML. Characters that have special meanings are
|
32 |
+
replaced so that they display as the actual characters. This mitigates
|
33 |
+
injection attacks, meaning untrusted user input can safely be displayed
|
34 |
+
on a page.
|
35 |
+
|
36 |
+
|
37 |
+
Installing
|
38 |
+
----------
|
39 |
+
|
40 |
+
Install and update using `pip`_:
|
41 |
+
|
42 |
+
.. code-block:: text
|
43 |
+
|
44 |
+
pip install -U MarkupSafe
|
45 |
+
|
46 |
+
.. _pip: https://pip.pypa.io/en/stable/getting-started/
|
47 |
+
|
48 |
+
|
49 |
+
Examples
|
50 |
+
--------
|
51 |
+
|
52 |
+
.. code-block:: pycon
|
53 |
+
|
54 |
+
>>> from markupsafe import Markup, escape
|
55 |
+
|
56 |
+
>>> # escape replaces special characters and wraps in Markup
|
57 |
+
>>> escape("<script>alert(document.cookie);</script>")
|
58 |
+
Markup('<script>alert(document.cookie);</script>')
|
59 |
+
|
60 |
+
>>> # wrap in Markup to mark text "safe" and prevent escaping
|
61 |
+
>>> Markup("<strong>Hello</strong>")
|
62 |
+
Markup('<strong>hello</strong>')
|
63 |
+
|
64 |
+
>>> escape(Markup("<strong>Hello</strong>"))
|
65 |
+
Markup('<strong>hello</strong>')
|
66 |
+
|
67 |
+
>>> # Markup is a str subclass
|
68 |
+
>>> # methods and operators escape their arguments
|
69 |
+
>>> template = Markup("Hello <em>{name}</em>")
|
70 |
+
>>> template.format(name='"World"')
|
71 |
+
Markup('Hello <em>"World"</em>')
|
72 |
+
|
73 |
+
|
74 |
+
Donate
|
75 |
+
------
|
76 |
+
|
77 |
+
The Pallets organization develops and supports MarkupSafe and other
|
78 |
+
popular packages. In order to grow the community of contributors and
|
79 |
+
users, and allow the maintainers to devote more time to the projects,
|
80 |
+
`please donate today`_.
|
81 |
+
|
82 |
+
.. _please donate today: https://palletsprojects.com/donate
|
83 |
+
|
84 |
+
|
85 |
+
Links
|
86 |
+
-----
|
87 |
+
|
88 |
+
- Documentation: https://markupsafe.palletsprojects.com/
|
89 |
+
- Changes: https://markupsafe.palletsprojects.com/changes/
|
90 |
+
- PyPI Releases: https://pypi.org/project/MarkupSafe/
|
91 |
+
- Source Code: https://github.com/pallets/markupsafe/
|
92 |
+
- Issue Tracker: https://github.com/pallets/markupsafe/issues/
|
93 |
+
- Chat: https://discord.gg/pallets
|
venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/RECORD
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MarkupSafe-2.1.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
MarkupSafe-2.1.5.dist-info/LICENSE.rst,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475
|
3 |
+
MarkupSafe-2.1.5.dist-info/METADATA,sha256=2dRDPam6OZLfpX0wg1JN5P3u9arqACxVSfdGmsJU7o8,3003
|
4 |
+
MarkupSafe-2.1.5.dist-info/RECORD,,
|
5 |
+
MarkupSafe-2.1.5.dist-info/WHEEL,sha256=1FEjxEYgybphwh9S0FO9IcZ0B-NIeM2ko8OzhFZeOeQ,152
|
6 |
+
MarkupSafe-2.1.5.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11
|
7 |
+
markupsafe/__init__.py,sha256=r7VOTjUq7EMQ4v3p4R1LoVOGJg6ysfYRncLr34laRBs,10958
|
8 |
+
markupsafe/__pycache__/__init__.cpython-310.pyc,,
|
9 |
+
markupsafe/__pycache__/_native.cpython-310.pyc,,
|
10 |
+
markupsafe/_native.py,sha256=GR86Qvo_GcgKmKreA1WmYN9ud17OFwkww8E-fiW-57s,1713
|
11 |
+
markupsafe/_speedups.c,sha256=X2XvQVtIdcK4Usz70BvkzoOfjTCmQlDkkjYSn-swE0g,7083
|
12 |
+
markupsafe/_speedups.cpython-310-x86_64-linux-gnu.so,sha256=kPt-fhZ_RG7PUbDvwmyC26ZvRJ9DvUlF3hszBIB6_xs,44240
|
13 |
+
markupsafe/_speedups.pyi,sha256=vfMCsOgbAXRNLUXkyuyonG8uEWKYU4PDqNuMaDELAYw,229
|
14 |
+
markupsafe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/WHEEL
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.42.0)
|
3 |
+
Root-Is-Purelib: false
|
4 |
+
Tag: cp310-cp310-manylinux_2_17_x86_64
|
5 |
+
Tag: cp310-cp310-manylinux2014_x86_64
|
6 |
+
|
venv/lib/python3.10/site-packages/MarkupSafe-2.1.5.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
markupsafe
|
venv/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 |
+
)
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (14.4 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-310.pyc
ADDED
Binary file (22.7 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-310.pyc
ADDED
Binary file (12.6 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-310.pyc
ADDED
Binary file (14.7 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_login.cpython-310.pyc
ADDED
Binary file (12.9 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_multi_commits.cpython-310.pyc
ADDED
Binary file (11.7 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-310.pyc
ADDED
Binary file (11.5 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_space_api.cpython-310.pyc
ADDED
Binary file (5.25 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_tensorboard_logger.cpython-310.pyc
ADDED
Binary file (6.09 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-310.pyc
ADDED
Binary file (3.1 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/community.cpython-310.pyc
ADDED
Binary file (13 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/constants.cpython-310.pyc
ADDED
Binary file (4.53 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/errors.cpython-310.pyc
ADDED
Binary file (1.36 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-310.pyc
ADDED
Binary file (14.2 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/file_download.cpython-310.pyc
ADDED
Binary file (50.4 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/hf_api.cpython-310.pyc
ADDED
Binary file (307 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/inference_api.cpython-310.pyc
ADDED
Binary file (7.58 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/keras_mixin.cpython-310.pyc
ADDED
Binary file (17.2 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/lfs.cpython-310.pyc
ADDED
Binary file (16.7 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/repocard_data.cpython-310.pyc
ADDED
Binary file (27.3 kB). View file
|
|
venv/lib/python3.10/site-packages/huggingface_hub/__pycache__/repository.cpython-310.pyc
ADDED
Binary file (45.5 kB). View file
|
|
venv/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).")
|
venv/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)
|
venv/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"]
|
venv/lib/python3.10/site-packages/huggingface_hub/_login.py
ADDED
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
"""Contains methods to login to the Hub."""
|
15 |
+
|
16 |
+
import os
|
17 |
+
import subprocess
|
18 |
+
from functools import partial
|
19 |
+
from getpass import getpass
|
20 |
+
from pathlib import Path
|
21 |
+
from typing import Optional
|
22 |
+
|
23 |
+
from . import constants
|
24 |
+
from .commands._cli_utils import ANSI
|
25 |
+
from .utils import (
|
26 |
+
capture_output,
|
27 |
+
get_token,
|
28 |
+
is_google_colab,
|
29 |
+
is_notebook,
|
30 |
+
list_credential_helpers,
|
31 |
+
logging,
|
32 |
+
run_subprocess,
|
33 |
+
set_git_credential,
|
34 |
+
unset_git_credential,
|
35 |
+
)
|
36 |
+
from .utils._token import _get_token_from_environment, _get_token_from_google_colab
|
37 |
+
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
_HF_LOGO_ASCII = """
|
42 |
+
_| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|
|
43 |
+
_| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
|
44 |
+
_|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|
|
45 |
+
_| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
|
46 |
+
_| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|
|
47 |
+
"""
|
48 |
+
|
49 |
+
|
50 |
+
def login(
|
51 |
+
token: Optional[str] = None,
|
52 |
+
add_to_git_credential: bool = False,
|
53 |
+
new_session: bool = True,
|
54 |
+
write_permission: bool = False,
|
55 |
+
) -> None:
|
56 |
+
"""Login the machine to access the Hub.
|
57 |
+
|
58 |
+
The `token` is persisted in cache and set as a git credential. Once done, the machine
|
59 |
+
is logged in and the access token will be available across all `huggingface_hub`
|
60 |
+
components. If `token` is not provided, it will be prompted to the user either with
|
61 |
+
a widget (in a notebook) or via the terminal.
|
62 |
+
|
63 |
+
To login from outside of a script, one can also use `huggingface-cli login` which is
|
64 |
+
a cli command that wraps [`login`].
|
65 |
+
|
66 |
+
<Tip>
|
67 |
+
|
68 |
+
[`login`] is a drop-in replacement method for [`notebook_login`] as it wraps and
|
69 |
+
extends its capabilities.
|
70 |
+
|
71 |
+
</Tip>
|
72 |
+
|
73 |
+
<Tip>
|
74 |
+
|
75 |
+
When the token is not passed, [`login`] will automatically detect if the script runs
|
76 |
+
in a notebook or not. However, this detection might not be accurate due to the
|
77 |
+
variety of notebooks that exists nowadays. If that is the case, you can always force
|
78 |
+
the UI by using [`notebook_login`] or [`interpreter_login`].
|
79 |
+
|
80 |
+
</Tip>
|
81 |
+
|
82 |
+
Args:
|
83 |
+
token (`str`, *optional*):
|
84 |
+
User access token to generate from https://huggingface.co/settings/token.
|
85 |
+
add_to_git_credential (`bool`, defaults to `False`):
|
86 |
+
If `True`, token will be set as git credential. If no git credential helper
|
87 |
+
is configured, a warning will be displayed to the user. If `token` is `None`,
|
88 |
+
the value of `add_to_git_credential` is ignored and will be prompted again
|
89 |
+
to the end user.
|
90 |
+
new_session (`bool`, defaults to `True`):
|
91 |
+
If `True`, will request a token even if one is already saved on the machine.
|
92 |
+
write_permission (`bool`, defaults to `False`):
|
93 |
+
If `True`, requires a token with write permission.
|
94 |
+
Raises:
|
95 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
96 |
+
If an organization token is passed. Only personal account tokens are valid
|
97 |
+
to login.
|
98 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
99 |
+
If token is invalid.
|
100 |
+
[`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
101 |
+
If running in a notebook but `ipywidgets` is not installed.
|
102 |
+
"""
|
103 |
+
if token is not None:
|
104 |
+
if not add_to_git_credential:
|
105 |
+
print(
|
106 |
+
"Token has not been saved to git credential helper. Pass"
|
107 |
+
" `add_to_git_credential=True` if you want to set the git"
|
108 |
+
" credential as well."
|
109 |
+
)
|
110 |
+
_login(token, add_to_git_credential=add_to_git_credential, write_permission=write_permission)
|
111 |
+
elif is_notebook():
|
112 |
+
notebook_login(new_session=new_session, write_permission=write_permission)
|
113 |
+
else:
|
114 |
+
interpreter_login(new_session=new_session, write_permission=write_permission)
|
115 |
+
|
116 |
+
|
117 |
+
def logout() -> None:
|
118 |
+
"""Logout the machine from the Hub.
|
119 |
+
|
120 |
+
Token is deleted from the machine and removed from git credential.
|
121 |
+
"""
|
122 |
+
if get_token() is None:
|
123 |
+
print("Not logged in!")
|
124 |
+
return
|
125 |
+
|
126 |
+
# Delete token from git credentials
|
127 |
+
unset_git_credential()
|
128 |
+
|
129 |
+
# Delete token file
|
130 |
+
try:
|
131 |
+
Path(constants.HF_TOKEN_PATH).unlink()
|
132 |
+
except FileNotFoundError:
|
133 |
+
pass
|
134 |
+
|
135 |
+
# Check if still logged in
|
136 |
+
if _get_token_from_google_colab() is not None:
|
137 |
+
raise EnvironmentError(
|
138 |
+
"You are automatically logged in using a Google Colab secret.\n"
|
139 |
+
"To log out, you must unset the `HF_TOKEN` secret in your Colab settings."
|
140 |
+
)
|
141 |
+
if _get_token_from_environment() is not None:
|
142 |
+
raise EnvironmentError(
|
143 |
+
"Token has been deleted from your machine but you are still logged in.\n"
|
144 |
+
"To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables."
|
145 |
+
)
|
146 |
+
|
147 |
+
print("Successfully logged out.")
|
148 |
+
|
149 |
+
|
150 |
+
###
|
151 |
+
# Interpreter-based login (text)
|
152 |
+
###
|
153 |
+
|
154 |
+
|
155 |
+
def interpreter_login(new_session: bool = True, write_permission: bool = False) -> None:
|
156 |
+
"""
|
157 |
+
Displays a prompt to login to the HF website and store the token.
|
158 |
+
|
159 |
+
This is equivalent to [`login`] without passing a token when not run in a notebook.
|
160 |
+
[`interpreter_login`] is useful if you want to force the use of the terminal prompt
|
161 |
+
instead of a notebook widget.
|
162 |
+
|
163 |
+
For more details, see [`login`].
|
164 |
+
|
165 |
+
Args:
|
166 |
+
new_session (`bool`, defaults to `True`):
|
167 |
+
If `True`, will request a token even if one is already saved on the machine.
|
168 |
+
write_permission (`bool`, defaults to `False`):
|
169 |
+
If `True`, requires a token with write permission.
|
170 |
+
|
171 |
+
"""
|
172 |
+
if not new_session and _current_token_okay(write_permission=write_permission):
|
173 |
+
print("User is already logged in.")
|
174 |
+
return
|
175 |
+
|
176 |
+
from .commands.delete_cache import _ask_for_confirmation_no_tui
|
177 |
+
|
178 |
+
print(_HF_LOGO_ASCII)
|
179 |
+
if get_token() is not None:
|
180 |
+
print(
|
181 |
+
" A token is already saved on your machine. Run `huggingface-cli"
|
182 |
+
" whoami` to get more information or `huggingface-cli logout` if you want"
|
183 |
+
" to log out."
|
184 |
+
)
|
185 |
+
print(" Setting a new token will erase the existing one.")
|
186 |
+
|
187 |
+
print(" To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .")
|
188 |
+
if os.name == "nt":
|
189 |
+
print("Token can be pasted using 'Right-Click'.")
|
190 |
+
token = getpass("Enter your token (input will not be visible): ")
|
191 |
+
add_to_git_credential = _ask_for_confirmation_no_tui("Add token as git credential?")
|
192 |
+
|
193 |
+
_login(token=token, add_to_git_credential=add_to_git_credential, write_permission=write_permission)
|
194 |
+
|
195 |
+
|
196 |
+
###
|
197 |
+
# Notebook-based login (widget)
|
198 |
+
###
|
199 |
+
|
200 |
+
NOTEBOOK_LOGIN_PASSWORD_HTML = """<center> <img
|
201 |
+
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
|
202 |
+
alt='Hugging Face'> <br> Immediately click login after typing your password or
|
203 |
+
it might be stored in plain text in this notebook file. </center>"""
|
204 |
+
|
205 |
+
|
206 |
+
NOTEBOOK_LOGIN_TOKEN_HTML_START = """<center> <img
|
207 |
+
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
|
208 |
+
alt='Hugging Face'> <br> Copy a token from <a
|
209 |
+
href="https://huggingface.co/settings/tokens" target="_blank">your Hugging Face
|
210 |
+
tokens page</a> and paste it below. <br> Immediately click login after copying
|
211 |
+
your token or it might be stored in plain text in this notebook file. </center>"""
|
212 |
+
|
213 |
+
|
214 |
+
NOTEBOOK_LOGIN_TOKEN_HTML_END = """
|
215 |
+
<b>Pro Tip:</b> If you don't already have one, you can create a dedicated
|
216 |
+
'notebooks' token with 'write' access, that you can then easily reuse for all
|
217 |
+
notebooks. </center>"""
|
218 |
+
|
219 |
+
|
220 |
+
def notebook_login(new_session: bool = True, write_permission: bool = False) -> None:
|
221 |
+
"""
|
222 |
+
Displays a widget to login to the HF website and store the token.
|
223 |
+
|
224 |
+
This is equivalent to [`login`] without passing a token when run in a notebook.
|
225 |
+
[`notebook_login`] is useful if you want to force the use of the notebook widget
|
226 |
+
instead of a prompt in the terminal.
|
227 |
+
|
228 |
+
For more details, see [`login`].
|
229 |
+
|
230 |
+
Args:
|
231 |
+
new_session (`bool`, defaults to `True`):
|
232 |
+
If `True`, will request a token even if one is already saved on the machine.
|
233 |
+
write_permission (`bool`, defaults to `False`):
|
234 |
+
If `True`, requires a token with write permission.
|
235 |
+
"""
|
236 |
+
try:
|
237 |
+
import ipywidgets.widgets as widgets # type: ignore
|
238 |
+
from IPython.display import display # type: ignore
|
239 |
+
except ImportError:
|
240 |
+
raise ImportError(
|
241 |
+
"The `notebook_login` function can only be used in a notebook (Jupyter or"
|
242 |
+
" Colab) and you need the `ipywidgets` module: `pip install ipywidgets`."
|
243 |
+
)
|
244 |
+
if not new_session and _current_token_okay(write_permission=write_permission):
|
245 |
+
print("User is already logged in.")
|
246 |
+
return
|
247 |
+
|
248 |
+
box_layout = widgets.Layout(display="flex", flex_flow="column", align_items="center", width="50%")
|
249 |
+
|
250 |
+
token_widget = widgets.Password(description="Token:")
|
251 |
+
git_checkbox_widget = widgets.Checkbox(value=True, description="Add token as git credential?")
|
252 |
+
token_finish_button = widgets.Button(description="Login")
|
253 |
+
|
254 |
+
login_token_widget = widgets.VBox(
|
255 |
+
[
|
256 |
+
widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_START),
|
257 |
+
token_widget,
|
258 |
+
git_checkbox_widget,
|
259 |
+
token_finish_button,
|
260 |
+
widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_END),
|
261 |
+
],
|
262 |
+
layout=box_layout,
|
263 |
+
)
|
264 |
+
display(login_token_widget)
|
265 |
+
|
266 |
+
# On click events
|
267 |
+
def login_token_event(t, write_permission: bool = False):
|
268 |
+
"""
|
269 |
+
Event handler for the login button.
|
270 |
+
|
271 |
+
Args:
|
272 |
+
write_permission (`bool`, defaults to `False`):
|
273 |
+
If `True`, requires a token with write permission.
|
274 |
+
"""
|
275 |
+
token = token_widget.value
|
276 |
+
add_to_git_credential = git_checkbox_widget.value
|
277 |
+
# Erase token and clear value to make sure it's not saved in the notebook.
|
278 |
+
token_widget.value = ""
|
279 |
+
# Hide inputs
|
280 |
+
login_token_widget.children = [widgets.Label("Connecting...")]
|
281 |
+
try:
|
282 |
+
with capture_output() as captured:
|
283 |
+
_login(token, add_to_git_credential=add_to_git_credential, write_permission=write_permission)
|
284 |
+
message = captured.getvalue()
|
285 |
+
except Exception as error:
|
286 |
+
message = str(error)
|
287 |
+
# Print result (success message or error)
|
288 |
+
login_token_widget.children = [widgets.Label(line) for line in message.split("\n") if line.strip()]
|
289 |
+
|
290 |
+
token_finish_button.on_click(partial(login_token_event, write_permission=write_permission))
|
291 |
+
|
292 |
+
|
293 |
+
###
|
294 |
+
# Login private helpers
|
295 |
+
###
|
296 |
+
|
297 |
+
|
298 |
+
def _login(token: str, add_to_git_credential: bool, write_permission: bool = False) -> None:
|
299 |
+
from .hf_api import get_token_permission # avoid circular import
|
300 |
+
|
301 |
+
if token.startswith("api_org"):
|
302 |
+
raise ValueError("You must use your personal account token, not an organization token.")
|
303 |
+
|
304 |
+
permission = get_token_permission(token)
|
305 |
+
if permission is None:
|
306 |
+
raise ValueError("Invalid token passed!")
|
307 |
+
elif write_permission and permission != "write":
|
308 |
+
raise ValueError(
|
309 |
+
"Token is valid but is 'read-only' and a 'write' token is required.\nPlease provide a new token with"
|
310 |
+
" correct permission."
|
311 |
+
)
|
312 |
+
print(f"Token is valid (permission: {permission}).")
|
313 |
+
|
314 |
+
if add_to_git_credential:
|
315 |
+
if _is_git_credential_helper_configured():
|
316 |
+
set_git_credential(token)
|
317 |
+
print(
|
318 |
+
"Your token has been saved in your configured git credential helpers"
|
319 |
+
+ f" ({','.join(list_credential_helpers())})."
|
320 |
+
)
|
321 |
+
else:
|
322 |
+
print("Token has not been saved to git credential helper.")
|
323 |
+
|
324 |
+
# Save token
|
325 |
+
path = Path(constants.HF_TOKEN_PATH)
|
326 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
327 |
+
path.write_text(token)
|
328 |
+
print(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
|
329 |
+
print("Login successful")
|
330 |
+
|
331 |
+
|
332 |
+
def _current_token_okay(write_permission: bool = False):
|
333 |
+
"""Check if the current token is valid.
|
334 |
+
|
335 |
+
Args:
|
336 |
+
write_permission (`bool`, defaults to `False`):
|
337 |
+
If `True`, requires a token with write permission.
|
338 |
+
|
339 |
+
Returns:
|
340 |
+
`bool`: `True` if the current token is valid, `False` otherwise.
|
341 |
+
"""
|
342 |
+
from .hf_api import get_token_permission # avoid circular import
|
343 |
+
|
344 |
+
permission = get_token_permission()
|
345 |
+
if permission is None or (write_permission and permission != "write"):
|
346 |
+
return False
|
347 |
+
return True
|
348 |
+
|
349 |
+
|
350 |
+
def _is_git_credential_helper_configured() -> bool:
|
351 |
+
"""Check if a git credential helper is configured.
|
352 |
+
|
353 |
+
Warns user if not the case (except for Google Colab where "store" is set by default
|
354 |
+
by `huggingface_hub`).
|
355 |
+
"""
|
356 |
+
helpers = list_credential_helpers()
|
357 |
+
if len(helpers) > 0:
|
358 |
+
return True # Do not warn: at least 1 helper is set
|
359 |
+
|
360 |
+
# Only in Google Colab to avoid the warning message
|
361 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1043#issuecomment-1247010710
|
362 |
+
if is_google_colab():
|
363 |
+
_set_store_as_git_credential_helper_globally()
|
364 |
+
return True # Do not warn: "store" is used by default in Google Colab
|
365 |
+
|
366 |
+
# Otherwise, warn user
|
367 |
+
print(
|
368 |
+
ANSI.red(
|
369 |
+
"Cannot authenticate through git-credential as no helper is defined on your"
|
370 |
+
" machine.\nYou might have to re-authenticate when pushing to the Hugging"
|
371 |
+
" Face Hub.\nRun the following command in your terminal in case you want to"
|
372 |
+
" set the 'store' credential helper as default.\n\ngit config --global"
|
373 |
+
" credential.helper store\n\nRead"
|
374 |
+
" https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more"
|
375 |
+
" details."
|
376 |
+
)
|
377 |
+
)
|
378 |
+
return False
|
379 |
+
|
380 |
+
|
381 |
+
def _set_store_as_git_credential_helper_globally() -> None:
|
382 |
+
"""Set globally the credential.helper to `store`.
|
383 |
+
|
384 |
+
To be used only in Google Colab as we assume the user doesn't care about the git
|
385 |
+
credential config. It is the only particular case where we don't want to display the
|
386 |
+
warning message in [`notebook_login()`].
|
387 |
+
|
388 |
+
Related:
|
389 |
+
- https://github.com/huggingface/huggingface_hub/issues/1043
|
390 |
+
- https://github.com/huggingface/huggingface_hub/issues/1051
|
391 |
+
- https://git-scm.com/docs/git-credential-store
|
392 |
+
"""
|
393 |
+
try:
|
394 |
+
run_subprocess("git config --global credential.helper store")
|
395 |
+
except subprocess.CalledProcessError as exc:
|
396 |
+
raise EnvironmentError(exc.stderr)
|
venv/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)}
|
venv/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
|
venv/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
|
venv/lib/python3.10/site-packages/huggingface_hub/_tensorboard_logger.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
"""Contains a logger to push training logs to the Hub, using Tensorboard."""
|
15 |
+
|
16 |
+
from pathlib import Path
|
17 |
+
from typing import TYPE_CHECKING, List, Optional, Union
|
18 |
+
|
19 |
+
from huggingface_hub._commit_scheduler import CommitScheduler
|
20 |
+
|
21 |
+
from .utils import experimental, is_tensorboard_available
|
22 |
+
|
23 |
+
|
24 |
+
if is_tensorboard_available():
|
25 |
+
from tensorboardX import SummaryWriter
|
26 |
+
|
27 |
+
# TODO: clarify: should we import from torch.utils.tensorboard ?
|
28 |
+
|
29 |
+
else:
|
30 |
+
SummaryWriter = object # Dummy class to avoid failing at import. Will raise on instance creation.
|
31 |
+
|
32 |
+
if TYPE_CHECKING:
|
33 |
+
from tensorboardX import SummaryWriter
|
34 |
+
|
35 |
+
|
36 |
+
class HFSummaryWriter(SummaryWriter):
|
37 |
+
"""
|
38 |
+
Wrapper around the tensorboard's `SummaryWriter` to push training logs to the Hub.
|
39 |
+
|
40 |
+
Data is logged locally and then pushed to the Hub asynchronously. Pushing data to the Hub is done in a separate
|
41 |
+
thread to avoid blocking the training script. In particular, if the upload fails for any reason (e.g. a connection
|
42 |
+
issue), the main script will not be interrupted. Data is automatically pushed to the Hub every `commit_every`
|
43 |
+
minutes (default to every 5 minutes).
|
44 |
+
|
45 |
+
<Tip warning={true}>
|
46 |
+
|
47 |
+
`HFSummaryWriter` is experimental. Its API is subject to change in the future without prior notice.
|
48 |
+
|
49 |
+
</Tip>
|
50 |
+
|
51 |
+
Args:
|
52 |
+
repo_id (`str`):
|
53 |
+
The id of the repo to which the logs will be pushed.
|
54 |
+
logdir (`str`, *optional*):
|
55 |
+
The directory where the logs will be written. If not specified, a local directory will be created by the
|
56 |
+
underlying `SummaryWriter` object.
|
57 |
+
commit_every (`int` or `float`, *optional*):
|
58 |
+
The frequency (in minutes) at which the logs will be pushed to the Hub. Defaults to 5 minutes.
|
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 |
+
repo_type (`str`, *optional*):
|
63 |
+
The type of the repo to which the logs will be pushed. Defaults to "model".
|
64 |
+
repo_revision (`str`, *optional*):
|
65 |
+
The revision of the repo to which the logs will be pushed. Defaults to "main".
|
66 |
+
repo_private (`bool`, *optional*):
|
67 |
+
Whether to create a private repo or not. Defaults to False. This argument is ignored if the repo already
|
68 |
+
exists.
|
69 |
+
path_in_repo (`str`, *optional*):
|
70 |
+
The path to the folder in the repo where the logs will be pushed. Defaults to "tensorboard/".
|
71 |
+
repo_allow_patterns (`List[str]` or `str`, *optional*):
|
72 |
+
A list of patterns to include in the upload. Defaults to `"*.tfevents.*"`. Check out the
|
73 |
+
[upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
|
74 |
+
repo_ignore_patterns (`List[str]` or `str`, *optional*):
|
75 |
+
A list of patterns to exclude in the upload. Check out the
|
76 |
+
[upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
|
77 |
+
token (`str`, *optional*):
|
78 |
+
Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more
|
79 |
+
details
|
80 |
+
kwargs:
|
81 |
+
Additional keyword arguments passed to `SummaryWriter`.
|
82 |
+
|
83 |
+
Examples:
|
84 |
+
```py
|
85 |
+
>>> from huggingface_hub import HFSummaryWriter
|
86 |
+
|
87 |
+
# Logs are automatically pushed every 15 minutes
|
88 |
+
>>> logger = HFSummaryWriter(repo_id="test_hf_logger", commit_every=15)
|
89 |
+
>>> logger.add_scalar("a", 1)
|
90 |
+
>>> logger.add_scalar("b", 2)
|
91 |
+
...
|
92 |
+
|
93 |
+
# You can also trigger a push manually
|
94 |
+
>>> logger.scheduler.trigger()
|
95 |
+
```
|
96 |
+
|
97 |
+
```py
|
98 |
+
>>> from huggingface_hub import HFSummaryWriter
|
99 |
+
|
100 |
+
# Logs are automatically pushed every 5 minutes (default) + when exiting the context manager
|
101 |
+
>>> with HFSummaryWriter(repo_id="test_hf_logger") as logger:
|
102 |
+
... logger.add_scalar("a", 1)
|
103 |
+
... logger.add_scalar("b", 2)
|
104 |
+
```
|
105 |
+
"""
|
106 |
+
|
107 |
+
@experimental
|
108 |
+
def __new__(cls, *args, **kwargs) -> "HFSummaryWriter":
|
109 |
+
if not is_tensorboard_available():
|
110 |
+
raise ImportError(
|
111 |
+
"You must have `tensorboard` installed to use `HFSummaryWriter`. Please run `pip install --upgrade"
|
112 |
+
" tensorboardX` first."
|
113 |
+
)
|
114 |
+
return super().__new__(cls)
|
115 |
+
|
116 |
+
def __init__(
|
117 |
+
self,
|
118 |
+
repo_id: str,
|
119 |
+
*,
|
120 |
+
logdir: Optional[str] = None,
|
121 |
+
commit_every: Union[int, float] = 5,
|
122 |
+
squash_history: bool = False,
|
123 |
+
repo_type: Optional[str] = None,
|
124 |
+
repo_revision: Optional[str] = None,
|
125 |
+
repo_private: bool = False,
|
126 |
+
path_in_repo: Optional[str] = "tensorboard",
|
127 |
+
repo_allow_patterns: Optional[Union[List[str], str]] = "*.tfevents.*",
|
128 |
+
repo_ignore_patterns: Optional[Union[List[str], str]] = None,
|
129 |
+
token: Optional[str] = None,
|
130 |
+
**kwargs,
|
131 |
+
):
|
132 |
+
# Initialize SummaryWriter
|
133 |
+
super().__init__(logdir=logdir, **kwargs)
|
134 |
+
|
135 |
+
# Check logdir has been correctly initialized and fail early otherwise. In practice, SummaryWriter takes care of it.
|
136 |
+
if not isinstance(self.logdir, str):
|
137 |
+
raise ValueError(f"`self.logdir` must be a string. Got '{self.logdir}' of type {type(self.logdir)}.")
|
138 |
+
|
139 |
+
# Append logdir name to `path_in_repo`
|
140 |
+
if path_in_repo is None or path_in_repo == "":
|
141 |
+
path_in_repo = Path(self.logdir).name
|
142 |
+
else:
|
143 |
+
path_in_repo = path_in_repo.strip("/") + "/" + Path(self.logdir).name
|
144 |
+
|
145 |
+
# Initialize scheduler
|
146 |
+
self.scheduler = CommitScheduler(
|
147 |
+
folder_path=self.logdir,
|
148 |
+
path_in_repo=path_in_repo,
|
149 |
+
repo_id=repo_id,
|
150 |
+
repo_type=repo_type,
|
151 |
+
revision=repo_revision,
|
152 |
+
private=repo_private,
|
153 |
+
token=token,
|
154 |
+
allow_patterns=repo_allow_patterns,
|
155 |
+
ignore_patterns=repo_ignore_patterns,
|
156 |
+
every=commit_every,
|
157 |
+
squash_history=squash_history,
|
158 |
+
)
|
159 |
+
|
160 |
+
# Exposing some high-level info at root level
|
161 |
+
self.repo_id = self.scheduler.repo_id
|
162 |
+
self.repo_type = self.scheduler.repo_type
|
163 |
+
self.repo_revision = self.scheduler.revision
|
164 |
+
|
165 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
166 |
+
"""Push to hub in a non-blocking way when exiting the logger's context manager."""
|
167 |
+
super().__exit__(exc_type, exc_val, exc_tb)
|
168 |
+
future = self.scheduler.trigger()
|
169 |
+
future.result()
|
venv/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
|
venv/lib/python3.10/site-packages/huggingface_hub/_webhooks_server.py
ADDED
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 `WebhooksServer` and `webhook_endpoint` to create a webhook server easily."""
|
16 |
+
|
17 |
+
import atexit
|
18 |
+
import inspect
|
19 |
+
import os
|
20 |
+
from functools import wraps
|
21 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
|
22 |
+
|
23 |
+
from .utils import experimental, is_gradio_available
|
24 |
+
from .utils._deprecation import _deprecate_method
|
25 |
+
|
26 |
+
|
27 |
+
if TYPE_CHECKING:
|
28 |
+
import gradio as gr
|
29 |
+
|
30 |
+
|
31 |
+
from fastapi import FastAPI, Request
|
32 |
+
from fastapi.responses import JSONResponse
|
33 |
+
|
34 |
+
|
35 |
+
_global_app: Optional["WebhooksServer"] = None
|
36 |
+
_is_local = os.getenv("SYSTEM") != "spaces"
|
37 |
+
|
38 |
+
|
39 |
+
@experimental
|
40 |
+
class WebhooksServer:
|
41 |
+
"""
|
42 |
+
The [`WebhooksServer`] class lets you create an instance of a Gradio app that can receive Huggingface webhooks.
|
43 |
+
These webhooks can be registered using the [`~WebhooksServer.add_webhook`] decorator. Webhook endpoints are added to
|
44 |
+
the app as a POST endpoint to the FastAPI router. Once all the webhooks are registered, the `run` method has to be
|
45 |
+
called to start the app.
|
46 |
+
|
47 |
+
It is recommended to accept [`WebhookPayload`] as the first argument of the webhook function. It is a Pydantic
|
48 |
+
model that contains all the information about the webhook event. The data will be parsed automatically for you.
|
49 |
+
|
50 |
+
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to setup your
|
51 |
+
WebhooksServer and deploy it on a Space.
|
52 |
+
|
53 |
+
<Tip warning={true}>
|
54 |
+
|
55 |
+
`WebhooksServer` is experimental. Its API is subject to change in the future.
|
56 |
+
|
57 |
+
</Tip>
|
58 |
+
|
59 |
+
<Tip warning={true}>
|
60 |
+
|
61 |
+
You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`).
|
62 |
+
|
63 |
+
</Tip>
|
64 |
+
|
65 |
+
Args:
|
66 |
+
ui (`gradio.Blocks`, optional):
|
67 |
+
A Gradio UI instance to be used as the Space landing page. If `None`, a UI displaying instructions
|
68 |
+
about the configured webhooks is created.
|
69 |
+
webhook_secret (`str`, optional):
|
70 |
+
A secret key to verify incoming webhook requests. You can set this value to any secret you want as long as
|
71 |
+
you also configure it in your [webhooks settings panel](https://huggingface.co/settings/webhooks). You
|
72 |
+
can also set this value as the `WEBHOOK_SECRET` environment variable. If no secret is provided, the
|
73 |
+
webhook endpoints are opened without any security.
|
74 |
+
|
75 |
+
Example:
|
76 |
+
|
77 |
+
```python
|
78 |
+
import gradio as gr
|
79 |
+
from huggingface_hub import WebhooksServer, WebhookPayload
|
80 |
+
|
81 |
+
with gr.Blocks() as ui:
|
82 |
+
...
|
83 |
+
|
84 |
+
app = WebhooksServer(ui=ui, webhook_secret="my_secret_key")
|
85 |
+
|
86 |
+
@app.add_webhook("/say_hello")
|
87 |
+
async def hello(payload: WebhookPayload):
|
88 |
+
return {"message": "hello"}
|
89 |
+
|
90 |
+
app.run()
|
91 |
+
```
|
92 |
+
"""
|
93 |
+
|
94 |
+
def __new__(cls, *args, **kwargs) -> "WebhooksServer":
|
95 |
+
if not is_gradio_available():
|
96 |
+
raise ImportError(
|
97 |
+
"You must have `gradio` installed to use `WebhooksServer`. Please run `pip install --upgrade gradio`"
|
98 |
+
" first."
|
99 |
+
)
|
100 |
+
return super().__new__(cls)
|
101 |
+
|
102 |
+
def __init__(
|
103 |
+
self,
|
104 |
+
ui: Optional["gr.Blocks"] = None,
|
105 |
+
webhook_secret: Optional[str] = None,
|
106 |
+
) -> None:
|
107 |
+
self._ui = ui
|
108 |
+
|
109 |
+
self.webhook_secret = webhook_secret or os.getenv("WEBHOOK_SECRET")
|
110 |
+
self.registered_webhooks: Dict[str, Callable] = {}
|
111 |
+
_warn_on_empty_secret(self.webhook_secret)
|
112 |
+
|
113 |
+
def add_webhook(self, path: Optional[str] = None) -> Callable:
|
114 |
+
"""
|
115 |
+
Decorator to add a webhook to the [`WebhooksServer`] server.
|
116 |
+
|
117 |
+
Args:
|
118 |
+
path (`str`, optional):
|
119 |
+
The URL path to register the webhook function. If not provided, the function name will be used as the
|
120 |
+
path. In any case, all webhooks are registered under `/webhooks`.
|
121 |
+
|
122 |
+
Raises:
|
123 |
+
ValueError: If the provided path is already registered as a webhook.
|
124 |
+
|
125 |
+
Example:
|
126 |
+
```python
|
127 |
+
from huggingface_hub import WebhooksServer, WebhookPayload
|
128 |
+
|
129 |
+
app = WebhooksServer()
|
130 |
+
|
131 |
+
@app.add_webhook
|
132 |
+
async def trigger_training(payload: WebhookPayload):
|
133 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
134 |
+
# Trigger a training job if a dataset is updated
|
135 |
+
...
|
136 |
+
|
137 |
+
app.run()
|
138 |
+
```
|
139 |
+
"""
|
140 |
+
# Usage: directly as decorator. Example: `@app.add_webhook`
|
141 |
+
if callable(path):
|
142 |
+
# If path is a function, it means it was used as a decorator without arguments
|
143 |
+
return self.add_webhook()(path)
|
144 |
+
|
145 |
+
# Usage: provide a path. Example: `@app.add_webhook(...)`
|
146 |
+
@wraps(FastAPI.post)
|
147 |
+
def _inner_post(*args, **kwargs):
|
148 |
+
func = args[0]
|
149 |
+
abs_path = f"/webhooks/{(path or func.__name__).strip('/')}"
|
150 |
+
if abs_path in self.registered_webhooks:
|
151 |
+
raise ValueError(f"Webhook {abs_path} already exists.")
|
152 |
+
self.registered_webhooks[abs_path] = func
|
153 |
+
|
154 |
+
return _inner_post
|
155 |
+
|
156 |
+
def launch(self, prevent_thread_lock: bool = False, **launch_kwargs: Any) -> None:
|
157 |
+
"""Launch the Gradio app and register webhooks to the underlying FastAPI server.
|
158 |
+
|
159 |
+
Input parameters are forwarded to Gradio when launching the app.
|
160 |
+
"""
|
161 |
+
ui = self._ui or self._get_default_ui()
|
162 |
+
|
163 |
+
# Start Gradio App
|
164 |
+
# - as non-blocking so that webhooks can be added afterwards
|
165 |
+
# - as shared if launch locally (to debug webhooks)
|
166 |
+
launch_kwargs.setdefault("share", _is_local)
|
167 |
+
self.fastapi_app, _, _ = ui.launch(prevent_thread_lock=True, **launch_kwargs)
|
168 |
+
|
169 |
+
# Register webhooks to FastAPI app
|
170 |
+
for path, func in self.registered_webhooks.items():
|
171 |
+
# Add secret check if required
|
172 |
+
if self.webhook_secret is not None:
|
173 |
+
func = _wrap_webhook_to_check_secret(func, webhook_secret=self.webhook_secret)
|
174 |
+
|
175 |
+
# Add route to FastAPI app
|
176 |
+
self.fastapi_app.post(path)(func)
|
177 |
+
|
178 |
+
# Print instructions and block main thread
|
179 |
+
url = (ui.share_url or ui.local_url).strip("/")
|
180 |
+
message = "\nWebhooks are correctly setup and ready to use:"
|
181 |
+
message += "\n" + "\n".join(f" - POST {url}{webhook}" for webhook in self.registered_webhooks)
|
182 |
+
message += "\nGo to https://huggingface.co/settings/webhooks to setup your webhooks."
|
183 |
+
print(message)
|
184 |
+
|
185 |
+
if not prevent_thread_lock:
|
186 |
+
ui.block_thread()
|
187 |
+
|
188 |
+
@_deprecate_method(version="0.23", message="Use `WebhooksServer.launch` instead.")
|
189 |
+
def run(self) -> None:
|
190 |
+
return self.launch()
|
191 |
+
|
192 |
+
def _get_default_ui(self) -> "gr.Blocks":
|
193 |
+
"""Default UI if not provided (lists webhooks and provides basic instructions)."""
|
194 |
+
import gradio as gr
|
195 |
+
|
196 |
+
with gr.Blocks() as ui:
|
197 |
+
gr.Markdown("# This is an app to process 🤗 Webhooks")
|
198 |
+
gr.Markdown(
|
199 |
+
"Webhooks are a foundation for MLOps-related features. They allow you to listen for new changes on"
|
200 |
+
" specific repos or to all repos belonging to particular set of users/organizations (not just your"
|
201 |
+
" repos, but any repo). Check out this [guide](https://huggingface.co/docs/hub/webhooks) to get to"
|
202 |
+
" know more about webhooks on the Huggingface Hub."
|
203 |
+
)
|
204 |
+
gr.Markdown(
|
205 |
+
f"{len(self.registered_webhooks)} webhook(s) are registered:"
|
206 |
+
+ "\n\n"
|
207 |
+
+ "\n ".join(
|
208 |
+
f"- [{webhook_path}]({_get_webhook_doc_url(webhook.__name__, webhook_path)})"
|
209 |
+
for webhook_path, webhook in self.registered_webhooks.items()
|
210 |
+
)
|
211 |
+
)
|
212 |
+
gr.Markdown(
|
213 |
+
"Go to https://huggingface.co/settings/webhooks to setup your webhooks."
|
214 |
+
+ "\nYou app is running locally. Please look at the logs to check the full URL you need to set."
|
215 |
+
if _is_local
|
216 |
+
else (
|
217 |
+
"\nThis app is running on a Space. You can find the corresponding URL in the options menu"
|
218 |
+
" (top-right) > 'Embed the Space'. The URL looks like 'https://{username}-{repo_name}.hf.space'."
|
219 |
+
)
|
220 |
+
)
|
221 |
+
return ui
|
222 |
+
|
223 |
+
|
224 |
+
@experimental
|
225 |
+
def webhook_endpoint(path: Optional[str] = None) -> Callable:
|
226 |
+
"""Decorator to start a [`WebhooksServer`] and register the decorated function as a webhook endpoint.
|
227 |
+
|
228 |
+
This is a helper to get started quickly. If you need more flexibility (custom landing page or webhook secret),
|
229 |
+
you can use [`WebhooksServer`] directly. You can register multiple webhook endpoints (to the same server) by using
|
230 |
+
this decorator multiple times.
|
231 |
+
|
232 |
+
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to setup your
|
233 |
+
server and deploy it on a Space.
|
234 |
+
|
235 |
+
<Tip warning={true}>
|
236 |
+
|
237 |
+
`webhook_endpoint` is experimental. Its API is subject to change in the future.
|
238 |
+
|
239 |
+
</Tip>
|
240 |
+
|
241 |
+
<Tip warning={true}>
|
242 |
+
|
243 |
+
You must have `gradio` installed to use `webhook_endpoint` (`pip install --upgrade gradio`).
|
244 |
+
|
245 |
+
</Tip>
|
246 |
+
|
247 |
+
Args:
|
248 |
+
path (`str`, optional):
|
249 |
+
The URL path to register the webhook function. If not provided, the function name will be used as the path.
|
250 |
+
In any case, all webhooks are registered under `/webhooks`.
|
251 |
+
|
252 |
+
Examples:
|
253 |
+
The default usage is to register a function as a webhook endpoint. The function name will be used as the path.
|
254 |
+
The server will be started automatically at exit (i.e. at the end of the script).
|
255 |
+
|
256 |
+
```python
|
257 |
+
from huggingface_hub import webhook_endpoint, WebhookPayload
|
258 |
+
|
259 |
+
@webhook_endpoint
|
260 |
+
async def trigger_training(payload: WebhookPayload):
|
261 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
262 |
+
# Trigger a training job if a dataset is updated
|
263 |
+
...
|
264 |
+
|
265 |
+
# Server is automatically started at the end of the script.
|
266 |
+
```
|
267 |
+
|
268 |
+
Advanced usage: register a function as a webhook endpoint and start the server manually. This is useful if you
|
269 |
+
are running it in a notebook.
|
270 |
+
|
271 |
+
```python
|
272 |
+
from huggingface_hub import webhook_endpoint, WebhookPayload
|
273 |
+
|
274 |
+
@webhook_endpoint
|
275 |
+
async def trigger_training(payload: WebhookPayload):
|
276 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
277 |
+
# Trigger a training job if a dataset is updated
|
278 |
+
...
|
279 |
+
|
280 |
+
# Start the server manually
|
281 |
+
trigger_training.run()
|
282 |
+
```
|
283 |
+
"""
|
284 |
+
if callable(path):
|
285 |
+
# If path is a function, it means it was used as a decorator without arguments
|
286 |
+
return webhook_endpoint()(path)
|
287 |
+
|
288 |
+
@wraps(WebhooksServer.add_webhook)
|
289 |
+
def _inner(func: Callable) -> Callable:
|
290 |
+
app = _get_global_app()
|
291 |
+
app.add_webhook(path)(func)
|
292 |
+
if len(app.registered_webhooks) == 1:
|
293 |
+
# Register `app.run` to run at exit (only once)
|
294 |
+
atexit.register(app.run)
|
295 |
+
|
296 |
+
@wraps(app.run)
|
297 |
+
def _run_now():
|
298 |
+
# Run the app directly (without waiting atexit)
|
299 |
+
atexit.unregister(app.run)
|
300 |
+
app.run()
|
301 |
+
|
302 |
+
func.run = _run_now # type: ignore
|
303 |
+
return func
|
304 |
+
|
305 |
+
return _inner
|
306 |
+
|
307 |
+
|
308 |
+
def _get_global_app() -> WebhooksServer:
|
309 |
+
global _global_app
|
310 |
+
if _global_app is None:
|
311 |
+
_global_app = WebhooksServer()
|
312 |
+
return _global_app
|
313 |
+
|
314 |
+
|
315 |
+
def _warn_on_empty_secret(webhook_secret: Optional[str]) -> None:
|
316 |
+
if webhook_secret is None:
|
317 |
+
print("Webhook secret is not defined. This means your webhook endpoints will be open to everyone.")
|
318 |
+
print(
|
319 |
+
"To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization: "
|
320 |
+
"\n\t`app = WebhooksServer(webhook_secret='my_secret', ...)`"
|
321 |
+
)
|
322 |
+
print(
|
323 |
+
"For more details about webhook secrets, please refer to"
|
324 |
+
" https://huggingface.co/docs/hub/webhooks#webhook-secret."
|
325 |
+
)
|
326 |
+
else:
|
327 |
+
print("Webhook secret is correctly defined.")
|
328 |
+
|
329 |
+
|
330 |
+
def _get_webhook_doc_url(webhook_name: str, webhook_path: str) -> str:
|
331 |
+
"""Returns the anchor to a given webhook in the docs (experimental)"""
|
332 |
+
return "/docs#/default/" + webhook_name + webhook_path.replace("/", "_") + "_post"
|
333 |
+
|
334 |
+
|
335 |
+
def _wrap_webhook_to_check_secret(func: Callable, webhook_secret: str) -> Callable:
|
336 |
+
"""Wraps a webhook function to check the webhook secret before calling the function.
|
337 |
+
|
338 |
+
This is a hacky way to add the `request` parameter to the function signature. Since FastAPI based itself on route
|
339 |
+
parameters to inject the values to the function, we need to hack the function signature to retrieve the `Request`
|
340 |
+
object (and hence the headers). A far cleaner solution would be to use a middleware. However, since
|
341 |
+
`fastapi==0.90.1`, a middleware cannot be added once the app has started. And since the FastAPI app is started by
|
342 |
+
Gradio internals (and not by us), we cannot add a middleware.
|
343 |
+
|
344 |
+
This method is called only when a secret has been defined by the user. If a request is sent without the
|
345 |
+
"x-webhook-secret", the function will return a 401 error (unauthorized). If the header is sent but is incorrect,
|
346 |
+
the function will return a 403 error (forbidden).
|
347 |
+
|
348 |
+
Inspired by https://stackoverflow.com/a/33112180.
|
349 |
+
"""
|
350 |
+
initial_sig = inspect.signature(func)
|
351 |
+
|
352 |
+
@wraps(func)
|
353 |
+
async def _protected_func(request: Request, **kwargs):
|
354 |
+
request_secret = request.headers.get("x-webhook-secret")
|
355 |
+
if request_secret is None:
|
356 |
+
return JSONResponse({"error": "x-webhook-secret header not set."}, status_code=401)
|
357 |
+
if request_secret != webhook_secret:
|
358 |
+
return JSONResponse({"error": "Invalid webhook secret."}, status_code=403)
|
359 |
+
|
360 |
+
# Inject `request` in kwargs if required
|
361 |
+
if "request" in initial_sig.parameters:
|
362 |
+
kwargs["request"] = request
|
363 |
+
|
364 |
+
# Handle both sync and async routes
|
365 |
+
if inspect.iscoroutinefunction(func):
|
366 |
+
return await func(**kwargs)
|
367 |
+
else:
|
368 |
+
return func(**kwargs)
|
369 |
+
|
370 |
+
# Update signature to include request
|
371 |
+
if "request" not in initial_sig.parameters:
|
372 |
+
_protected_func.__signature__ = initial_sig.replace( # type: ignore
|
373 |
+
parameters=(
|
374 |
+
inspect.Parameter(name="request", kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request),
|
375 |
+
)
|
376 |
+
+ tuple(initial_sig.parameters.values())
|
377 |
+
)
|
378 |
+
|
379 |
+
# Return protected route
|
380 |
+
return _protected_func
|
venv/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)
|
venv/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 |
+
]
|
venv/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
|
venv/lib/python3.10/site-packages/huggingface_hub/fastai_utils.py
ADDED
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
from pathlib import Path
|
4 |
+
from pickle import DEFAULT_PROTOCOL, PicklingError
|
5 |
+
from typing import Any, Dict, List, Optional, Union
|
6 |
+
|
7 |
+
from packaging import version
|
8 |
+
|
9 |
+
from huggingface_hub import snapshot_download
|
10 |
+
from huggingface_hub.constants import CONFIG_NAME
|
11 |
+
from huggingface_hub.hf_api import HfApi
|
12 |
+
from huggingface_hub.utils import (
|
13 |
+
SoftTemporaryDirectory,
|
14 |
+
get_fastai_version,
|
15 |
+
get_fastcore_version,
|
16 |
+
get_python_version,
|
17 |
+
)
|
18 |
+
|
19 |
+
from .utils import logging, validate_hf_hub_args
|
20 |
+
from .utils._runtime import _PY_VERSION # noqa: F401 # for backward compatibility...
|
21 |
+
|
22 |
+
|
23 |
+
logger = logging.get_logger(__name__)
|
24 |
+
|
25 |
+
|
26 |
+
def _check_fastai_fastcore_versions(
|
27 |
+
fastai_min_version: str = "2.4",
|
28 |
+
fastcore_min_version: str = "1.3.27",
|
29 |
+
):
|
30 |
+
"""
|
31 |
+
Checks that the installed fastai and fastcore versions are compatible for pickle serialization.
|
32 |
+
|
33 |
+
Args:
|
34 |
+
fastai_min_version (`str`, *optional*):
|
35 |
+
The minimum fastai version supported.
|
36 |
+
fastcore_min_version (`str`, *optional*):
|
37 |
+
The minimum fastcore version supported.
|
38 |
+
|
39 |
+
<Tip>
|
40 |
+
Raises the following error:
|
41 |
+
|
42 |
+
- [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
43 |
+
if the fastai or fastcore libraries are not available or are of an invalid version.
|
44 |
+
|
45 |
+
</Tip>
|
46 |
+
"""
|
47 |
+
|
48 |
+
if (get_fastcore_version() or get_fastai_version()) == "N/A":
|
49 |
+
raise ImportError(
|
50 |
+
f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are"
|
51 |
+
f" required. Currently using fastai=={get_fastai_version()} and"
|
52 |
+
f" fastcore=={get_fastcore_version()}."
|
53 |
+
)
|
54 |
+
|
55 |
+
current_fastai_version = version.Version(get_fastai_version())
|
56 |
+
current_fastcore_version = version.Version(get_fastcore_version())
|
57 |
+
|
58 |
+
if current_fastai_version < version.Version(fastai_min_version):
|
59 |
+
raise ImportError(
|
60 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require a"
|
61 |
+
f" fastai>={fastai_min_version} version, but you are using fastai version"
|
62 |
+
f" {get_fastai_version()} which is incompatible. Upgrade with `pip install"
|
63 |
+
" fastai==2.5.6`."
|
64 |
+
)
|
65 |
+
|
66 |
+
if current_fastcore_version < version.Version(fastcore_min_version):
|
67 |
+
raise ImportError(
|
68 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require a"
|
69 |
+
f" fastcore>={fastcore_min_version} version, but you are using fastcore"
|
70 |
+
f" version {get_fastcore_version()} which is incompatible. Upgrade with"
|
71 |
+
" `pip install fastcore==1.3.27`."
|
72 |
+
)
|
73 |
+
|
74 |
+
|
75 |
+
def _check_fastai_fastcore_pyproject_versions(
|
76 |
+
storage_folder: str,
|
77 |
+
fastai_min_version: str = "2.4",
|
78 |
+
fastcore_min_version: str = "1.3.27",
|
79 |
+
):
|
80 |
+
"""
|
81 |
+
Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions
|
82 |
+
that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist
|
83 |
+
or does not contain versions for fastai and fastcore, then it logs a warning.
|
84 |
+
|
85 |
+
Args:
|
86 |
+
storage_folder (`str`):
|
87 |
+
Folder to look for the `pyproject.toml` file.
|
88 |
+
fastai_min_version (`str`, *optional*):
|
89 |
+
The minimum fastai version supported.
|
90 |
+
fastcore_min_version (`str`, *optional*):
|
91 |
+
The minimum fastcore version supported.
|
92 |
+
|
93 |
+
<Tip>
|
94 |
+
Raises the following errors:
|
95 |
+
|
96 |
+
- [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
97 |
+
if the `toml` module is not installed.
|
98 |
+
- [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
99 |
+
if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore.
|
100 |
+
|
101 |
+
</Tip>
|
102 |
+
"""
|
103 |
+
|
104 |
+
try:
|
105 |
+
import toml
|
106 |
+
except ModuleNotFoundError:
|
107 |
+
raise ImportError(
|
108 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module."
|
109 |
+
" Install it with `pip install toml`."
|
110 |
+
)
|
111 |
+
|
112 |
+
# Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages.
|
113 |
+
if not os.path.isfile(f"{storage_folder}/pyproject.toml"):
|
114 |
+
logger.warning(
|
115 |
+
"There is no `pyproject.toml` in the repository that contains the fastai"
|
116 |
+
" `Learner`. The `pyproject.toml` would allow us to verify that your fastai"
|
117 |
+
" and fastcore versions are compatible with those of the model you want to"
|
118 |
+
" load."
|
119 |
+
)
|
120 |
+
return
|
121 |
+
pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml")
|
122 |
+
|
123 |
+
if "build-system" not in pyproject_toml.keys():
|
124 |
+
logger.warning(
|
125 |
+
"There is no `build-system` section in the pyproject.toml of the repository"
|
126 |
+
" that contains the fastai `Learner`. The `build-system` would allow us to"
|
127 |
+
" verify that your fastai and fastcore versions are compatible with those"
|
128 |
+
" of the model you want to load."
|
129 |
+
)
|
130 |
+
return
|
131 |
+
build_system_toml = pyproject_toml["build-system"]
|
132 |
+
|
133 |
+
if "requires" not in build_system_toml.keys():
|
134 |
+
logger.warning(
|
135 |
+
"There is no `requires` section in the pyproject.toml of the repository"
|
136 |
+
" that contains the fastai `Learner`. The `requires` would allow us to"
|
137 |
+
" verify that your fastai and fastcore versions are compatible with those"
|
138 |
+
" of the model you want to load."
|
139 |
+
)
|
140 |
+
return
|
141 |
+
package_versions = build_system_toml["requires"]
|
142 |
+
|
143 |
+
# Extracts contains fastai and fastcore versions from `pyproject.toml` if available.
|
144 |
+
# If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest.
|
145 |
+
fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")]
|
146 |
+
if len(fastai_packages) == 0:
|
147 |
+
logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.")
|
148 |
+
# fastai_version is an empty string if not specified
|
149 |
+
else:
|
150 |
+
fastai_version = str(fastai_packages[0]).partition("=")[2]
|
151 |
+
if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version):
|
152 |
+
raise ImportError(
|
153 |
+
"`from_pretrained_fastai` requires"
|
154 |
+
f" fastai>={fastai_min_version} version but the model to load uses"
|
155 |
+
f" {fastai_version} which is incompatible."
|
156 |
+
)
|
157 |
+
|
158 |
+
fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")]
|
159 |
+
if len(fastcore_packages) == 0:
|
160 |
+
logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.")
|
161 |
+
# fastcore_version is an empty string if not specified
|
162 |
+
else:
|
163 |
+
fastcore_version = str(fastcore_packages[0]).partition("=")[2]
|
164 |
+
if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version):
|
165 |
+
raise ImportError(
|
166 |
+
"`from_pretrained_fastai` requires"
|
167 |
+
f" fastcore>={fastcore_min_version} version, but you are using fastcore"
|
168 |
+
f" version {fastcore_version} which is incompatible."
|
169 |
+
)
|
170 |
+
|
171 |
+
|
172 |
+
README_TEMPLATE = """---
|
173 |
+
tags:
|
174 |
+
- fastai
|
175 |
+
---
|
176 |
+
|
177 |
+
# Amazing!
|
178 |
+
|
179 |
+
🥳 Congratulations on hosting your fastai model on the Hugging Face Hub!
|
180 |
+
|
181 |
+
# Some next steps
|
182 |
+
1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))!
|
183 |
+
|
184 |
+
2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)).
|
185 |
+
|
186 |
+
3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)!
|
187 |
+
|
188 |
+
Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card.
|
189 |
+
|
190 |
+
|
191 |
+
---
|
192 |
+
|
193 |
+
|
194 |
+
# Model card
|
195 |
+
|
196 |
+
## Model description
|
197 |
+
More information needed
|
198 |
+
|
199 |
+
## Intended uses & limitations
|
200 |
+
More information needed
|
201 |
+
|
202 |
+
## Training and evaluation data
|
203 |
+
More information needed
|
204 |
+
"""
|
205 |
+
|
206 |
+
PYPROJECT_TEMPLATE = f"""[build-system]
|
207 |
+
requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]
|
208 |
+
build-backend = "setuptools.build_meta:__legacy__"
|
209 |
+
"""
|
210 |
+
|
211 |
+
|
212 |
+
def _create_model_card(repo_dir: Path):
|
213 |
+
"""
|
214 |
+
Creates a model card for the repository.
|
215 |
+
|
216 |
+
Args:
|
217 |
+
repo_dir (`Path`):
|
218 |
+
Directory where model card is created.
|
219 |
+
"""
|
220 |
+
readme_path = repo_dir / "README.md"
|
221 |
+
|
222 |
+
if not readme_path.exists():
|
223 |
+
with readme_path.open("w", encoding="utf-8") as f:
|
224 |
+
f.write(README_TEMPLATE)
|
225 |
+
|
226 |
+
|
227 |
+
def _create_model_pyproject(repo_dir: Path):
|
228 |
+
"""
|
229 |
+
Creates a `pyproject.toml` for the repository.
|
230 |
+
|
231 |
+
Args:
|
232 |
+
repo_dir (`Path`):
|
233 |
+
Directory where `pyproject.toml` is created.
|
234 |
+
"""
|
235 |
+
pyproject_path = repo_dir / "pyproject.toml"
|
236 |
+
|
237 |
+
if not pyproject_path.exists():
|
238 |
+
with pyproject_path.open("w", encoding="utf-8") as f:
|
239 |
+
f.write(PYPROJECT_TEMPLATE)
|
240 |
+
|
241 |
+
|
242 |
+
def _save_pretrained_fastai(
|
243 |
+
learner,
|
244 |
+
save_directory: Union[str, Path],
|
245 |
+
config: Optional[Dict[str, Any]] = None,
|
246 |
+
):
|
247 |
+
"""
|
248 |
+
Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used.
|
249 |
+
|
250 |
+
Args:
|
251 |
+
learner (`Learner`):
|
252 |
+
The `fastai.Learner` you'd like to save.
|
253 |
+
save_directory (`str` or `Path`):
|
254 |
+
Specific directory in which you want to save the fastai learner.
|
255 |
+
config (`dict`, *optional*):
|
256 |
+
Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'.
|
257 |
+
|
258 |
+
<Tip>
|
259 |
+
|
260 |
+
Raises the following error:
|
261 |
+
|
262 |
+
- [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError)
|
263 |
+
if the config file provided is not a dictionary.
|
264 |
+
|
265 |
+
</Tip>
|
266 |
+
"""
|
267 |
+
_check_fastai_fastcore_versions()
|
268 |
+
|
269 |
+
os.makedirs(save_directory, exist_ok=True)
|
270 |
+
|
271 |
+
# if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE.
|
272 |
+
if config is not None:
|
273 |
+
if not isinstance(config, dict):
|
274 |
+
raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'")
|
275 |
+
path = os.path.join(save_directory, CONFIG_NAME)
|
276 |
+
with open(path, "w") as f:
|
277 |
+
json.dump(config, f)
|
278 |
+
|
279 |
+
_create_model_card(Path(save_directory))
|
280 |
+
_create_model_pyproject(Path(save_directory))
|
281 |
+
|
282 |
+
# learner.export saves the model in `self.path`.
|
283 |
+
learner.path = Path(save_directory)
|
284 |
+
os.makedirs(save_directory, exist_ok=True)
|
285 |
+
try:
|
286 |
+
learner.export(
|
287 |
+
fname="model.pkl",
|
288 |
+
pickle_protocol=DEFAULT_PROTOCOL,
|
289 |
+
)
|
290 |
+
except PicklingError:
|
291 |
+
raise PicklingError(
|
292 |
+
"You are using a lambda function, i.e., an anonymous function. `pickle`"
|
293 |
+
" cannot pickle function objects and requires that all functions have"
|
294 |
+
" names. One possible solution is to name the function."
|
295 |
+
)
|
296 |
+
|
297 |
+
|
298 |
+
@validate_hf_hub_args
|
299 |
+
def from_pretrained_fastai(
|
300 |
+
repo_id: str,
|
301 |
+
revision: Optional[str] = None,
|
302 |
+
):
|
303 |
+
"""
|
304 |
+
Load pretrained fastai model from the Hub or from a local directory.
|
305 |
+
|
306 |
+
Args:
|
307 |
+
repo_id (`str`):
|
308 |
+
The location where the pickled fastai.Learner is. It can be either of the two:
|
309 |
+
- Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'.
|
310 |
+
You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`.
|
311 |
+
Revision is the specific model version to use. Since we use a git-based system for storing models and other
|
312 |
+
artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id.
|
313 |
+
- Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml
|
314 |
+
indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`.
|
315 |
+
revision (`str`, *optional*):
|
316 |
+
Revision at which the repo's files are downloaded. See documentation of `snapshot_download`.
|
317 |
+
|
318 |
+
Returns:
|
319 |
+
The `fastai.Learner` model in the `repo_id` repo.
|
320 |
+
"""
|
321 |
+
_check_fastai_fastcore_versions()
|
322 |
+
|
323 |
+
# Load the `repo_id` repo.
|
324 |
+
# `snapshot_download` returns the folder where the model was stored.
|
325 |
+
# `cache_dir` will be the default '/root/.cache/huggingface/hub'
|
326 |
+
if not os.path.isdir(repo_id):
|
327 |
+
storage_folder = snapshot_download(
|
328 |
+
repo_id=repo_id,
|
329 |
+
revision=revision,
|
330 |
+
library_name="fastai",
|
331 |
+
library_version=get_fastai_version(),
|
332 |
+
)
|
333 |
+
else:
|
334 |
+
storage_folder = repo_id
|
335 |
+
|
336 |
+
_check_fastai_fastcore_pyproject_versions(storage_folder)
|
337 |
+
|
338 |
+
from fastai.learner import load_learner # type: ignore
|
339 |
+
|
340 |
+
return load_learner(os.path.join(storage_folder, "model.pkl"))
|
341 |
+
|
342 |
+
|
343 |
+
@validate_hf_hub_args
|
344 |
+
def push_to_hub_fastai(
|
345 |
+
learner,
|
346 |
+
*,
|
347 |
+
repo_id: str,
|
348 |
+
commit_message: str = "Push FastAI model using huggingface_hub.",
|
349 |
+
private: bool = False,
|
350 |
+
token: Optional[str] = None,
|
351 |
+
config: Optional[dict] = None,
|
352 |
+
branch: Optional[str] = None,
|
353 |
+
create_pr: Optional[bool] = None,
|
354 |
+
allow_patterns: Optional[Union[List[str], str]] = None,
|
355 |
+
ignore_patterns: Optional[Union[List[str], str]] = None,
|
356 |
+
delete_patterns: Optional[Union[List[str], str]] = None,
|
357 |
+
api_endpoint: Optional[str] = None,
|
358 |
+
):
|
359 |
+
"""
|
360 |
+
Upload learner checkpoint files to the Hub.
|
361 |
+
|
362 |
+
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
|
363 |
+
`delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
|
364 |
+
details.
|
365 |
+
|
366 |
+
Args:
|
367 |
+
learner (`Learner`):
|
368 |
+
The `fastai.Learner' you'd like to push to the Hub.
|
369 |
+
repo_id (`str`):
|
370 |
+
The repository id for your model in Hub in the format of "namespace/repo_name". The namespace can be your individual account or an organization to which you have write access (for example, 'stanfordnlp/stanza-de').
|
371 |
+
commit_message (`str`, *optional*):
|
372 |
+
Message to commit while pushing. Will default to :obj:`"add model"`.
|
373 |
+
private (`bool`, *optional*, defaults to `False`):
|
374 |
+
Whether or not the repository created should be private.
|
375 |
+
token (`str`, *optional*):
|
376 |
+
The Hugging Face account token to use as HTTP bearer authorization for remote files. If :obj:`None`, the token will be asked by a prompt.
|
377 |
+
config (`dict`, *optional*):
|
378 |
+
Configuration object to be saved alongside the model weights.
|
379 |
+
branch (`str`, *optional*):
|
380 |
+
The git branch on which to push the model. This defaults to
|
381 |
+
the default branch as specified in your repository, which
|
382 |
+
defaults to `"main"`.
|
383 |
+
create_pr (`boolean`, *optional*):
|
384 |
+
Whether or not to create a Pull Request from `branch` with that commit.
|
385 |
+
Defaults to `False`.
|
386 |
+
api_endpoint (`str`, *optional*):
|
387 |
+
The API endpoint to use when pushing the model to the hub.
|
388 |
+
allow_patterns (`List[str]` or `str`, *optional*):
|
389 |
+
If provided, only files matching at least one pattern are pushed.
|
390 |
+
ignore_patterns (`List[str]` or `str`, *optional*):
|
391 |
+
If provided, files matching any of the patterns are not pushed.
|
392 |
+
delete_patterns (`List[str]` or `str`, *optional*):
|
393 |
+
If provided, remote files matching any of the patterns will be deleted from the repo.
|
394 |
+
|
395 |
+
Returns:
|
396 |
+
The url of the commit of your model in the given repository.
|
397 |
+
|
398 |
+
<Tip>
|
399 |
+
|
400 |
+
Raises the following error:
|
401 |
+
|
402 |
+
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
403 |
+
if the user is not log on to the Hugging Face Hub.
|
404 |
+
|
405 |
+
</Tip>
|
406 |
+
"""
|
407 |
+
_check_fastai_fastcore_versions()
|
408 |
+
api = HfApi(endpoint=api_endpoint)
|
409 |
+
repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
|
410 |
+
|
411 |
+
# Push the files to the repo in a single commit
|
412 |
+
with SoftTemporaryDirectory() as tmp:
|
413 |
+
saved_path = Path(tmp) / repo_id
|
414 |
+
_save_pretrained_fastai(learner, saved_path, config=config)
|
415 |
+
return api.upload_folder(
|
416 |
+
repo_id=repo_id,
|
417 |
+
token=token,
|
418 |
+
folder_path=saved_path,
|
419 |
+
commit_message=commit_message,
|
420 |
+
revision=branch,
|
421 |
+
create_pr=create_pr,
|
422 |
+
allow_patterns=allow_patterns,
|
423 |
+
ignore_patterns=ignore_patterns,
|
424 |
+
delete_patterns=delete_patterns,
|
425 |
+
)
|
venv/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
|
venv/lib/python3.10/site-packages/huggingface_hub/hf_api.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/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)
|
venv/lib/python3.10/site-packages/huggingface_hub/hub_mixin.py
ADDED
@@ -0,0 +1,704 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
from dataclasses import asdict, dataclass, is_dataclass
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, TypeVar, Union, get_args
|
7 |
+
|
8 |
+
from .constants import CONFIG_NAME, PYTORCH_WEIGHTS_NAME, SAFETENSORS_SINGLE_FILE
|
9 |
+
from .file_download import hf_hub_download
|
10 |
+
from .hf_api import HfApi
|
11 |
+
from .repocard import ModelCard, ModelCardData
|
12 |
+
from .utils import (
|
13 |
+
EntryNotFoundError,
|
14 |
+
HfHubHTTPError,
|
15 |
+
SoftTemporaryDirectory,
|
16 |
+
is_jsonable,
|
17 |
+
is_safetensors_available,
|
18 |
+
is_torch_available,
|
19 |
+
logging,
|
20 |
+
validate_hf_hub_args,
|
21 |
+
)
|
22 |
+
from .utils._deprecation import _deprecate_arguments
|
23 |
+
|
24 |
+
|
25 |
+
if TYPE_CHECKING:
|
26 |
+
from _typeshed import DataclassInstance
|
27 |
+
|
28 |
+
if is_torch_available():
|
29 |
+
import torch # type: ignore
|
30 |
+
|
31 |
+
if is_safetensors_available():
|
32 |
+
from safetensors.torch import load_model as load_model_as_safetensor
|
33 |
+
from safetensors.torch import save_model as save_model_as_safetensor
|
34 |
+
|
35 |
+
|
36 |
+
logger = logging.get_logger(__name__)
|
37 |
+
|
38 |
+
# Generic variable that is either ModelHubMixin or a subclass thereof
|
39 |
+
T = TypeVar("T", bound="ModelHubMixin")
|
40 |
+
|
41 |
+
DEFAULT_MODEL_CARD = """
|
42 |
+
---
|
43 |
+
# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
|
44 |
+
# Doc / guide: https://huggingface.co/docs/hub/model-cards
|
45 |
+
{{ card_data }}
|
46 |
+
---
|
47 |
+
|
48 |
+
This model has been pushed to the Hub using **{{ library_name }}**:
|
49 |
+
- Repo: {{ repo_url | default("[More Information Needed]", true) }}
|
50 |
+
- Docs: {{ docs_url | default("[More Information Needed]", true) }}
|
51 |
+
"""
|
52 |
+
|
53 |
+
|
54 |
+
@dataclass
|
55 |
+
class MixinInfo:
|
56 |
+
library_name: Optional[str] = None
|
57 |
+
tags: Optional[List[str]] = None
|
58 |
+
repo_url: Optional[str] = None
|
59 |
+
docs_url: Optional[str] = None
|
60 |
+
|
61 |
+
|
62 |
+
class ModelHubMixin:
|
63 |
+
"""
|
64 |
+
A generic mixin to integrate ANY machine learning framework with the Hub.
|
65 |
+
|
66 |
+
To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models
|
67 |
+
have to be overwritten in [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelHubMixin`] is a good example
|
68 |
+
of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions.
|
69 |
+
|
70 |
+
When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to
|
71 |
+
`__init__` but to the class definition itself. This is useful to define metadata about the library integrating
|
72 |
+
[`ModelHubMixin`].
|
73 |
+
|
74 |
+
Args:
|
75 |
+
library_name (`str`, *optional*):
|
76 |
+
Name of the library integrating ModelHubMixin. Used to generate model card.
|
77 |
+
tags (`List[str]`, *optional*):
|
78 |
+
Tags to be added to the model card. Used to generate model card.
|
79 |
+
repo_url (`str`, *optional*):
|
80 |
+
URL of the library repository. Used to generate model card.
|
81 |
+
docs_url (`str`, *optional*):
|
82 |
+
URL of the library documentation. Used to generate model card.
|
83 |
+
|
84 |
+
Example:
|
85 |
+
|
86 |
+
```python
|
87 |
+
>>> from huggingface_hub import ModelHubMixin
|
88 |
+
|
89 |
+
# Inherit from ModelHubMixin
|
90 |
+
>>> class MyCustomModel(
|
91 |
+
... ModelHubMixin,
|
92 |
+
... library_name="my-library",
|
93 |
+
... tags=["x-custom-tag"],
|
94 |
+
... repo_url="https://github.com/huggingface/my-cool-library",
|
95 |
+
... docs_url="https://huggingface.co/docs/my-cool-library",
|
96 |
+
... # ^ optional metadata to generate model card
|
97 |
+
... ):
|
98 |
+
... def __init__(self, size: int = 512, device: str = "cpu"):
|
99 |
+
... # define how to initialize your model
|
100 |
+
... super().__init__()
|
101 |
+
... ...
|
102 |
+
...
|
103 |
+
... def _save_pretrained(self, save_directory: Path) -> None:
|
104 |
+
... # define how to serialize your model
|
105 |
+
... ...
|
106 |
+
...
|
107 |
+
... @classmethod
|
108 |
+
... def from_pretrained(
|
109 |
+
... cls: Type[T],
|
110 |
+
... pretrained_model_name_or_path: Union[str, Path],
|
111 |
+
... *,
|
112 |
+
... force_download: bool = False,
|
113 |
+
... resume_download: bool = False,
|
114 |
+
... proxies: Optional[Dict] = None,
|
115 |
+
... token: Optional[Union[str, bool]] = None,
|
116 |
+
... cache_dir: Optional[Union[str, Path]] = None,
|
117 |
+
... local_files_only: bool = False,
|
118 |
+
... revision: Optional[str] = None,
|
119 |
+
... **model_kwargs,
|
120 |
+
... ) -> T:
|
121 |
+
... # define how to deserialize your model
|
122 |
+
... ...
|
123 |
+
|
124 |
+
>>> model = MyCustomModel(size=256, device="gpu")
|
125 |
+
|
126 |
+
# Save model weights to local directory
|
127 |
+
>>> model.save_pretrained("my-awesome-model")
|
128 |
+
|
129 |
+
# Push model weights to the Hub
|
130 |
+
>>> model.push_to_hub("my-awesome-model")
|
131 |
+
|
132 |
+
# Download and initialize weights from the Hub
|
133 |
+
>>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model")
|
134 |
+
>>> reloaded_model._hub_mixin_config
|
135 |
+
{"size": 256, "device": "gpu"}
|
136 |
+
|
137 |
+
# Model card has been correctly populated
|
138 |
+
>>> from huggingface_hub import ModelCard
|
139 |
+
>>> card = ModelCard.load("username/my-awesome-model")
|
140 |
+
>>> card.data.tags
|
141 |
+
["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"]
|
142 |
+
>>> card.data.library_name
|
143 |
+
"my-library"
|
144 |
+
```
|
145 |
+
"""
|
146 |
+
|
147 |
+
_hub_mixin_config: Optional[Union[dict, "DataclassInstance"]] = None
|
148 |
+
# ^ optional config attribute automatically set in `from_pretrained`
|
149 |
+
_hub_mixin_info: MixinInfo
|
150 |
+
# ^ information about the library integrating ModelHubMixin (used to generate model card)
|
151 |
+
_hub_mixin_init_parameters: Dict[str, inspect.Parameter]
|
152 |
+
_hub_mixin_jsonable_default_values: Dict[str, Any]
|
153 |
+
_hub_mixin_inject_config: bool
|
154 |
+
# ^ internal values to handle config
|
155 |
+
|
156 |
+
def __init_subclass__(
|
157 |
+
cls,
|
158 |
+
*,
|
159 |
+
library_name: Optional[str] = None,
|
160 |
+
tags: Optional[List[str]] = None,
|
161 |
+
repo_url: Optional[str] = None,
|
162 |
+
docs_url: Optional[str] = None,
|
163 |
+
) -> None:
|
164 |
+
"""Inspect __init__ signature only once when subclassing + handle modelcard."""
|
165 |
+
super().__init_subclass__()
|
166 |
+
|
167 |
+
# Will be reused when creating modelcard
|
168 |
+
tags = tags or []
|
169 |
+
tags.append("model_hub_mixin")
|
170 |
+
cls._hub_mixin_info = MixinInfo(
|
171 |
+
library_name=library_name,
|
172 |
+
tags=tags,
|
173 |
+
repo_url=repo_url,
|
174 |
+
docs_url=docs_url,
|
175 |
+
)
|
176 |
+
|
177 |
+
# Inspect __init__ signature to handle config
|
178 |
+
cls._hub_mixin_init_parameters = dict(inspect.signature(cls.__init__).parameters)
|
179 |
+
cls._hub_mixin_jsonable_default_values = {
|
180 |
+
param.name: param.default
|
181 |
+
for param in cls._hub_mixin_init_parameters.values()
|
182 |
+
if param.default is not inspect.Parameter.empty and is_jsonable(param.default)
|
183 |
+
}
|
184 |
+
cls._hub_mixin_inject_config = "config" in inspect.signature(cls._from_pretrained).parameters
|
185 |
+
|
186 |
+
def __new__(cls, *args, **kwargs) -> "ModelHubMixin":
|
187 |
+
"""Create a new instance of the class and handle config.
|
188 |
+
|
189 |
+
3 cases:
|
190 |
+
- If `self._hub_mixin_config` is already set, do nothing.
|
191 |
+
- If `config` is passed as a dataclass, set it as `self._hub_mixin_config`.
|
192 |
+
- Otherwise, build `self._hub_mixin_config` from default values and passed values.
|
193 |
+
"""
|
194 |
+
instance = super().__new__(cls)
|
195 |
+
|
196 |
+
# If `config` is already set, return early
|
197 |
+
if instance._hub_mixin_config is not None:
|
198 |
+
return instance
|
199 |
+
|
200 |
+
# Infer passed values
|
201 |
+
passed_values = {
|
202 |
+
**{
|
203 |
+
key: value
|
204 |
+
for key, value in zip(
|
205 |
+
# [1:] to skip `self` parameter
|
206 |
+
list(cls._hub_mixin_init_parameters)[1:],
|
207 |
+
args,
|
208 |
+
)
|
209 |
+
},
|
210 |
+
**kwargs,
|
211 |
+
}
|
212 |
+
|
213 |
+
# If config passed as dataclass => set it and return early
|
214 |
+
if is_dataclass(passed_values.get("config")):
|
215 |
+
instance._hub_mixin_config = passed_values["config"]
|
216 |
+
return instance
|
217 |
+
|
218 |
+
# Otherwise, build config from default + passed values
|
219 |
+
init_config = {
|
220 |
+
# default values
|
221 |
+
**cls._hub_mixin_jsonable_default_values,
|
222 |
+
# passed values
|
223 |
+
**{key: value for key, value in passed_values.items() if is_jsonable(value)},
|
224 |
+
}
|
225 |
+
init_config.pop("config", {})
|
226 |
+
|
227 |
+
# Populate `init_config` with provided config
|
228 |
+
provided_config = passed_values.get("config")
|
229 |
+
if isinstance(provided_config, dict):
|
230 |
+
init_config.update(provided_config)
|
231 |
+
|
232 |
+
# Set `config` attribute and return
|
233 |
+
if init_config != {}:
|
234 |
+
instance._hub_mixin_config = init_config
|
235 |
+
return instance
|
236 |
+
|
237 |
+
def save_pretrained(
|
238 |
+
self,
|
239 |
+
save_directory: Union[str, Path],
|
240 |
+
*,
|
241 |
+
config: Optional[Union[dict, "DataclassInstance"]] = None,
|
242 |
+
repo_id: Optional[str] = None,
|
243 |
+
push_to_hub: bool = False,
|
244 |
+
**push_to_hub_kwargs,
|
245 |
+
) -> Optional[str]:
|
246 |
+
"""
|
247 |
+
Save weights in local directory.
|
248 |
+
|
249 |
+
Args:
|
250 |
+
save_directory (`str` or `Path`):
|
251 |
+
Path to directory in which the model weights and configuration will be saved.
|
252 |
+
config (`dict` or `DataclassInstance`, *optional*):
|
253 |
+
Model configuration specified as a key/value dictionary or a dataclass instance.
|
254 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
255 |
+
Whether or not to push your model to the Huggingface Hub after saving it.
|
256 |
+
repo_id (`str`, *optional*):
|
257 |
+
ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
|
258 |
+
not provided.
|
259 |
+
kwargs:
|
260 |
+
Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method.
|
261 |
+
"""
|
262 |
+
save_directory = Path(save_directory)
|
263 |
+
save_directory.mkdir(parents=True, exist_ok=True)
|
264 |
+
|
265 |
+
# Remove config.json if already exists. After `_save_pretrained` we don't want to overwrite config.json
|
266 |
+
# as it might have been saved by the custom `_save_pretrained` already. However we do want to overwrite
|
267 |
+
# an existing config.json if it was not saved by `_save_pretrained`.
|
268 |
+
config_path = save_directory / CONFIG_NAME
|
269 |
+
config_path.unlink(missing_ok=True)
|
270 |
+
|
271 |
+
# save model weights/files (framework-specific)
|
272 |
+
self._save_pretrained(save_directory)
|
273 |
+
|
274 |
+
# save config (if provided and if not serialized yet in `_save_pretrained`)
|
275 |
+
if config is None:
|
276 |
+
config = self._hub_mixin_config
|
277 |
+
if config is not None:
|
278 |
+
if is_dataclass(config):
|
279 |
+
config = asdict(config) # type: ignore[arg-type]
|
280 |
+
if not config_path.exists():
|
281 |
+
config_str = json.dumps(config, sort_keys=True, indent=2)
|
282 |
+
config_path.write_text(config_str)
|
283 |
+
|
284 |
+
# save model card
|
285 |
+
model_card_path = save_directory / "README.md"
|
286 |
+
if not model_card_path.exists(): # do not overwrite if already exists
|
287 |
+
self.generate_model_card().save(save_directory / "README.md")
|
288 |
+
|
289 |
+
# push to the Hub if required
|
290 |
+
if push_to_hub:
|
291 |
+
kwargs = push_to_hub_kwargs.copy() # soft-copy to avoid mutating input
|
292 |
+
if config is not None: # kwarg for `push_to_hub`
|
293 |
+
kwargs["config"] = config
|
294 |
+
if repo_id is None:
|
295 |
+
repo_id = save_directory.name # Defaults to `save_directory` name
|
296 |
+
return self.push_to_hub(repo_id=repo_id, **kwargs)
|
297 |
+
return None
|
298 |
+
|
299 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
300 |
+
"""
|
301 |
+
Overwrite this method in subclass to define how to save your model.
|
302 |
+
Check out our [integration guide](../guides/integrations) for instructions.
|
303 |
+
|
304 |
+
Args:
|
305 |
+
save_directory (`str` or `Path`):
|
306 |
+
Path to directory in which the model weights and configuration will be saved.
|
307 |
+
"""
|
308 |
+
raise NotImplementedError
|
309 |
+
|
310 |
+
@classmethod
|
311 |
+
@validate_hf_hub_args
|
312 |
+
def from_pretrained(
|
313 |
+
cls: Type[T],
|
314 |
+
pretrained_model_name_or_path: Union[str, Path],
|
315 |
+
*,
|
316 |
+
force_download: bool = False,
|
317 |
+
resume_download: bool = False,
|
318 |
+
proxies: Optional[Dict] = None,
|
319 |
+
token: Optional[Union[str, bool]] = None,
|
320 |
+
cache_dir: Optional[Union[str, Path]] = None,
|
321 |
+
local_files_only: bool = False,
|
322 |
+
revision: Optional[str] = None,
|
323 |
+
**model_kwargs,
|
324 |
+
) -> T:
|
325 |
+
"""
|
326 |
+
Download a model from the Huggingface Hub and instantiate it.
|
327 |
+
|
328 |
+
Args:
|
329 |
+
pretrained_model_name_or_path (`str`, `Path`):
|
330 |
+
- Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`.
|
331 |
+
- Or a path to a `directory` containing model weights saved using
|
332 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `../path/to/my_model_directory/`.
|
333 |
+
revision (`str`, *optional*):
|
334 |
+
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id.
|
335 |
+
Defaults to the latest commit on `main` branch.
|
336 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
337 |
+
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
|
338 |
+
the existing cache.
|
339 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
340 |
+
Whether to delete incompletely received files. Will attempt to resume the download if such a file exists.
|
341 |
+
proxies (`Dict[str, str]`, *optional*):
|
342 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
343 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on every request.
|
344 |
+
token (`str` or `bool`, *optional*):
|
345 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
346 |
+
cached when running `huggingface-cli login`.
|
347 |
+
cache_dir (`str`, `Path`, *optional*):
|
348 |
+
Path to the folder where cached files are stored.
|
349 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
350 |
+
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
|
351 |
+
model_kwargs (`Dict`, *optional*):
|
352 |
+
Additional kwargs to pass to the model during initialization.
|
353 |
+
"""
|
354 |
+
model_id = str(pretrained_model_name_or_path)
|
355 |
+
config_file: Optional[str] = None
|
356 |
+
if os.path.isdir(model_id):
|
357 |
+
if CONFIG_NAME in os.listdir(model_id):
|
358 |
+
config_file = os.path.join(model_id, CONFIG_NAME)
|
359 |
+
else:
|
360 |
+
logger.warning(f"{CONFIG_NAME} not found in {Path(model_id).resolve()}")
|
361 |
+
else:
|
362 |
+
try:
|
363 |
+
config_file = hf_hub_download(
|
364 |
+
repo_id=model_id,
|
365 |
+
filename=CONFIG_NAME,
|
366 |
+
revision=revision,
|
367 |
+
cache_dir=cache_dir,
|
368 |
+
force_download=force_download,
|
369 |
+
proxies=proxies,
|
370 |
+
resume_download=resume_download,
|
371 |
+
token=token,
|
372 |
+
local_files_only=local_files_only,
|
373 |
+
)
|
374 |
+
except HfHubHTTPError as e:
|
375 |
+
logger.info(f"{CONFIG_NAME} not found on the HuggingFace Hub: {str(e)}")
|
376 |
+
|
377 |
+
# Read config
|
378 |
+
config = None
|
379 |
+
if config_file is not None:
|
380 |
+
with open(config_file, "r", encoding="utf-8") as f:
|
381 |
+
config = json.load(f)
|
382 |
+
|
383 |
+
# Populate model_kwargs from config
|
384 |
+
for param in cls._hub_mixin_init_parameters.values():
|
385 |
+
if param.name not in model_kwargs and param.name in config:
|
386 |
+
model_kwargs[param.name] = config[param.name]
|
387 |
+
|
388 |
+
# Check if `config` argument was passed at init
|
389 |
+
if "config" in cls._hub_mixin_init_parameters:
|
390 |
+
# Check if `config` argument is a dataclass
|
391 |
+
config_annotation = cls._hub_mixin_init_parameters["config"].annotation
|
392 |
+
if config_annotation is inspect.Parameter.empty:
|
393 |
+
pass # no annotation
|
394 |
+
elif is_dataclass(config_annotation):
|
395 |
+
config = _load_dataclass(config_annotation, config)
|
396 |
+
else:
|
397 |
+
# if Optional/Union annotation => check if a dataclass is in the Union
|
398 |
+
for _sub_annotation in get_args(config_annotation):
|
399 |
+
if is_dataclass(_sub_annotation):
|
400 |
+
config = _load_dataclass(_sub_annotation, config)
|
401 |
+
break
|
402 |
+
|
403 |
+
# Forward config to model initialization
|
404 |
+
model_kwargs["config"] = config
|
405 |
+
|
406 |
+
# Inject config if `**kwargs` are expected
|
407 |
+
if is_dataclass(cls):
|
408 |
+
for key in cls.__dataclass_fields__:
|
409 |
+
if key not in model_kwargs and key in config:
|
410 |
+
model_kwargs[key] = config[key]
|
411 |
+
elif any(param.kind == inspect.Parameter.VAR_KEYWORD for param in cls._hub_mixin_init_parameters.values()):
|
412 |
+
for key, value in config.items():
|
413 |
+
if key not in model_kwargs:
|
414 |
+
model_kwargs[key] = value
|
415 |
+
|
416 |
+
# Finally, also inject if `_from_pretrained` expects it
|
417 |
+
if cls._hub_mixin_inject_config:
|
418 |
+
model_kwargs["config"] = config
|
419 |
+
|
420 |
+
instance = cls._from_pretrained(
|
421 |
+
model_id=str(model_id),
|
422 |
+
revision=revision,
|
423 |
+
cache_dir=cache_dir,
|
424 |
+
force_download=force_download,
|
425 |
+
proxies=proxies,
|
426 |
+
resume_download=resume_download,
|
427 |
+
local_files_only=local_files_only,
|
428 |
+
token=token,
|
429 |
+
**model_kwargs,
|
430 |
+
)
|
431 |
+
|
432 |
+
# Implicitly set the config as instance attribute if not already set by the class
|
433 |
+
# This way `config` will be available when calling `save_pretrained` or `push_to_hub`.
|
434 |
+
if config is not None and (getattr(instance, "_hub_mixin_config", None) in (None, {})):
|
435 |
+
instance._hub_mixin_config = config
|
436 |
+
|
437 |
+
return instance
|
438 |
+
|
439 |
+
@classmethod
|
440 |
+
def _from_pretrained(
|
441 |
+
cls: Type[T],
|
442 |
+
*,
|
443 |
+
model_id: str,
|
444 |
+
revision: Optional[str],
|
445 |
+
cache_dir: Optional[Union[str, Path]],
|
446 |
+
force_download: bool,
|
447 |
+
proxies: Optional[Dict],
|
448 |
+
resume_download: bool,
|
449 |
+
local_files_only: bool,
|
450 |
+
token: Optional[Union[str, bool]],
|
451 |
+
**model_kwargs,
|
452 |
+
) -> T:
|
453 |
+
"""Overwrite this method in subclass to define how to load your model from pretrained.
|
454 |
+
|
455 |
+
Use [`hf_hub_download`] or [`snapshot_download`] to download files from the Hub before loading them. Most
|
456 |
+
args taken as input can be directly passed to those 2 methods. If needed, you can add more arguments to this
|
457 |
+
method using "model_kwargs". For example [`PyTorchModelHubMixin._from_pretrained`] takes as input a `map_location`
|
458 |
+
parameter to set on which device the model should be loaded.
|
459 |
+
|
460 |
+
Check out our [integration guide](../guides/integrations) for more instructions.
|
461 |
+
|
462 |
+
Args:
|
463 |
+
model_id (`str`):
|
464 |
+
ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
|
465 |
+
revision (`str`, *optional*):
|
466 |
+
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
|
467 |
+
latest commit on `main` branch.
|
468 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
469 |
+
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
|
470 |
+
the existing cache.
|
471 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
472 |
+
Whether to delete incompletely received files. Will attempt to resume the download if such a file exists.
|
473 |
+
proxies (`Dict[str, str]`, *optional*):
|
474 |
+
A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128',
|
475 |
+
'http://hostname': 'foo.bar:4012'}`).
|
476 |
+
token (`str` or `bool`, *optional*):
|
477 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
478 |
+
cached when running `huggingface-cli login`.
|
479 |
+
cache_dir (`str`, `Path`, *optional*):
|
480 |
+
Path to the folder where cached files are stored.
|
481 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
482 |
+
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
|
483 |
+
model_kwargs:
|
484 |
+
Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
|
485 |
+
"""
|
486 |
+
raise NotImplementedError
|
487 |
+
|
488 |
+
@_deprecate_arguments(
|
489 |
+
version="0.23.0",
|
490 |
+
deprecated_args=["api_endpoint"],
|
491 |
+
custom_message="Use `HF_ENDPOINT` environment variable instead.",
|
492 |
+
)
|
493 |
+
@validate_hf_hub_args
|
494 |
+
def push_to_hub(
|
495 |
+
self,
|
496 |
+
repo_id: str,
|
497 |
+
*,
|
498 |
+
config: Optional[Union[dict, "DataclassInstance"]] = None,
|
499 |
+
commit_message: str = "Push model using huggingface_hub.",
|
500 |
+
private: bool = False,
|
501 |
+
token: Optional[str] = None,
|
502 |
+
branch: Optional[str] = None,
|
503 |
+
create_pr: Optional[bool] = None,
|
504 |
+
allow_patterns: Optional[Union[List[str], str]] = None,
|
505 |
+
ignore_patterns: Optional[Union[List[str], str]] = None,
|
506 |
+
delete_patterns: Optional[Union[List[str], str]] = None,
|
507 |
+
# TODO: remove once deprecated
|
508 |
+
api_endpoint: Optional[str] = None,
|
509 |
+
) -> str:
|
510 |
+
"""
|
511 |
+
Upload model checkpoint to the Hub.
|
512 |
+
|
513 |
+
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
|
514 |
+
`delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
|
515 |
+
details.
|
516 |
+
|
517 |
+
Args:
|
518 |
+
repo_id (`str`):
|
519 |
+
ID of the repository to push to (example: `"username/my-model"`).
|
520 |
+
config (`dict` or `DataclassInstance`, *optional*):
|
521 |
+
Model configuration specified as a key/value dictionary or a dataclass instance.
|
522 |
+
commit_message (`str`, *optional*):
|
523 |
+
Message to commit while pushing.
|
524 |
+
private (`bool`, *optional*, defaults to `False`):
|
525 |
+
Whether the repository created should be private.
|
526 |
+
api_endpoint (`str`, *optional*):
|
527 |
+
The API endpoint to use when pushing the model to the hub.
|
528 |
+
token (`str`, *optional*):
|
529 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
530 |
+
cached when running `huggingface-cli login`.
|
531 |
+
branch (`str`, *optional*):
|
532 |
+
The git branch on which to push the model. This defaults to `"main"`.
|
533 |
+
create_pr (`boolean`, *optional*):
|
534 |
+
Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`.
|
535 |
+
allow_patterns (`List[str]` or `str`, *optional*):
|
536 |
+
If provided, only files matching at least one pattern are pushed.
|
537 |
+
ignore_patterns (`List[str]` or `str`, *optional*):
|
538 |
+
If provided, files matching any of the patterns are not pushed.
|
539 |
+
delete_patterns (`List[str]` or `str`, *optional*):
|
540 |
+
If provided, remote files matching any of the patterns will be deleted from the repo.
|
541 |
+
|
542 |
+
Returns:
|
543 |
+
The url of the commit of your model in the given repository.
|
544 |
+
"""
|
545 |
+
api = HfApi(endpoint=api_endpoint, token=token)
|
546 |
+
repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id
|
547 |
+
|
548 |
+
# Push the files to the repo in a single commit
|
549 |
+
with SoftTemporaryDirectory() as tmp:
|
550 |
+
saved_path = Path(tmp) / repo_id
|
551 |
+
self.save_pretrained(saved_path, config=config)
|
552 |
+
return api.upload_folder(
|
553 |
+
repo_id=repo_id,
|
554 |
+
repo_type="model",
|
555 |
+
folder_path=saved_path,
|
556 |
+
commit_message=commit_message,
|
557 |
+
revision=branch,
|
558 |
+
create_pr=create_pr,
|
559 |
+
allow_patterns=allow_patterns,
|
560 |
+
ignore_patterns=ignore_patterns,
|
561 |
+
delete_patterns=delete_patterns,
|
562 |
+
)
|
563 |
+
|
564 |
+
def generate_model_card(self, *args, **kwargs) -> ModelCard:
|
565 |
+
card = ModelCard.from_template(
|
566 |
+
card_data=ModelCardData(**asdict(self._hub_mixin_info)),
|
567 |
+
template_str=DEFAULT_MODEL_CARD,
|
568 |
+
)
|
569 |
+
return card
|
570 |
+
|
571 |
+
|
572 |
+
class PyTorchModelHubMixin(ModelHubMixin):
|
573 |
+
"""
|
574 |
+
Implementation of [`ModelHubMixin`] to provide model Hub upload/download capabilities to PyTorch models. The model
|
575 |
+
is set in evaluation mode by default using `model.eval()` (dropout modules are deactivated). To train the model,
|
576 |
+
you should first set it back in training mode with `model.train()`.
|
577 |
+
|
578 |
+
Example:
|
579 |
+
|
580 |
+
```python
|
581 |
+
>>> import torch
|
582 |
+
>>> import torch.nn as nn
|
583 |
+
>>> from huggingface_hub import PyTorchModelHubMixin
|
584 |
+
|
585 |
+
>>> class MyModel(
|
586 |
+
... nn.Module,
|
587 |
+
... PyTorchModelHubMixin,
|
588 |
+
... library_name="keras-nlp",
|
589 |
+
... repo_url="https://github.com/keras-team/keras-nlp",
|
590 |
+
... docs_url="https://keras.io/keras_nlp/",
|
591 |
+
... # ^ optional metadata to generate model card
|
592 |
+
... ):
|
593 |
+
... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
|
594 |
+
... super().__init__()
|
595 |
+
... self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
|
596 |
+
... self.linear = nn.Linear(output_size, vocab_size)
|
597 |
+
|
598 |
+
... def forward(self, x):
|
599 |
+
... return self.linear(x + self.param)
|
600 |
+
>>> model = MyModel(hidden_size=256)
|
601 |
+
|
602 |
+
# Save model weights to local directory
|
603 |
+
>>> model.save_pretrained("my-awesome-model")
|
604 |
+
|
605 |
+
# Push model weights to the Hub
|
606 |
+
>>> model.push_to_hub("my-awesome-model")
|
607 |
+
|
608 |
+
# Download and initialize weights from the Hub
|
609 |
+
>>> model = MyModel.from_pretrained("username/my-awesome-model")
|
610 |
+
>>> model.hidden_size
|
611 |
+
256
|
612 |
+
```
|
613 |
+
"""
|
614 |
+
|
615 |
+
def __init_subclass__(cls, *args, tags: Optional[List[str]] = None, **kwargs) -> None:
|
616 |
+
tags = tags or []
|
617 |
+
tags.append("pytorch_model_hub_mixin")
|
618 |
+
kwargs["tags"] = tags
|
619 |
+
return super().__init_subclass__(*args, **kwargs)
|
620 |
+
|
621 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
622 |
+
"""Save weights from a Pytorch model to a local directory."""
|
623 |
+
model_to_save = self.module if hasattr(self, "module") else self # type: ignore
|
624 |
+
save_model_as_safetensor(model_to_save, str(save_directory / SAFETENSORS_SINGLE_FILE))
|
625 |
+
|
626 |
+
@classmethod
|
627 |
+
def _from_pretrained(
|
628 |
+
cls,
|
629 |
+
*,
|
630 |
+
model_id: str,
|
631 |
+
revision: Optional[str],
|
632 |
+
cache_dir: Optional[Union[str, Path]],
|
633 |
+
force_download: bool,
|
634 |
+
proxies: Optional[Dict],
|
635 |
+
resume_download: bool,
|
636 |
+
local_files_only: bool,
|
637 |
+
token: Union[str, bool, None],
|
638 |
+
map_location: str = "cpu",
|
639 |
+
strict: bool = False,
|
640 |
+
**model_kwargs,
|
641 |
+
):
|
642 |
+
"""Load Pytorch pretrained weights and return the loaded model."""
|
643 |
+
model = cls(**model_kwargs)
|
644 |
+
if os.path.isdir(model_id):
|
645 |
+
print("Loading weights from local directory")
|
646 |
+
model_file = os.path.join(model_id, SAFETENSORS_SINGLE_FILE)
|
647 |
+
return cls._load_as_safetensor(model, model_file, map_location, strict)
|
648 |
+
else:
|
649 |
+
try:
|
650 |
+
model_file = hf_hub_download(
|
651 |
+
repo_id=model_id,
|
652 |
+
filename=SAFETENSORS_SINGLE_FILE,
|
653 |
+
revision=revision,
|
654 |
+
cache_dir=cache_dir,
|
655 |
+
force_download=force_download,
|
656 |
+
proxies=proxies,
|
657 |
+
resume_download=resume_download,
|
658 |
+
token=token,
|
659 |
+
local_files_only=local_files_only,
|
660 |
+
)
|
661 |
+
return cls._load_as_safetensor(model, model_file, map_location, strict)
|
662 |
+
except EntryNotFoundError:
|
663 |
+
model_file = hf_hub_download(
|
664 |
+
repo_id=model_id,
|
665 |
+
filename=PYTORCH_WEIGHTS_NAME,
|
666 |
+
revision=revision,
|
667 |
+
cache_dir=cache_dir,
|
668 |
+
force_download=force_download,
|
669 |
+
proxies=proxies,
|
670 |
+
resume_download=resume_download,
|
671 |
+
token=token,
|
672 |
+
local_files_only=local_files_only,
|
673 |
+
)
|
674 |
+
return cls._load_as_pickle(model, model_file, map_location, strict)
|
675 |
+
|
676 |
+
@classmethod
|
677 |
+
def _load_as_pickle(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
|
678 |
+
state_dict = torch.load(model_file, map_location=torch.device(map_location))
|
679 |
+
model.load_state_dict(state_dict, strict=strict) # type: ignore
|
680 |
+
model.eval() # type: ignore
|
681 |
+
return model
|
682 |
+
|
683 |
+
@classmethod
|
684 |
+
def _load_as_safetensor(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
|
685 |
+
load_model_as_safetensor(model, model_file, strict=strict) # type: ignore [arg-type]
|
686 |
+
if map_location != "cpu":
|
687 |
+
# TODO: remove this once https://github.com/huggingface/safetensors/pull/449 is merged.
|
688 |
+
logger.warning(
|
689 |
+
"Loading model weights on other devices than 'cpu' is not supported natively."
|
690 |
+
" This means that the model is loaded on 'cpu' first and then copied to the device."
|
691 |
+
" This leads to a slower loading time."
|
692 |
+
" Support for loading directly on other devices is planned to be added in future releases."
|
693 |
+
" See https://github.com/huggingface/huggingface_hub/pull/2086 for more details."
|
694 |
+
)
|
695 |
+
model.to(map_location) # type: ignore [attr-defined]
|
696 |
+
return model
|
697 |
+
|
698 |
+
|
699 |
+
def _load_dataclass(datacls: Type["DataclassInstance"], data: dict) -> "DataclassInstance":
|
700 |
+
"""Load a dataclass instance from a dictionary.
|
701 |
+
|
702 |
+
Fields not expected by the dataclass are ignored.
|
703 |
+
"""
|
704 |
+
return datacls(**{k: v for k, v in data.items() if k in datacls.__dataclass_fields__})
|