Add files using upload-large-folder tool
Browse files- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/METADATA +324 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/RECORD +181 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/WHEEL +5 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/entry_points.txt +7 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/top_level.txt +1 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/dataclasses.py +684 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/errors.py +473 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/fastai_utils.py +414 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/file_download.py +1936 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/hf_api.py +0 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/hf_file_system.py +1442 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/hub_mixin.py +834 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/lfs.py +395 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/py.typed +0 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/repocard.py +826 -0
- .cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/repocard_data.py +770 -0
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/filters/__init__.py +942 -0
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/formatters/__init__.py +157 -0
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/formatters/_mapping.py +23 -0
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/formatters/bbcode.py +108 -0
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: huggingface_hub
|
| 3 |
+
Version: 1.10.1
|
| 4 |
+
Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hub
|
| 5 |
+
Home-page: https://github.com/huggingface/huggingface_hub
|
| 6 |
+
Author: Hugging Face, Inc.
|
| 7 |
+
Author-email: julien@huggingface.co
|
| 8 |
+
License: Apache-2.0
|
| 9 |
+
Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-models
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: Intended Audience :: Education
|
| 12 |
+
Classifier: Intended Audience :: Science/Research
|
| 13 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 14 |
+
Classifier: Operating System :: OS Independent
|
| 15 |
+
Classifier: Programming Language :: Python :: 3
|
| 16 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 22 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 23 |
+
Requires-Python: >=3.10.0
|
| 24 |
+
Description-Content-Type: text/markdown
|
| 25 |
+
License-File: LICENSE
|
| 26 |
+
Requires-Dist: filelock>=3.10.0
|
| 27 |
+
Requires-Dist: fsspec>=2023.5.0
|
| 28 |
+
Requires-Dist: hf-xet<2.0.0,>=1.4.3; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64"
|
| 29 |
+
Requires-Dist: httpx<1,>=0.23.0
|
| 30 |
+
Requires-Dist: packaging>=20.9
|
| 31 |
+
Requires-Dist: pyyaml>=5.1
|
| 32 |
+
Requires-Dist: tqdm>=4.42.1
|
| 33 |
+
Requires-Dist: typer
|
| 34 |
+
Requires-Dist: typing-extensions>=4.1.0
|
| 35 |
+
Provides-Extra: oauth
|
| 36 |
+
Requires-Dist: authlib>=1.3.2; extra == "oauth"
|
| 37 |
+
Requires-Dist: fastapi; extra == "oauth"
|
| 38 |
+
Requires-Dist: httpx; extra == "oauth"
|
| 39 |
+
Requires-Dist: itsdangerous; extra == "oauth"
|
| 40 |
+
Provides-Extra: torch
|
| 41 |
+
Requires-Dist: torch; extra == "torch"
|
| 42 |
+
Requires-Dist: safetensors[torch]; extra == "torch"
|
| 43 |
+
Provides-Extra: fastai
|
| 44 |
+
Requires-Dist: toml; extra == "fastai"
|
| 45 |
+
Requires-Dist: fastai>=2.4; extra == "fastai"
|
| 46 |
+
Requires-Dist: fastcore>=1.3.27; extra == "fastai"
|
| 47 |
+
Provides-Extra: hf-xet
|
| 48 |
+
Requires-Dist: hf-xet<2.0.0,>=1.4.3; extra == "hf-xet"
|
| 49 |
+
Provides-Extra: mcp
|
| 50 |
+
Requires-Dist: mcp>=1.8.0; extra == "mcp"
|
| 51 |
+
Provides-Extra: testing
|
| 52 |
+
Requires-Dist: authlib>=1.3.2; extra == "testing"
|
| 53 |
+
Requires-Dist: fastapi; extra == "testing"
|
| 54 |
+
Requires-Dist: httpx; extra == "testing"
|
| 55 |
+
Requires-Dist: itsdangerous; extra == "testing"
|
| 56 |
+
Requires-Dist: jedi; extra == "testing"
|
| 57 |
+
Requires-Dist: Jinja2; extra == "testing"
|
| 58 |
+
Requires-Dist: pytest>=8.4.2; extra == "testing"
|
| 59 |
+
Requires-Dist: pytest-cov; extra == "testing"
|
| 60 |
+
Requires-Dist: pytest-env; extra == "testing"
|
| 61 |
+
Requires-Dist: pytest-xdist; extra == "testing"
|
| 62 |
+
Requires-Dist: pytest-vcr; extra == "testing"
|
| 63 |
+
Requires-Dist: pytest-asyncio; extra == "testing"
|
| 64 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "testing"
|
| 65 |
+
Requires-Dist: pytest-mock; extra == "testing"
|
| 66 |
+
Requires-Dist: urllib3<2.0; extra == "testing"
|
| 67 |
+
Requires-Dist: soundfile; extra == "testing"
|
| 68 |
+
Requires-Dist: Pillow; extra == "testing"
|
| 69 |
+
Requires-Dist: numpy; extra == "testing"
|
| 70 |
+
Requires-Dist: duckdb; extra == "testing"
|
| 71 |
+
Requires-Dist: fastapi; extra == "testing"
|
| 72 |
+
Provides-Extra: gradio
|
| 73 |
+
Requires-Dist: gradio>=5.0.0; extra == "gradio"
|
| 74 |
+
Requires-Dist: requests; extra == "gradio"
|
| 75 |
+
Provides-Extra: typing
|
| 76 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "typing"
|
| 77 |
+
Requires-Dist: types-PyYAML; extra == "typing"
|
| 78 |
+
Requires-Dist: types-simplejson; extra == "typing"
|
| 79 |
+
Requires-Dist: types-toml; extra == "typing"
|
| 80 |
+
Requires-Dist: types-tqdm; extra == "typing"
|
| 81 |
+
Requires-Dist: types-urllib3; extra == "typing"
|
| 82 |
+
Provides-Extra: quality
|
| 83 |
+
Requires-Dist: ruff>=0.9.0; extra == "quality"
|
| 84 |
+
Requires-Dist: mypy==1.15.0; extra == "quality"
|
| 85 |
+
Requires-Dist: libcst>=1.4.0; extra == "quality"
|
| 86 |
+
Requires-Dist: ty; extra == "quality"
|
| 87 |
+
Provides-Extra: all
|
| 88 |
+
Requires-Dist: authlib>=1.3.2; extra == "all"
|
| 89 |
+
Requires-Dist: fastapi; extra == "all"
|
| 90 |
+
Requires-Dist: httpx; extra == "all"
|
| 91 |
+
Requires-Dist: itsdangerous; extra == "all"
|
| 92 |
+
Requires-Dist: jedi; extra == "all"
|
| 93 |
+
Requires-Dist: Jinja2; extra == "all"
|
| 94 |
+
Requires-Dist: pytest>=8.4.2; extra == "all"
|
| 95 |
+
Requires-Dist: pytest-cov; extra == "all"
|
| 96 |
+
Requires-Dist: pytest-env; extra == "all"
|
| 97 |
+
Requires-Dist: pytest-xdist; extra == "all"
|
| 98 |
+
Requires-Dist: pytest-vcr; extra == "all"
|
| 99 |
+
Requires-Dist: pytest-asyncio; extra == "all"
|
| 100 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "all"
|
| 101 |
+
Requires-Dist: pytest-mock; extra == "all"
|
| 102 |
+
Requires-Dist: urllib3<2.0; extra == "all"
|
| 103 |
+
Requires-Dist: soundfile; extra == "all"
|
| 104 |
+
Requires-Dist: Pillow; extra == "all"
|
| 105 |
+
Requires-Dist: numpy; extra == "all"
|
| 106 |
+
Requires-Dist: duckdb; extra == "all"
|
| 107 |
+
Requires-Dist: fastapi; extra == "all"
|
| 108 |
+
Requires-Dist: ruff>=0.9.0; extra == "all"
|
| 109 |
+
Requires-Dist: mypy==1.15.0; extra == "all"
|
| 110 |
+
Requires-Dist: libcst>=1.4.0; extra == "all"
|
| 111 |
+
Requires-Dist: ty; extra == "all"
|
| 112 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "all"
|
| 113 |
+
Requires-Dist: types-PyYAML; extra == "all"
|
| 114 |
+
Requires-Dist: types-simplejson; extra == "all"
|
| 115 |
+
Requires-Dist: types-toml; extra == "all"
|
| 116 |
+
Requires-Dist: types-tqdm; extra == "all"
|
| 117 |
+
Requires-Dist: types-urllib3; extra == "all"
|
| 118 |
+
Provides-Extra: dev
|
| 119 |
+
Requires-Dist: authlib>=1.3.2; extra == "dev"
|
| 120 |
+
Requires-Dist: fastapi; extra == "dev"
|
| 121 |
+
Requires-Dist: httpx; extra == "dev"
|
| 122 |
+
Requires-Dist: itsdangerous; extra == "dev"
|
| 123 |
+
Requires-Dist: jedi; extra == "dev"
|
| 124 |
+
Requires-Dist: Jinja2; extra == "dev"
|
| 125 |
+
Requires-Dist: pytest>=8.4.2; extra == "dev"
|
| 126 |
+
Requires-Dist: pytest-cov; extra == "dev"
|
| 127 |
+
Requires-Dist: pytest-env; extra == "dev"
|
| 128 |
+
Requires-Dist: pytest-xdist; extra == "dev"
|
| 129 |
+
Requires-Dist: pytest-vcr; extra == "dev"
|
| 130 |
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
| 131 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "dev"
|
| 132 |
+
Requires-Dist: pytest-mock; extra == "dev"
|
| 133 |
+
Requires-Dist: urllib3<2.0; extra == "dev"
|
| 134 |
+
Requires-Dist: soundfile; extra == "dev"
|
| 135 |
+
Requires-Dist: Pillow; extra == "dev"
|
| 136 |
+
Requires-Dist: numpy; extra == "dev"
|
| 137 |
+
Requires-Dist: duckdb; extra == "dev"
|
| 138 |
+
Requires-Dist: fastapi; extra == "dev"
|
| 139 |
+
Requires-Dist: ruff>=0.9.0; extra == "dev"
|
| 140 |
+
Requires-Dist: mypy==1.15.0; extra == "dev"
|
| 141 |
+
Requires-Dist: libcst>=1.4.0; extra == "dev"
|
| 142 |
+
Requires-Dist: ty; extra == "dev"
|
| 143 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "dev"
|
| 144 |
+
Requires-Dist: types-PyYAML; extra == "dev"
|
| 145 |
+
Requires-Dist: types-simplejson; extra == "dev"
|
| 146 |
+
Requires-Dist: types-toml; extra == "dev"
|
| 147 |
+
Requires-Dist: types-tqdm; extra == "dev"
|
| 148 |
+
Requires-Dist: types-urllib3; extra == "dev"
|
| 149 |
+
Dynamic: author
|
| 150 |
+
Dynamic: author-email
|
| 151 |
+
Dynamic: classifier
|
| 152 |
+
Dynamic: description
|
| 153 |
+
Dynamic: description-content-type
|
| 154 |
+
Dynamic: home-page
|
| 155 |
+
Dynamic: keywords
|
| 156 |
+
Dynamic: license
|
| 157 |
+
Dynamic: license-file
|
| 158 |
+
Dynamic: provides-extra
|
| 159 |
+
Dynamic: requires-dist
|
| 160 |
+
Dynamic: requires-python
|
| 161 |
+
Dynamic: summary
|
| 162 |
+
|
| 163 |
+
<p align="center">
|
| 164 |
+
<picture>
|
| 165 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub-dark.svg">
|
| 166 |
+
<source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg">
|
| 167 |
+
<img alt="huggingface_hub library logo" src="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg" width="352" height="59" style="max-width: 100%">
|
| 168 |
+
</picture>
|
| 169 |
+
<br/>
|
| 170 |
+
<br/>
|
| 171 |
+
</p>
|
| 172 |
+
|
| 173 |
+
<p align="center">
|
| 174 |
+
<i>The official Python client for the Huggingface Hub.</i>
|
| 175 |
+
</p>
|
| 176 |
+
|
| 177 |
+
<p align="center">
|
| 178 |
+
<a href="https://huggingface.co/docs/huggingface_hub/en/index"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/huggingface_hub/index.svg?down_color=red&down_message=offline&up_message=online&label=doc"></a>
|
| 179 |
+
<a href="https://github.com/huggingface/huggingface_hub/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/huggingface_hub.svg"></a>
|
| 180 |
+
<a href="https://github.com/huggingface/huggingface_hub"><img alt="PyPi version" src="https://img.shields.io/pypi/pyversions/huggingface_hub.svg"></a>
|
| 181 |
+
<a href="https://pypi.org/project/huggingface-hub"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/huggingface_hub"></a>
|
| 182 |
+
<a href="https://codecov.io/gh/huggingface/huggingface_hub"><img alt="Code coverage" src="https://codecov.io/gh/huggingface/huggingface_hub/branch/main/graph/badge.svg?token=RXP95LE2XL"></a>
|
| 183 |
+
</p>
|
| 184 |
+
|
| 185 |
+
<h4 align="center">
|
| 186 |
+
<p>
|
| 187 |
+
<b>English</b> |
|
| 188 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_de.md">Deutsch</a> |
|
| 189 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_fr.md">Français</a> |
|
| 190 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_hi.md">हिंदी</a> |
|
| 191 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_ko.md">한국어</a> |
|
| 192 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_cn.md">中文 (简体)</a>
|
| 193 |
+
<p>
|
| 194 |
+
</h4>
|
| 195 |
+
|
| 196 |
+
---
|
| 197 |
+
|
| 198 |
+
**Documentation**: <a href="https://hf.co/docs/huggingface_hub" target="_blank">https://hf.co/docs/huggingface_hub</a>
|
| 199 |
+
|
| 200 |
+
**Source Code**: <a href="https://github.com/huggingface/huggingface_hub" target="_blank">https://github.com/huggingface/huggingface_hub</a>
|
| 201 |
+
|
| 202 |
+
---
|
| 203 |
+
|
| 204 |
+
## Welcome to the huggingface_hub library
|
| 205 |
+
|
| 206 |
+
The `huggingface_hub` library allows you to interact with the [Hugging Face Hub](https://huggingface.co/), a platform democratizing open-source Machine Learning for creators and collaborators. Discover pre-trained models and datasets for your projects or play with the thousands of machine learning apps hosted on the Hub. You can also create and share your own models, datasets and demos with the community. The `huggingface_hub` library provides a simple way to do all these things with Python.
|
| 207 |
+
|
| 208 |
+
## Key features
|
| 209 |
+
|
| 210 |
+
- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub.
|
| 211 |
+
- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub.
|
| 212 |
+
- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository).
|
| 213 |
+
- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models.
|
| 214 |
+
- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces.
|
| 215 |
+
- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models.
|
| 216 |
+
- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments.
|
| 217 |
+
|
| 218 |
+
## Installation
|
| 219 |
+
|
| 220 |
+
Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/):
|
| 221 |
+
|
| 222 |
+
```bash
|
| 223 |
+
pip install huggingface_hub
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
If you prefer, you can also install it with [conda](https://huggingface.co/docs/huggingface_hub/en/installation#install-with-conda).
|
| 227 |
+
|
| 228 |
+
In order to keep the package minimal by default, `huggingface_hub` comes with optional dependencies useful for some use cases. For example, if you want to use the MCP module, run:
|
| 229 |
+
|
| 230 |
+
```bash
|
| 231 |
+
pip install "huggingface_hub[mcp]"
|
| 232 |
+
```
|
| 233 |
+
|
| 234 |
+
To learn more installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation).
|
| 235 |
+
|
| 236 |
+
## Quick start
|
| 237 |
+
|
| 238 |
+
### Download files
|
| 239 |
+
|
| 240 |
+
Download a single file
|
| 241 |
+
|
| 242 |
+
```py
|
| 243 |
+
from huggingface_hub import hf_hub_download
|
| 244 |
+
|
| 245 |
+
hf_hub_download(repo_id="tiiuae/falcon-7b-instruct", filename="config.json")
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
Or an entire repository
|
| 249 |
+
|
| 250 |
+
```py
|
| 251 |
+
from huggingface_hub import snapshot_download
|
| 252 |
+
|
| 253 |
+
snapshot_download("stabilityai/stable-diffusion-2-1")
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache).
|
| 257 |
+
|
| 258 |
+
### Login
|
| 259 |
+
|
| 260 |
+
The Hugging Face Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). To log in your machine, run the following CLI:
|
| 261 |
+
|
| 262 |
+
```bash
|
| 263 |
+
hf auth login
|
| 264 |
+
# or using an environment variable
|
| 265 |
+
hf auth login --token $HUGGINGFACE_TOKEN
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
### Create a repository
|
| 269 |
+
|
| 270 |
+
```py
|
| 271 |
+
from huggingface_hub import create_repo
|
| 272 |
+
|
| 273 |
+
create_repo(repo_id="super-cool-model")
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
### Upload files
|
| 277 |
+
|
| 278 |
+
Upload a single file
|
| 279 |
+
|
| 280 |
+
```py
|
| 281 |
+
from huggingface_hub import upload_file
|
| 282 |
+
|
| 283 |
+
upload_file(
|
| 284 |
+
path_or_fileobj="/home/lysandre/dummy-test/README.md",
|
| 285 |
+
path_in_repo="README.md",
|
| 286 |
+
repo_id="lysandre/test-model",
|
| 287 |
+
)
|
| 288 |
+
```
|
| 289 |
+
|
| 290 |
+
Or an entire folder
|
| 291 |
+
|
| 292 |
+
```py
|
| 293 |
+
from huggingface_hub import upload_folder
|
| 294 |
+
|
| 295 |
+
upload_folder(
|
| 296 |
+
folder_path="/path/to/local/space",
|
| 297 |
+
repo_id="username/my-cool-space",
|
| 298 |
+
repo_type="space",
|
| 299 |
+
)
|
| 300 |
+
```
|
| 301 |
+
|
| 302 |
+
For details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload).
|
| 303 |
+
|
| 304 |
+
## Integrating to the Hub.
|
| 305 |
+
|
| 306 |
+
We're partnering with cool open source ML libraries to provide free model hosting and versioning. You can find the existing integrations [here](https://huggingface.co/docs/hub/libraries).
|
| 307 |
+
|
| 308 |
+
The advantages are:
|
| 309 |
+
|
| 310 |
+
- Free model or dataset hosting for libraries and their users.
|
| 311 |
+
- Built-in file versioning, even with very large files, thanks to a git-based approach.
|
| 312 |
+
- In-browser widgets to play with the uploaded models.
|
| 313 |
+
- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable.
|
| 314 |
+
- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe.
|
| 315 |
+
- Usage stats and more features to come.
|
| 316 |
+
|
| 317 |
+
If you would like to integrate your library, feel free to open an issue to begin the discussion. We wrote a [step-by-step guide](https://huggingface.co/docs/hub/adding-a-library) with ❤️ showing how to do this integration.
|
| 318 |
+
|
| 319 |
+
## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️
|
| 320 |
+
|
| 321 |
+
Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community.
|
| 322 |
+
Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community.
|
| 323 |
+
We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarize
|
| 324 |
+
how to get started to contribute to this repository.
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
huggingface_hub/__init__.py,sha256=YYF-TUFz8NllcULmALKEcfBt2SZnFc3eCdy_12Zaimo,57746
|
| 2 |
+
huggingface_hub/_buckets.py,sha256=q-bbpYX9JROVMy0Qdk2Rx4hDv-B5_cDAQQYUdqeS6NA,43591
|
| 3 |
+
huggingface_hub/_commit_api.py,sha256=cEdBcUeL6e2mb2KSTXV9A5bQPuQ48rF1nhJQ4DqC2-c,40992
|
| 4 |
+
huggingface_hub/_commit_scheduler.py,sha256=VG3zjb7xb66NrFMq_pB9dWIsoqSPoF6CntovV7vUiWg,14684
|
| 5 |
+
huggingface_hub/_dataset_viewer.py,sha256=LE9k4s0WJ0JNdriJ8L6qV_-xfbUVC1VEh7CBd0jOjLI,5675
|
| 6 |
+
huggingface_hub/_eval_results.py,sha256=Og7p7bCl2HQG6ZWlSDyir-CRTXjNWPu3S3q65cTGffs,8126
|
| 7 |
+
huggingface_hub/_inference_endpoints.py,sha256=rwetck_MnbV-MrTLVN7cazIrxUNYi5x2nBkw1devnxY,17643
|
| 8 |
+
huggingface_hub/_jobs_api.py,sha256=XSmWO4MfXalDTfJ9wyrtV6wPW9I_2PiXGEuuMXylAhQ,14479
|
| 9 |
+
huggingface_hub/_local_folder.py,sha256=Fc_hikyMaZRHtXIDZj38hL7MNkq5nZZVxQF-dd-EkMo,18279
|
| 10 |
+
huggingface_hub/_login.py,sha256=Y4n1dlXYBr_6hrTv6X_Sx5iR2SR9_2NgFZ5t8grWmgk,19447
|
| 11 |
+
huggingface_hub/_oauth.py,sha256=S8evEd8JLJHz-JiSjGH4WiIi_A7oDox_xH7E9rN1Jic,18628
|
| 12 |
+
huggingface_hub/_snapshot_download.py,sha256=KqiEBSM8CvVXFAZHUS1lINN94WK05q9-exNWrzYO6kE,20614
|
| 13 |
+
huggingface_hub/_space_api.py,sha256=hSLxhMHJXzHPWfhVRvr2oH7Hs3Fo4nkDG86e9_iP0F8,8580
|
| 14 |
+
huggingface_hub/_tensorboard_logger.py,sha256=wIf7jwvb28mbhaNDvoJBnHSaIZvAhqfiiUSsqe0xd5E,8337
|
| 15 |
+
huggingface_hub/_upload_large_folder.py,sha256=TG8gXPxE2zY7vWZST1lJLZ0Sed8OMeuKkbe2TO8v6D0,31082
|
| 16 |
+
huggingface_hub/_webhooks_payload.py,sha256=B9zqljcm20DGeVxJKba570i6RP-cR9CEupMGBuNDHHA,3544
|
| 17 |
+
huggingface_hub/_webhooks_server.py,sha256=A172KmELV-pGjA819D4UgOHcuvHxCFdwOLPlu2kqHa4,15668
|
| 18 |
+
huggingface_hub/community.py,sha256=N5OE5Rbc2BMwpNXCFOPQAwn0otqQunsXdEnSE_0J2Xo,12325
|
| 19 |
+
huggingface_hub/constants.py,sha256=VQRYqDW1K0nTLREFihtiXqzRFAWv9OYjaYZlH2y6H4A,10801
|
| 20 |
+
huggingface_hub/dataclasses.py,sha256=LoEOPRQTXgr9V7OPWvieADLuflW47l6THGaduntlqx4,26047
|
| 21 |
+
huggingface_hub/errors.py,sha256=Mp34z5fFbtrMqcMtImFolD3p3M5T38e7J7Zetea-mVQ,14052
|
| 22 |
+
huggingface_hub/fastai_utils.py,sha256=jwKeVXH_VP0zxnOKVNQCVCkF-stH70l-bExbbrYkBKQ,16583
|
| 23 |
+
huggingface_hub/file_download.py,sha256=9_lRpeb7s440EDss4VRlOd2hmwdgQ5oBvtpCpj4W0h8,81520
|
| 24 |
+
huggingface_hub/hf_api.py,sha256=xVIo2TM3bTsSW3Yo2jiZaJY3NtZVmxqlDAJ9pnrgVOQ,600901
|
| 25 |
+
huggingface_hub/hf_file_system.py,sha256=WGTFhoV29lMQvt4y9C3IQX4tvQPAz9l3pe-dKFPH3oc,61518
|
| 26 |
+
huggingface_hub/hub_mixin.py,sha256=ljKAtm3qQsY-ARtxY-PCFx0koFXLI37JytMrzpqfnQo,36912
|
| 27 |
+
huggingface_hub/lfs.py,sha256=sVkRZMD8w-3vxaqSDSrsBCog6-lLyWP98u_xR1dIwMo,14123
|
| 28 |
+
huggingface_hub/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 29 |
+
huggingface_hub/repocard.py,sha256=p2b9GiEzqrMJZW3O41nwiC6AseQhFNbqCbSIpoP_8VE,34829
|
| 30 |
+
huggingface_hub/repocard_data.py,sha256=lI-DEIbmjtlOMvkntqwXA9ED4icTeCvNbAOYc2P2ZMk,33879
|
| 31 |
+
huggingface_hub/_hot_reload/__init__.py,sha256=nQEuyVZLAS_463Dff1JH5MorTpkYsBVFCyPhYWY3UyI,606
|
| 32 |
+
huggingface_hub/_hot_reload/client.py,sha256=biqp6o_ev8Z-BM3BFvK17rzqEKRiVLfiYKKrLUcmE0k,3414
|
| 33 |
+
huggingface_hub/_hot_reload/sse_client.py,sha256=49kmsB2P9sxgbZ16ed6F4aLDs3rsHrNpbp6iKlvF90c,4948
|
| 34 |
+
huggingface_hub/_hot_reload/types.py,sha256=u5FqzqEngOCVzd2nZ0zwsOpmNQAI94XCI0v2p0GAFIU,2611
|
| 35 |
+
huggingface_hub/cli/__init__.py,sha256=A4zmzuHD2OHjQ5zmdfcnsj0JeCzHVPtpzh-wCjInugA,606
|
| 36 |
+
huggingface_hub/cli/_cli_utils.py,sha256=LyZ0EOhlGQCMV0bpHPyjDeU0n7DEEf1nGj_wsDAwJn4,41288
|
| 37 |
+
huggingface_hub/cli/_errors.py,sha256=Vt_q9EOWU8OROh4Rmim2h_3yoFPg4PEIH6ZXFxehE60,4420
|
| 38 |
+
huggingface_hub/cli/_output.py,sha256=LJcjaiUx02Ri4YXhcLBGfXWbpme3IxcFLws3izICcQU,9279
|
| 39 |
+
huggingface_hub/cli/_skills.py,sha256=Lra5VDcRMdf6LqnxAfph8soGOZBEQEuiG30yb30XFx8,15607
|
| 40 |
+
huggingface_hub/cli/auth.py,sha256=2noH1mdMxBjopBiCqZ4RBG0WnnxqsJv1-Ao2flvdIEw,4977
|
| 41 |
+
huggingface_hub/cli/buckets.py,sha256=bOnzLIUCofPwCMvZ5f1p679PpPedCiR5WLCSOl28_Uo,34436
|
| 42 |
+
huggingface_hub/cli/cache.py,sha256=hfpcOkzbkbr1WgxEEKkqNAvMPfYEtLHHlpeTvkcWsFE,27930
|
| 43 |
+
huggingface_hub/cli/collections.py,sha256=Jxyn3CymvbN0ht9WWpOWDDQXmxRwVQlj2lQVRwmmtJ0,11119
|
| 44 |
+
huggingface_hub/cli/datasets.py,sha256=Y53w7uX_6oDgBJFJzy_jepHTfEwXEGCkqFUROkgxDHk,6045
|
| 45 |
+
huggingface_hub/cli/deprecated_cli.py,sha256=vAK_CR4NE9uzNJ0I59SyBnIln5nlypG4CPoohMoPMVg,1090
|
| 46 |
+
huggingface_hub/cli/discussions.py,sha256=HudxUFLsTnmB_RXfRbW5bpcwaRQGlgsAhUZG758BjKk,16873
|
| 47 |
+
huggingface_hub/cli/download.py,sha256=dme703Dv4BKy0UWOUa5rq2lDd6oML3w3EOnGh81OaEw,8456
|
| 48 |
+
huggingface_hub/cli/extensions.py,sha256=bxI4Jm6NtnhHgm1Ja9MWqx8p8NP148wxy6R8dPk2-Qo,22217
|
| 49 |
+
huggingface_hub/cli/hf.py,sha256=PvTG54_Bp1Xm246Vjo7snxpDHGdRT7phuDCkawhL0FU,4514
|
| 50 |
+
huggingface_hub/cli/inference_endpoints.py,sha256=o8zlJviRsmlHQwsZH5sFWAIS3Nq6kWoUgYBLyf1zzSQ,14689
|
| 51 |
+
huggingface_hub/cli/jobs.py,sha256=P__-mKLcEbTxPpY-NgCN6V7QeH371mTXkoKQWeKh4Io,38558
|
| 52 |
+
huggingface_hub/cli/lfs.py,sha256=v2yBjwBNOg0WAr6WtT5wWlTxut8OUVmcQ0ryG99OtCA,5876
|
| 53 |
+
huggingface_hub/cli/models.py,sha256=yOhSQIPs1Sj1Xl-i3tEuxdgDc8Dvs31EvSEEmAjemNU,4122
|
| 54 |
+
huggingface_hub/cli/papers.py,sha256=fcUWGDLCnkT--ZVo8OeZfCJUr9igU4WLoIJJOKsdE7c,5969
|
| 55 |
+
huggingface_hub/cli/repo_files.py,sha256=qmGq1IjsigWdRUG62OJ6qWIIvnbaLyYKCjXb6oQuTH0,2606
|
| 56 |
+
huggingface_hub/cli/repos.py,sha256=4rbwFWj0n0B-h3TwbYqGHVFn7OB01t6qhsuGYL_rbHM,16554
|
| 57 |
+
huggingface_hub/cli/skills.py,sha256=OV1-9t3HnoGSCLrNC38tcr2CCUjR2JVhbb_cYOCsLo4,16539
|
| 58 |
+
huggingface_hub/cli/spaces.py,sha256=99Uk08r-XRQsZ9XBlM9sOkcRrw72xeZ0ZGCN3pLyrVY,16392
|
| 59 |
+
huggingface_hub/cli/system.py,sha256=RNEJRtrz3bt2r3-nY6XCgd46lb9-XWMgRt-lvMqRxN4,968
|
| 60 |
+
huggingface_hub/cli/upload.py,sha256=EPTgOQy-pKGICIUHonWl_eqRR6uBixCVSSawwnVaGEE,11375
|
| 61 |
+
huggingface_hub/cli/upload_large_folder.py,sha256=awPcKskKoczmoyqkIYpwz93LYm0UFoT6ysLG6Wvr60E,4661
|
| 62 |
+
huggingface_hub/cli/webhooks.py,sha256=BTWY4FttWyVjPqoUfLqW9jVGu_o-KzC3oZYYZV9Pweg,9931
|
| 63 |
+
huggingface_hub/inference/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 64 |
+
huggingface_hub/inference/_client.py,sha256=HQHnsXtnn1wzFwsrPe68F5jkgbYm46LvhB1iNA8aVhU,157652
|
| 65 |
+
huggingface_hub/inference/_common.py,sha256=X-fBP8s6xuNTAuQsGVIethE8dNQaa-mK7Ds54qVVDz8,14999
|
| 66 |
+
huggingface_hub/inference/_generated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 67 |
+
huggingface_hub/inference/_generated/_async_client.py,sha256=NsfY1Ec84wfoXxAEf4K4mv29_uZM08dYy_aKRel9mxM,160863
|
| 68 |
+
huggingface_hub/inference/_generated/types/__init__.py,sha256=e625ENOmTUM4uUL1eAlsZOK7CovNoGBDH-TxSNQhaC4,6869
|
| 69 |
+
huggingface_hub/inference/_generated/types/audio_classification.py,sha256=DGWEvrRPX7xpXlbYY4LMojGcULdEZFTshhNR81rTNcQ,1567
|
| 70 |
+
huggingface_hub/inference/_generated/types/audio_to_audio.py,sha256=2Ep4WkePL7oJwcp5nRJqApwviumGHbft9HhXE9XLHj4,891
|
| 71 |
+
huggingface_hub/inference/_generated/types/automatic_speech_recognition.py,sha256=X0uCj9qwAcOmlKtV3vWH5cAgLGY0PuYIy2eSH7GE1qs,5439
|
| 72 |
+
huggingface_hub/inference/_generated/types/base.py,sha256=EPWp1qudjeEimEAyQ-ptdxpAACoRM8tW342-Ds7pP3I,6938
|
| 73 |
+
huggingface_hub/inference/_generated/types/chat_completion.py,sha256=3yc06ZI0NCZzsaeoxSMWyIHqGc8Vn_6aExncuXa1llE,11100
|
| 74 |
+
huggingface_hub/inference/_generated/types/depth_estimation.py,sha256=5Kn4xNGJg235Cofr1lzO59eRGCuLTZun8z5t6a2do8Q,910
|
| 75 |
+
huggingface_hub/inference/_generated/types/document_question_answering.py,sha256=aUZcrDGexjw8Fnm2rACm_3my77V15NnQHZxj-sa7bjo,3146
|
| 76 |
+
huggingface_hub/inference/_generated/types/feature_extraction.py,sha256=DiO47PqwhdNta_KPDBsXfCPIL6BWNhyCLymxORlqUA0,1509
|
| 77 |
+
huggingface_hub/inference/_generated/types/fill_mask.py,sha256=NhEskgoiMst7U_0cV_S-wryga4_2T5LgpbyQ23vHMp0,1680
|
| 78 |
+
huggingface_hub/inference/_generated/types/image_classification.py,sha256=xWr4OY65EcIIhd7MI610a7xlaAVHQeydi8Gc7tlaPTU,1579
|
| 79 |
+
huggingface_hub/inference/_generated/types/image_segmentation.py,sha256=lZKzbn_gkSi1sYGLb9ryeRr0aDAVrfYh0H5Iiv5JNsY,1935
|
| 80 |
+
huggingface_hub/inference/_generated/types/image_text_to_image.py,sha256=pRQgYKXJbIpEjRBxuIE6NRDtk_km9DSTQ2s2qxkYJRM,2585
|
| 81 |
+
huggingface_hub/inference/_generated/types/image_text_to_video.py,sha256=MVhP8D4eYjpT3hWYkkpuiME-hWY09o7C4rIn_wmnAmY,2450
|
| 82 |
+
huggingface_hub/inference/_generated/types/image_to_image.py,sha256=P9TeMFSnZI_pa6DyinzDPWL0PNm_INJwsqFUEzpwIcU,2262
|
| 83 |
+
huggingface_hub/inference/_generated/types/image_to_text.py,sha256=DCDS0Nqi-4AuATitvZm4EgrzYQuQEQ5lzBcaHuCmHnY,4740
|
| 84 |
+
huggingface_hub/inference/_generated/types/image_to_video.py,sha256=iMCjiFTUza9AW_MyJ1videhYgvMY9QSzQ59kNdTE9QY,2206
|
| 85 |
+
huggingface_hub/inference/_generated/types/object_detection.py,sha256=zNILlyZJh59rNNfqXM5x9uprDCPfEU-bvBtabeKSMzI,1965
|
| 86 |
+
huggingface_hub/inference/_generated/types/question_answering.py,sha256=lIRf8DjRiAsjzWUBEsGt354SB4bvejLokf-8luHw6_o,2845
|
| 87 |
+
huggingface_hub/inference/_generated/types/sentence_similarity.py,sha256=eNGiO4dR-Lft9yOLE0E97jfVyOT_ExDWZW5GeJGdatU,1027
|
| 88 |
+
huggingface_hub/inference/_generated/types/summarization.py,sha256=5Dpt6LRteT-hO9esa3Ty_-xSL5U-zTtVZzy3iKwZRng,1472
|
| 89 |
+
huggingface_hub/inference/_generated/types/table_question_answering.py,sha256=bwn616XJ-eLa5JKzn3m9rZZ3z63INGEUwRSOCWlEh-4,2269
|
| 90 |
+
huggingface_hub/inference/_generated/types/text2text_generation.py,sha256=fotSlPWtIlp_LG26AQvNRXxU-jCUfda5PWsxCkbFeKM,1591
|
| 91 |
+
huggingface_hub/inference/_generated/types/text_classification.py,sha256=uamBzz4YzWQ9mb6yuriykX8r47ZHf0K3eJpOLzB2qJw,1439
|
| 92 |
+
huggingface_hub/inference/_generated/types/text_generation.py,sha256=FRUljypvCSQ2RaiylhlHeLJfHNy8qZvuty6SCB_zcaA,5813
|
| 93 |
+
huggingface_hub/inference/_generated/types/text_to_audio.py,sha256=CiaTUSBdFtOs3gGTosqyQrjCwrN8mVJLRxDDWUtwZpQ,4677
|
| 94 |
+
huggingface_hub/inference/_generated/types/text_to_image.py,sha256=Ju25WIDHE-1n8jlZ_udG4rpAaPYpmghR7-cDgVfuf48,1869
|
| 95 |
+
huggingface_hub/inference/_generated/types/text_to_speech.py,sha256=WqDzWkhZsDcjapkoFrkyjF903SKs7aHhjypsYrn8oBw,4693
|
| 96 |
+
huggingface_hub/inference/_generated/types/text_to_video.py,sha256=KjcDbtChwrIxIdTH6vcesUaMcjL2xjPf2nWEnHazj4Y,1756
|
| 97 |
+
huggingface_hub/inference/_generated/types/token_classification.py,sha256=8KRBlqgFDszaUnPMvdRkZNQaZBtDfBhKZ6SggQldQMM,1894
|
| 98 |
+
huggingface_hub/inference/_generated/types/translation.py,sha256=-j2PC1-qfoxvGMaKesqf5jXelqj0BDlEpfvZ7dsIEJM,1742
|
| 99 |
+
huggingface_hub/inference/_generated/types/video_classification.py,sha256=vfaCqp8MuRMMtGvYCX0x4-AcwEd71kPHgSYJTNIOxLQ,1668
|
| 100 |
+
huggingface_hub/inference/_generated/types/visual_question_answering.py,sha256=sWIB-SuEpW21oU6O5qQF3tt5PavUFsFOa8Xg4upTtek,1654
|
| 101 |
+
huggingface_hub/inference/_generated/types/zero_shot_classification.py,sha256=gx-7WHad7xsNa89iSKSteKHjaHrKbIyzN_nSdJN3HCY,1697
|
| 102 |
+
huggingface_hub/inference/_generated/types/zero_shot_image_classification.py,sha256=JZTQvcbSGrOQlWcPuJvAMT8YziDpBRn1O2RQSw507uY,1449
|
| 103 |
+
huggingface_hub/inference/_generated/types/zero_shot_object_detection.py,sha256=sjdpVUN5zW9aYBymLVUs6i5HVk2qkUBO9ysEjHmsXVM,1605
|
| 104 |
+
huggingface_hub/inference/_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 105 |
+
huggingface_hub/inference/_mcp/_cli_hacks.py,sha256=KX9HZJPa1p8ngY3mtYGGlVUXfg4vYbbBRs-8HLToP04,3284
|
| 106 |
+
huggingface_hub/inference/_mcp/agent.py,sha256=ufIzMGHore5n252hV5GZPM0ouDXIl6tv5Jl_5gHXnbg,4250
|
| 107 |
+
huggingface_hub/inference/_mcp/cli.py,sha256=YsabbtVJzQ4vNN5km86BYcLV0SgkgE3hM2pIt6BpyAA,9801
|
| 108 |
+
huggingface_hub/inference/_mcp/constants.py,sha256=lLRgR6gRuqJ4u7jqngVUgVYeOzactgJpkTxx66t1piE,2463
|
| 109 |
+
huggingface_hub/inference/_mcp/mcp_client.py,sha256=dGp8PhN6aVw4bDnuSySFSiguHUiz-nzhgv89CVdO7pI,17243
|
| 110 |
+
huggingface_hub/inference/_mcp/types.py,sha256=yHNfPsM9MhD06oeKdkbmrBsW-3WhUeqA26fyfRfx_bk,929
|
| 111 |
+
huggingface_hub/inference/_mcp/utils.py,sha256=gxSB_rBjQ6VrkApKFsxk6-UzhijxkDVNuZrsjW5pL8k,4318
|
| 112 |
+
huggingface_hub/inference/_providers/__init__.py,sha256=9IqrkkjF2CpEXTXcSuUzFTSuImVRvVyyAp8ffbazzl8,10450
|
| 113 |
+
huggingface_hub/inference/_providers/_common.py,sha256=9GwMvLkV0Rt22Ej27DAZq4HtsnUOK0mrbCxZ4GbfH_4,13794
|
| 114 |
+
huggingface_hub/inference/_providers/black_forest_labs.py,sha256=HO3DaD97Hqy6b823b6VUPqiEqhHLKGeMVtJ4CMjGRPA,2817
|
| 115 |
+
huggingface_hub/inference/_providers/cerebras.py,sha256=QOJ-1U-os7uE7p6eUnn_P_APq-yQhx28be7c3Tq2EuA,210
|
| 116 |
+
huggingface_hub/inference/_providers/clarifai.py,sha256=1cEXQwhGk4DRKiPCQUa5y-L6okTo4781EImQC8yJVOw,380
|
| 117 |
+
huggingface_hub/inference/_providers/cohere.py,sha256=P9kbIuvQ2rXI1yNmgbw5VKFFTE0huLq2k-BCyDkDico,1226
|
| 118 |
+
huggingface_hub/inference/_providers/fal_ai.py,sha256=Y2vo5Dl3e8EoehplwNshu8LbDT1e7V4ZyhAMqs0wXws,11705
|
| 119 |
+
huggingface_hub/inference/_providers/featherless_ai.py,sha256=C8OHdFpoFyA--pawLTekUmUSRq4sw_r0D-cSPekD4kE,1347
|
| 120 |
+
huggingface_hub/inference/_providers/fireworks_ai.py,sha256=go6XPum8u0-g768HJ_r0S4Gb445gZJxnuY_acktz-9c,1188
|
| 121 |
+
huggingface_hub/inference/_providers/groq.py,sha256=JTk2JV4ZOlaohho7zLAFQtk92kGVsPmLJ1hmzcwsqvQ,315
|
| 122 |
+
huggingface_hub/inference/_providers/hf_inference.py,sha256=d2vdCKSi5CtyQqYndHHvH7SY131-7YHUK3yE7653eIc,9467
|
| 123 |
+
huggingface_hub/inference/_providers/hyperbolic.py,sha256=Zk2rw2k-R0JxrfpcaHhAUuB5D6s40XK0tuvuKwglsUE,1950
|
| 124 |
+
huggingface_hub/inference/_providers/nebius.py,sha256=OTPXQIYxQSwZc8FzhGAHUaa6Mkp3h6LphSVoa_1gY7I,3513
|
| 125 |
+
huggingface_hub/inference/_providers/novita.py,sha256=ATEoSdPAPLMfx3JpBc0sOyLh4upJYP6xHBuo4YEDYvg,2470
|
| 126 |
+
huggingface_hub/inference/_providers/nscale.py,sha256=T1L2JLI9LqYT9_YEdW76YEtxfDNtdGkoFhH-p2LmSxg,1767
|
| 127 |
+
huggingface_hub/inference/_providers/nvidia.py,sha256=ocMuhycyIo8qiJf-E50oHGYuPvMcJC0BexSXBOYaOFg,251
|
| 128 |
+
huggingface_hub/inference/_providers/openai.py,sha256=wwjaaQ55xLmDsDnHpZk52xbuLoGZfWzJkFsE8AdFVaI,1054
|
| 129 |
+
huggingface_hub/inference/_providers/ovhcloud.py,sha256=tdmymlkbddMJKV7NRZ-tH2wymbLPFDTqUSXpWJUXyDQ,314
|
| 130 |
+
huggingface_hub/inference/_providers/publicai.py,sha256=1I2W6rORloB5QHSvky4njZO2XKLTwA-kPdNoauoT5rg,210
|
| 131 |
+
huggingface_hub/inference/_providers/replicate.py,sha256=hte0ZB2RtGFwpAuLrFp2Gbgsn3EOlccCnJkWTDTW__A,6027
|
| 132 |
+
huggingface_hub/inference/_providers/sambanova.py,sha256=2dkhLf5nKGZ8hOqF-oWYHIN-Wckcwq0cMVf8UYgmDy4,1999
|
| 133 |
+
huggingface_hub/inference/_providers/scaleway.py,sha256=MfIc7ZND1sPr__rOmNHZVg0VpECQo0bVyksgIm_32xQ,1174
|
| 134 |
+
huggingface_hub/inference/_providers/together.py,sha256=OviPGPE6JvJwxf94DKpmsyWlryLU-W9OrHBcr36JT1w,3384
|
| 135 |
+
huggingface_hub/inference/_providers/wavespeed.py,sha256=MGM7Y7r2nQiH_EH0t5UE1o1fT-o3sS7RaQlicS9WHsg,5028
|
| 136 |
+
huggingface_hub/inference/_providers/zai_org.py,sha256=gLJZOEmCPmUZvdM7VDn2nxm4ac3veHdoMgQNR63UeWE,4739
|
| 137 |
+
huggingface_hub/serialization/__init__.py,sha256=jCiw_vVQYW52gwVfWiqgocf2Q19kGTQlRGVpf-4SLP8,963
|
| 138 |
+
huggingface_hub/serialization/_base.py,sha256=-bhRW21ZIqza5gE_kWkL8ax-EE6L6xabKkkK35wOX0Y,8176
|
| 139 |
+
huggingface_hub/serialization/_dduf.py,sha256=FmGRg5wkXI5sNCgZgCNJFmqb_nVrrQYOHf4Lqq0d64I,15385
|
| 140 |
+
huggingface_hub/serialization/_torch.py,sha256=Sdi9LxYSZJPj7GtM60jDFCqOXhxHQA59PvReUs6OuzM,46077
|
| 141 |
+
huggingface_hub/templates/datasetcard_template.md,sha256=W-EMqR6wndbrnZorkVv56URWPG49l7MATGeI015kTvs,5503
|
| 142 |
+
huggingface_hub/templates/modelcard_template.md,sha256=4AqArS3cqdtbit5Bo-DhjcnDFR-pza5hErLLTPM4Yuc,6870
|
| 143 |
+
huggingface_hub/utils/__init__.py,sha256=Qj-VsqSdXTUfUDk2ZfBf756oaYw7-x8W_AUZdtDiwXQ,3983
|
| 144 |
+
huggingface_hub/utils/_auth.py,sha256=DeSmNYy8UiAgrETNsHE5VZtzc-3-IKRqtFjxMxXBRdE,8227
|
| 145 |
+
huggingface_hub/utils/_cache_assets.py,sha256=nnzHRtQAR50dQeIK6qKddsmjjTW9v9HZ7b9bq7PJqss,5691
|
| 146 |
+
huggingface_hub/utils/_cache_manager.py,sha256=K3MfxR2we_uU2j5xLD1bMru6zihzDDlyZZm6mGUOxtM,33023
|
| 147 |
+
huggingface_hub/utils/_chunk_utils.py,sha256=pTjy8Z-KLU4W_6D3OUh3E8lCodWDCd6aJwjNDU0C5U8,2121
|
| 148 |
+
huggingface_hub/utils/_datetime.py,sha256=tbNyI0Dkh27oScPUtLIT_8apqIIkXZYbigjOn9S3aMw,2755
|
| 149 |
+
huggingface_hub/utils/_deprecation.py,sha256=n4kNHbGipquSObJ-gxodcfd6lqoe_8s-VIsTuo3Oruk,4865
|
| 150 |
+
huggingface_hub/utils/_detect_agent.py,sha256=6ABYV6J7Z2mI2fjHO1NzZRpP0PNXUPGZMnty9C30xVs,2995
|
| 151 |
+
huggingface_hub/utils/_dotenv.py,sha256=QfL6aWFp5NffhJEYFd6FtKHqly5EBpY8Cb-o9t8Ul04,1980
|
| 152 |
+
huggingface_hub/utils/_experimental.py,sha256=q9vUvc1JybVFRQ0GRREG-BLouZEJC_40MxcwbAlOud0,2464
|
| 153 |
+
huggingface_hub/utils/_fixes.py,sha256=jTK1VLmc0ZC9ROSXjKoL5F6kOZFByzirRWIdXxhBfWU,4124
|
| 154 |
+
huggingface_hub/utils/_git_credential.py,sha256=1BhjvIScCOAToDORLOKrR3Szs-m0E5AYHPmC0SD7Nrs,4548
|
| 155 |
+
huggingface_hub/utils/_headers.py,sha256=fHd8JflV1sX02mdQnwc7k1zll3ZXceu-HmmGz0UOEFo,8090
|
| 156 |
+
huggingface_hub/utils/_http.py,sha256=mYe00YziVhqev6j6d_cwYpnDZ159ZSBjywsSluakOlU,42918
|
| 157 |
+
huggingface_hub/utils/_lfs.py,sha256=xMU-ROgNAUpDkzbH6yRZsE-eVYUYTNMGrgVb_QdTv-k,3942
|
| 158 |
+
huggingface_hub/utils/_pagination.py,sha256=buIKERSyWOJqVSY9nv8hImDmNErD-PPOnXosXm2O87Y,1832
|
| 159 |
+
huggingface_hub/utils/_parsing.py,sha256=Z07oEU-19L_0Mav7_LRZLz0z0NuS4bLDaAY1RPdeqf0,2982
|
| 160 |
+
huggingface_hub/utils/_paths.py,sha256=ZceF9JnRzNrvrMSvPbgriuRQ3_LpLa3EE8W21bvBxaU,5265
|
| 161 |
+
huggingface_hub/utils/_runtime.py,sha256=U2FY_TzuvJYEgG1eMznMgEUttLqj1PVCxEOHWKPT-bw,13034
|
| 162 |
+
huggingface_hub/utils/_safetensors.py,sha256=qFE7OA-vjU8X0zBBtOeNRzLu147KF-PdFoaxkYfWB4M,4426
|
| 163 |
+
huggingface_hub/utils/_subprocess.py,sha256=tFVBBNot_HLVqQ79y873TGb12C4PUTMwub-GhzDTemE,4542
|
| 164 |
+
huggingface_hub/utils/_telemetry.py,sha256=Tpa3YmOLhK_MEnL2i2fRLQy8aqAEZWbj6MKC18Hs8BA,4824
|
| 165 |
+
huggingface_hub/utils/_terminal.py,sha256=7jdWt1xvmx7nOlYG416833EjJyukvDzksTVfRFloAtg,3532
|
| 166 |
+
huggingface_hub/utils/_typing.py,sha256=1LeE785YedppXSR9a1fQDu5rhTxX5v9kBYBaHrP65rA,3542
|
| 167 |
+
huggingface_hub/utils/_validators.py,sha256=tuC1U4yxB-4XKIajZMnKZUSKvZ6qPpydY8LItfa0g40,8419
|
| 168 |
+
huggingface_hub/utils/_verification.py,sha256=ZSilnolSkYmHB3vmBlWuuVr53xz59P5uGnxC3H-Hjc0,5434
|
| 169 |
+
huggingface_hub/utils/_xet.py,sha256=v2VI_iVGIp4-mGT44L9nY9R4fdBeVepjUBzsVIeQS1g,9834
|
| 170 |
+
huggingface_hub/utils/_xet_progress_reporting.py,sha256=IlrrHAgHYKsep4o9fhsCtdMFhKxp5rKoHs785x5q21k,6826
|
| 171 |
+
huggingface_hub/utils/endpoint_helpers.py,sha256=9VtIAlxQ5H_4y30sjCAgbu7XCqAtNLC7aRYxaNn0hLI,2366
|
| 172 |
+
huggingface_hub/utils/insecure_hashlib.py,sha256=z3dVUFvdBZ8kQI_8Vzvvlr3ims-EBiY-SYPdnzIKOkw,1008
|
| 173 |
+
huggingface_hub/utils/logging.py,sha256=WaXk5gRa8Ml_LUIH34QCr8suYj8i_8Wot4IDnYJyWyM,4870
|
| 174 |
+
huggingface_hub/utils/sha.py,sha256=h8wxheZpcv671RhtiIFcFmQTDSrogN3kwQx3ZaNEUHg,2121
|
| 175 |
+
huggingface_hub/utils/tqdm.py,sha256=n1iEPQR8mCbpwFvFolVV_w7uLL-ST8CedvfGZB8Q7ZY,12335
|
| 176 |
+
huggingface_hub-1.10.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
| 177 |
+
huggingface_hub-1.10.1.dist-info/METADATA,sha256=gK_X8_quZLC_FQraiTjtb9BnGHHR1mygCTGkIPLs-ow,14017
|
| 178 |
+
huggingface_hub-1.10.1.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
|
| 179 |
+
huggingface_hub-1.10.1.dist-info/entry_points.txt,sha256=zP7F_bBSdircPQFysHQZ9F3Lcn5_dCSOEZxVlGCsG0w,212
|
| 180 |
+
huggingface_hub-1.10.1.dist-info/top_level.txt,sha256=8KzlQJAY4miUvjAssOAJodqKOw3harNzuiwGQ9qLSSk,16
|
| 181 |
+
huggingface_hub-1.10.1.dist-info/RECORD,,
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (79.0.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub-1.10.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
hf = huggingface_hub.cli.hf:main
|
| 3 |
+
huggingface-cli = huggingface_hub.cli.deprecated_cli:main
|
| 4 |
+
tiny-agents = huggingface_hub.inference._mcp.cli:app
|
| 5 |
+
|
| 6 |
+
[fsspec.specs]
|
| 7 |
+
hf = huggingface_hub.HfFileSystem
|
.cache/uv/archive-v0/P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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections.abc
|
| 2 |
+
import inspect
|
| 3 |
+
import types
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from dataclasses import _MISSING_TYPE, MISSING, Field, field, fields, make_dataclass
|
| 6 |
+
from functools import lru_cache, wraps
|
| 7 |
+
from typing import (
|
| 8 |
+
Annotated,
|
| 9 |
+
Any,
|
| 10 |
+
ForwardRef,
|
| 11 |
+
Literal,
|
| 12 |
+
Type,
|
| 13 |
+
TypeVar,
|
| 14 |
+
Union,
|
| 15 |
+
get_args,
|
| 16 |
+
get_origin,
|
| 17 |
+
overload,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
# Python 3.11+
|
| 23 |
+
from typing import NotRequired, Required # type: ignore
|
| 24 |
+
except ImportError:
|
| 25 |
+
try:
|
| 26 |
+
# In case typing_extensions is installed
|
| 27 |
+
from typing_extensions import NotRequired, Required # type: ignore
|
| 28 |
+
except ImportError:
|
| 29 |
+
# Fallback: create dummy types that will never match
|
| 30 |
+
Required = type("Required", (), {}) # type: ignore
|
| 31 |
+
NotRequired = type("NotRequired", (), {}) # type: ignore
|
| 32 |
+
|
| 33 |
+
from .errors import (
|
| 34 |
+
StrictDataclassClassValidationError,
|
| 35 |
+
StrictDataclassDefinitionError,
|
| 36 |
+
StrictDataclassFieldValidationError,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Validator_T = Callable[[Any], None]
|
| 41 |
+
T = TypeVar("T")
|
| 42 |
+
TypedDictType = TypeVar("TypedDictType", bound=dict[str, Any])
|
| 43 |
+
|
| 44 |
+
_TYPED_DICT_DEFAULT_VALUE = object() # used as default value in TypedDict fields (to distinguish from None)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# The overload decorator helps type checkers understand the different return types
|
| 48 |
+
@overload
|
| 49 |
+
def strict(cls: Type[T]) -> Type[T]: ...
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@overload
|
| 53 |
+
def strict(*, accept_kwargs: bool = False) -> Callable[[Type[T]], Type[T]]: ...
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def strict(cls: Type[T] | None = None, *, accept_kwargs: bool = False) -> Type[T] | Callable[[Type[T]], Type[T]]:
|
| 57 |
+
"""
|
| 58 |
+
Decorator to add strict validation to a dataclass.
|
| 59 |
+
|
| 60 |
+
This decorator must be used on top of `@dataclass` to ensure IDEs and static typing tools
|
| 61 |
+
recognize the class as a dataclass.
|
| 62 |
+
|
| 63 |
+
Can be used with or without arguments:
|
| 64 |
+
- `@strict`
|
| 65 |
+
- `@strict(accept_kwargs=True)`
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
cls:
|
| 69 |
+
The class to convert to a strict dataclass.
|
| 70 |
+
accept_kwargs (`bool`, *optional*):
|
| 71 |
+
If True, allows arbitrary keyword arguments in `__init__`. Defaults to False.
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
The enhanced dataclass with strict validation on field assignment.
|
| 75 |
+
|
| 76 |
+
Example:
|
| 77 |
+
```py
|
| 78 |
+
>>> from dataclasses import dataclass
|
| 79 |
+
>>> from huggingface_hub.dataclasses import as_validated_field, strict, validated_field
|
| 80 |
+
|
| 81 |
+
>>> @as_validated_field
|
| 82 |
+
>>> def positive_int(value: int):
|
| 83 |
+
... if not value >= 0:
|
| 84 |
+
... raise ValueError(f"Value must be positive, got {value}")
|
| 85 |
+
|
| 86 |
+
>>> @strict(accept_kwargs=True)
|
| 87 |
+
... @dataclass
|
| 88 |
+
... class User:
|
| 89 |
+
... name: str
|
| 90 |
+
... age: int = positive_int(default=10)
|
| 91 |
+
|
| 92 |
+
# Initialize
|
| 93 |
+
>>> User(name="John")
|
| 94 |
+
User(name='John', age=10)
|
| 95 |
+
|
| 96 |
+
# Extra kwargs are accepted
|
| 97 |
+
>>> User(name="John", age=30, lastname="Doe")
|
| 98 |
+
User(name='John', age=30, *lastname='Doe')
|
| 99 |
+
|
| 100 |
+
# Invalid type => raises
|
| 101 |
+
>>> User(name="John", age="30")
|
| 102 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 103 |
+
TypeError: Field 'age' expected int, got str (value: '30')
|
| 104 |
+
|
| 105 |
+
# Invalid value => raises
|
| 106 |
+
>>> User(name="John", age=-1)
|
| 107 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 108 |
+
ValueError: Value must be positive, got -1
|
| 109 |
+
```
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def wrap(cls: Type[T]) -> Type[T]:
|
| 113 |
+
if not hasattr(cls, "__dataclass_fields__"):
|
| 114 |
+
raise StrictDataclassDefinitionError(
|
| 115 |
+
f"Class '{cls.__name__}' must be a dataclass before applying @strict."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# List and store validators
|
| 119 |
+
field_validators: dict[str, list[Validator_T]] = {}
|
| 120 |
+
for f in fields(cls): # type: ignore [arg-type]
|
| 121 |
+
validators = []
|
| 122 |
+
validators.append(_create_type_validator(f))
|
| 123 |
+
custom_validator = f.metadata.get("validator")
|
| 124 |
+
if custom_validator is not None:
|
| 125 |
+
if not isinstance(custom_validator, list):
|
| 126 |
+
custom_validator = [custom_validator]
|
| 127 |
+
for validator in custom_validator:
|
| 128 |
+
if not _is_validator(validator):
|
| 129 |
+
raise StrictDataclassDefinitionError(
|
| 130 |
+
f"Invalid validator for field '{f.name}': {validator}. Must be a callable taking a single argument."
|
| 131 |
+
)
|
| 132 |
+
validators.extend(custom_validator)
|
| 133 |
+
field_validators[f.name] = validators
|
| 134 |
+
cls.__validators__ = field_validators # type: ignore
|
| 135 |
+
|
| 136 |
+
# Override __setattr__ to validate fields on assignment
|
| 137 |
+
original_setattr = cls.__setattr__
|
| 138 |
+
|
| 139 |
+
def __strict_setattr__(self: Any, name: str, value: Any) -> None:
|
| 140 |
+
"""Custom __setattr__ method for strict dataclasses."""
|
| 141 |
+
# Run all validators
|
| 142 |
+
for validator in self.__validators__.get(name, []):
|
| 143 |
+
try:
|
| 144 |
+
validator(value)
|
| 145 |
+
except (ValueError, TypeError) as e:
|
| 146 |
+
raise StrictDataclassFieldValidationError(field=name, cause=e) from e
|
| 147 |
+
|
| 148 |
+
# If validation passed, set the attribute
|
| 149 |
+
original_setattr(self, name, value)
|
| 150 |
+
|
| 151 |
+
cls.__setattr__ = __strict_setattr__ # type: ignore
|
| 152 |
+
|
| 153 |
+
if accept_kwargs:
|
| 154 |
+
# (optional) Override __init__ to accept arbitrary keyword arguments
|
| 155 |
+
original_init = cls.__init__
|
| 156 |
+
|
| 157 |
+
@wraps(original_init)
|
| 158 |
+
def __init__(self, *args, **kwargs: Any) -> None:
|
| 159 |
+
# Extract only the fields that are part of the dataclass
|
| 160 |
+
dataclass_fields = {f.name for f in fields(cls)} # type: ignore [arg-type]
|
| 161 |
+
standard_kwargs = {k: v for k, v in kwargs.items() if k in dataclass_fields}
|
| 162 |
+
|
| 163 |
+
# User shouldn't define custom `__init__` when `accepts_kwargs`, and instead
|
| 164 |
+
# are advised to move field manipulation to `__post_init__` (e.g., derive new field from existing ones)
|
| 165 |
+
# We need to call bare `__init__` here without `__post_init__` but the``original_init`` would call
|
| 166 |
+
# post-init right away with no kwargs.
|
| 167 |
+
if len(args) > 0:
|
| 168 |
+
raise ValueError(
|
| 169 |
+
f"When `accept_kwargs=True`, {cls.__name__} accepts only keyword arguments, "
|
| 170 |
+
f"but found `{len(args)}` positional args."
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
for f in fields(cls): # type: ignore
|
| 174 |
+
if f.name in standard_kwargs:
|
| 175 |
+
setattr(self, f.name, standard_kwargs[f.name])
|
| 176 |
+
elif f.default is not MISSING:
|
| 177 |
+
setattr(self, f.name, f.default)
|
| 178 |
+
elif f.default_factory is not MISSING:
|
| 179 |
+
setattr(self, f.name, f.default_factory())
|
| 180 |
+
else:
|
| 181 |
+
raise TypeError(f"Missing required field - '{f.name}'")
|
| 182 |
+
|
| 183 |
+
# Pass any additional kwargs to `__post_init__` and let the object
|
| 184 |
+
# decide whether to set the attr or use for different purposes (e.g. BC checks)
|
| 185 |
+
additional_kwargs = {}
|
| 186 |
+
for name, value in kwargs.items():
|
| 187 |
+
if name not in dataclass_fields:
|
| 188 |
+
additional_kwargs[name] = value
|
| 189 |
+
|
| 190 |
+
self.__post_init__(**additional_kwargs)
|
| 191 |
+
|
| 192 |
+
cls.__init__ = __init__ # type: ignore
|
| 193 |
+
|
| 194 |
+
# Define a default __post_init__ if not defined
|
| 195 |
+
if not hasattr(cls, "__post_init__"):
|
| 196 |
+
|
| 197 |
+
def __post_init__(self, **kwargs: Any) -> None:
|
| 198 |
+
"""Default __post_init__ to accept additional kwargs."""
|
| 199 |
+
for name, value in kwargs.items():
|
| 200 |
+
setattr(self, name, value)
|
| 201 |
+
|
| 202 |
+
cls.__post_init__ = __post_init__ # type: ignore
|
| 203 |
+
|
| 204 |
+
# (optional) Override __repr__ to include additional kwargs
|
| 205 |
+
original_repr = cls.__repr__
|
| 206 |
+
|
| 207 |
+
@wraps(original_repr)
|
| 208 |
+
def __repr__(self) -> str:
|
| 209 |
+
# Call the original __repr__ to get the standard fields
|
| 210 |
+
standard_repr = original_repr(self)
|
| 211 |
+
|
| 212 |
+
# Get additional kwargs
|
| 213 |
+
additional_kwargs = [
|
| 214 |
+
# add a '*' in front of additional kwargs to let the user know they are not part of the dataclass
|
| 215 |
+
f"*{k}={v!r}"
|
| 216 |
+
for k, v in self.__dict__.items()
|
| 217 |
+
if k not in cls.__dataclass_fields__ # type: ignore [attr-defined]
|
| 218 |
+
]
|
| 219 |
+
additional_repr = ", ".join(additional_kwargs)
|
| 220 |
+
|
| 221 |
+
# Combine both representations
|
| 222 |
+
return f"{standard_repr[:-1]}, {additional_repr})" if additional_kwargs else standard_repr
|
| 223 |
+
|
| 224 |
+
if cls.__dataclass_params__.repr is True: # type: ignore [attr-defined]
|
| 225 |
+
cls.__repr__ = __repr__ # type: ignore
|
| 226 |
+
|
| 227 |
+
# List all public methods starting with `validate_` => class validators.
|
| 228 |
+
class_validators = []
|
| 229 |
+
|
| 230 |
+
for name in dir(cls):
|
| 231 |
+
if not name.startswith("validate_"):
|
| 232 |
+
continue
|
| 233 |
+
method = getattr(cls, name)
|
| 234 |
+
if not callable(method):
|
| 235 |
+
continue
|
| 236 |
+
if len(inspect.signature(method).parameters) != 1:
|
| 237 |
+
raise StrictDataclassDefinitionError(
|
| 238 |
+
f"Class '{cls.__name__}' has a class validator '{name}' that takes more than one argument."
|
| 239 |
+
" Class validators must take only 'self' as an argument. Methods starting with 'validate_'"
|
| 240 |
+
" are considered to be class validators."
|
| 241 |
+
)
|
| 242 |
+
class_validators.append(method)
|
| 243 |
+
|
| 244 |
+
cls.__class_validators__ = class_validators # type: ignore
|
| 245 |
+
|
| 246 |
+
# Add `validate` method to the class, but first check if it already exists
|
| 247 |
+
def validate(self: T) -> None:
|
| 248 |
+
"""Run class validators on the instance."""
|
| 249 |
+
for validator in cls.__class_validators__: # type: ignore [attr-defined]
|
| 250 |
+
try:
|
| 251 |
+
validator(self)
|
| 252 |
+
except (ValueError, TypeError) as e:
|
| 253 |
+
raise StrictDataclassClassValidationError(validator=validator.__name__, cause=e) from e
|
| 254 |
+
|
| 255 |
+
# Hack to be able to raise if `.validate()` already exists except if it was created by this decorator on a parent class
|
| 256 |
+
# (in which case we just override it)
|
| 257 |
+
validate.__is_defined_by_strict_decorator__ = True # type: ignore [attr-defined]
|
| 258 |
+
|
| 259 |
+
if hasattr(cls, "validate"):
|
| 260 |
+
if not getattr(cls.validate, "__is_defined_by_strict_decorator__", False): # type: ignore [attr-defined]
|
| 261 |
+
raise StrictDataclassDefinitionError(
|
| 262 |
+
f"Class '{cls.__name__}' already implements a method called 'validate'."
|
| 263 |
+
" This method name is reserved when using the @strict decorator on a dataclass."
|
| 264 |
+
" If you want to keep your own method, please rename it."
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
cls.validate = validate # type: ignore
|
| 268 |
+
|
| 269 |
+
# Run class validators after initialization
|
| 270 |
+
initial_init = cls.__init__
|
| 271 |
+
|
| 272 |
+
@wraps(initial_init)
|
| 273 |
+
def init_with_validate(self, *args, **kwargs) -> None:
|
| 274 |
+
"""Run class validators after initialization."""
|
| 275 |
+
initial_init(self, *args, **kwargs) # type: ignore [call-arg]
|
| 276 |
+
cls.validate(self) # type: ignore [attr-defined]
|
| 277 |
+
|
| 278 |
+
setattr(cls, "__init__", init_with_validate)
|
| 279 |
+
|
| 280 |
+
return cls
|
| 281 |
+
|
| 282 |
+
# Return wrapped class or the decorator itself
|
| 283 |
+
return wrap(cls) if cls is not None else wrap
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def validate_typed_dict(schema: type[TypedDictType], data: dict) -> None:
|
| 287 |
+
"""
|
| 288 |
+
Validate that a dictionary conforms to the types defined in a TypedDict class.
|
| 289 |
+
|
| 290 |
+
Under the hood, the typed dict is converted to a strict dataclass and validated using the `@strict` decorator.
|
| 291 |
+
|
| 292 |
+
Args:
|
| 293 |
+
schema (`type[TypedDictType]`):
|
| 294 |
+
The TypedDict class defining the expected structure and types.
|
| 295 |
+
data (`dict`):
|
| 296 |
+
The dictionary to validate.
|
| 297 |
+
|
| 298 |
+
Raises:
|
| 299 |
+
`StrictDataclassFieldValidationError`:
|
| 300 |
+
If any field in the dictionary does not conform to the expected type.
|
| 301 |
+
|
| 302 |
+
Example:
|
| 303 |
+
```py
|
| 304 |
+
>>> from typing import Annotated, TypedDict
|
| 305 |
+
>>> from huggingface_hub.dataclasses import validate_typed_dict
|
| 306 |
+
|
| 307 |
+
>>> def positive_int(value: int):
|
| 308 |
+
... if not value >= 0:
|
| 309 |
+
... raise ValueError(f"Value must be positive, got {value}")
|
| 310 |
+
|
| 311 |
+
>>> class User(TypedDict):
|
| 312 |
+
... name: str
|
| 313 |
+
... age: Annotated[int, positive_int]
|
| 314 |
+
|
| 315 |
+
>>> # Valid data
|
| 316 |
+
>>> validate_typed_dict(User, {"name": "John", "age": 30})
|
| 317 |
+
|
| 318 |
+
>>> # Invalid type for age
|
| 319 |
+
>>> validate_typed_dict(User, {"name": "John", "age": "30"})
|
| 320 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 321 |
+
TypeError: Field 'age' expected int, got str (value: '30')
|
| 322 |
+
|
| 323 |
+
>>> # Invalid value for age
|
| 324 |
+
>>> validate_typed_dict(User, {"name": "John", "age": -1})
|
| 325 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 326 |
+
ValueError: Value must be positive, got -1
|
| 327 |
+
```
|
| 328 |
+
"""
|
| 329 |
+
# Convert typed dict to dataclass
|
| 330 |
+
strict_cls = _build_strict_cls_from_typed_dict(schema)
|
| 331 |
+
|
| 332 |
+
# Validate the data by instantiating the strict dataclass
|
| 333 |
+
strict_cls(**data) # will raise if validation fails
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@lru_cache
|
| 337 |
+
def _build_strict_cls_from_typed_dict(schema: type[TypedDictType]) -> Type:
|
| 338 |
+
# Extract type hints from the TypedDict class
|
| 339 |
+
type_hints = _get_typed_dict_annotations(schema)
|
| 340 |
+
|
| 341 |
+
# If the TypedDict is not total, wrap fields as NotRequired (unless explicitly Required or NotRequired)
|
| 342 |
+
if not getattr(schema, "__total__", True):
|
| 343 |
+
for key, value in type_hints.items():
|
| 344 |
+
origin = get_origin(value)
|
| 345 |
+
|
| 346 |
+
if origin is Annotated:
|
| 347 |
+
base, *meta = get_args(value)
|
| 348 |
+
if not _is_required_or_notrequired(base):
|
| 349 |
+
base = NotRequired[base]
|
| 350 |
+
type_hints[key] = Annotated[tuple([base] + list(meta))] # type: ignore
|
| 351 |
+
elif not _is_required_or_notrequired(value):
|
| 352 |
+
type_hints[key] = NotRequired[value]
|
| 353 |
+
|
| 354 |
+
# Convert type hints to dataclass fields
|
| 355 |
+
fields = []
|
| 356 |
+
for key, value in type_hints.items():
|
| 357 |
+
if get_origin(value) is Annotated:
|
| 358 |
+
base, *meta = get_args(value)
|
| 359 |
+
fields.append((key, base, field(default=_TYPED_DICT_DEFAULT_VALUE, metadata={"validator": meta[0]})))
|
| 360 |
+
else:
|
| 361 |
+
fields.append((key, value, field(default=_TYPED_DICT_DEFAULT_VALUE)))
|
| 362 |
+
|
| 363 |
+
# Create a strict dataclass from the TypedDict fields
|
| 364 |
+
return strict(make_dataclass(schema.__name__, fields))
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _get_typed_dict_annotations(schema: type[TypedDictType]) -> dict[str, Any]:
|
| 368 |
+
"""Extract type annotations from a TypedDict class."""
|
| 369 |
+
try:
|
| 370 |
+
# Available in Python 3.14+
|
| 371 |
+
import annotationlib
|
| 372 |
+
|
| 373 |
+
return annotationlib.get_annotations(schema)
|
| 374 |
+
except ImportError:
|
| 375 |
+
return {
|
| 376 |
+
# We do not use `get_type_hints` here to avoid evaluating ForwardRefs (which might fail).
|
| 377 |
+
# ForwardRefs are not validated by @strict anyway.
|
| 378 |
+
name: value if value is not None else type(None)
|
| 379 |
+
for name, value in schema.__dict__.get("__annotations__", {}).items()
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def validated_field(
|
| 384 |
+
validator: list[Validator_T] | Validator_T,
|
| 385 |
+
default: Any | _MISSING_TYPE = MISSING,
|
| 386 |
+
default_factory: Callable[[], Any] | _MISSING_TYPE = MISSING,
|
| 387 |
+
init: bool = True,
|
| 388 |
+
repr: bool = True,
|
| 389 |
+
hash: bool | None = None,
|
| 390 |
+
compare: bool = True,
|
| 391 |
+
metadata: dict | None = None,
|
| 392 |
+
**kwargs: Any,
|
| 393 |
+
) -> Any:
|
| 394 |
+
"""
|
| 395 |
+
Create a dataclass field with a custom validator.
|
| 396 |
+
|
| 397 |
+
Useful to apply several checks to a field. If only applying one rule, check out the [`as_validated_field`] decorator.
|
| 398 |
+
|
| 399 |
+
Args:
|
| 400 |
+
validator (`Callable` or `list[Callable]`):
|
| 401 |
+
A method that takes a value as input and raises ValueError/TypeError if the value is invalid.
|
| 402 |
+
Can be a list of validators to apply multiple checks.
|
| 403 |
+
**kwargs:
|
| 404 |
+
Additional arguments to pass to `dataclasses.field()`.
|
| 405 |
+
|
| 406 |
+
Returns:
|
| 407 |
+
A field with the validator attached in metadata
|
| 408 |
+
"""
|
| 409 |
+
if not isinstance(validator, list):
|
| 410 |
+
validator = [validator]
|
| 411 |
+
if metadata is None:
|
| 412 |
+
metadata = {}
|
| 413 |
+
metadata["validator"] = validator
|
| 414 |
+
return field( # type: ignore
|
| 415 |
+
default=default, # type: ignore [arg-type]
|
| 416 |
+
default_factory=default_factory, # type: ignore [arg-type]
|
| 417 |
+
init=init,
|
| 418 |
+
repr=repr,
|
| 419 |
+
hash=hash,
|
| 420 |
+
compare=compare,
|
| 421 |
+
metadata=metadata,
|
| 422 |
+
**kwargs,
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def as_validated_field(validator: Validator_T):
|
| 427 |
+
"""
|
| 428 |
+
Decorates a validator function as a [`validated_field`] (i.e. a dataclass field with a custom validator).
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
validator (`Callable`):
|
| 432 |
+
A method that takes a value as input and raises ValueError/TypeError if the value is invalid.
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
def _inner(
|
| 436 |
+
default: Any | _MISSING_TYPE = MISSING,
|
| 437 |
+
default_factory: Callable[[], Any] | _MISSING_TYPE = MISSING,
|
| 438 |
+
init: bool = True,
|
| 439 |
+
repr: bool = True,
|
| 440 |
+
hash: bool | None = None,
|
| 441 |
+
compare: bool = True,
|
| 442 |
+
metadata: dict | None = None,
|
| 443 |
+
**kwargs: Any,
|
| 444 |
+
):
|
| 445 |
+
return validated_field(
|
| 446 |
+
validator,
|
| 447 |
+
default=default,
|
| 448 |
+
default_factory=default_factory,
|
| 449 |
+
init=init,
|
| 450 |
+
repr=repr,
|
| 451 |
+
hash=hash,
|
| 452 |
+
compare=compare,
|
| 453 |
+
metadata=metadata,
|
| 454 |
+
**kwargs,
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
return _inner
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def type_validator(name: str, value: Any, expected_type: Any) -> None:
|
| 461 |
+
"""Validate that 'value' matches 'expected_type'."""
|
| 462 |
+
origin = get_origin(expected_type)
|
| 463 |
+
args = get_args(expected_type)
|
| 464 |
+
|
| 465 |
+
if expected_type is Any:
|
| 466 |
+
return
|
| 467 |
+
elif expected_type is None:
|
| 468 |
+
_validate_none(name, value)
|
| 469 |
+
elif validator := _BASIC_TYPE_VALIDATORS.get(origin):
|
| 470 |
+
validator(name, value, args)
|
| 471 |
+
elif isinstance(expected_type, type): # simple types
|
| 472 |
+
_validate_simple_type(name, value, expected_type)
|
| 473 |
+
elif isinstance(expected_type, ForwardRef) or isinstance(expected_type, str):
|
| 474 |
+
return
|
| 475 |
+
elif origin is Required:
|
| 476 |
+
if value is _TYPED_DICT_DEFAULT_VALUE:
|
| 477 |
+
raise TypeError(f"Field '{name}' is required but missing.")
|
| 478 |
+
type_validator(name, value, args[0])
|
| 479 |
+
elif origin is NotRequired:
|
| 480 |
+
if value is _TYPED_DICT_DEFAULT_VALUE:
|
| 481 |
+
return
|
| 482 |
+
type_validator(name, value, args[0])
|
| 483 |
+
else:
|
| 484 |
+
raise TypeError(f"Unsupported type for field '{name}': {expected_type}")
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _validate_none(name: str, value: Any) -> None:
|
| 488 |
+
"""Validate None type.
|
| 489 |
+
|
| 490 |
+
'None' is not a type, it's a special value. Type should be `NoneType` instead.
|
| 491 |
+
But in type annotations 'None' is accepted so we must support it.
|
| 492 |
+
"""
|
| 493 |
+
if value is not None:
|
| 494 |
+
raise TypeError(f"Field '{name}' expected None, got {type(value).__name__}")
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def _validate_union(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 498 |
+
"""Validate that value matches one of the types in a Union."""
|
| 499 |
+
errors = []
|
| 500 |
+
for t in args:
|
| 501 |
+
try:
|
| 502 |
+
type_validator(name, value, t)
|
| 503 |
+
return # Valid if any type matches
|
| 504 |
+
except TypeError as e:
|
| 505 |
+
errors.append(str(e))
|
| 506 |
+
|
| 507 |
+
raise TypeError(
|
| 508 |
+
f"Field '{name}' with value {repr(value)} doesn't match any type in {args}. Errors: {'; '.join(errors)}"
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _validate_literal(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 513 |
+
"""Validate Literal type."""
|
| 514 |
+
if isinstance(value, bool):
|
| 515 |
+
if value not in [arg for arg in args if isinstance(arg, bool)]:
|
| 516 |
+
raise TypeError(f"Field '{name}' expected one of {args}, got {value}")
|
| 517 |
+
elif isinstance(value, int):
|
| 518 |
+
if value not in [arg for arg in args if isinstance(arg, int) and not isinstance(arg, bool)]:
|
| 519 |
+
raise TypeError(f"Field '{name}' expected one of {args}, got {value}")
|
| 520 |
+
elif value not in args:
|
| 521 |
+
raise TypeError(f"Field '{name}' expected one of {args}, got {value}")
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def _validate_list(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 525 |
+
"""Validate list[T] type."""
|
| 526 |
+
if not isinstance(value, list):
|
| 527 |
+
raise TypeError(f"Field '{name}' expected a list, got {type(value).__name__}")
|
| 528 |
+
|
| 529 |
+
# Validate each item in the list
|
| 530 |
+
item_type = args[0]
|
| 531 |
+
for i, item in enumerate(value):
|
| 532 |
+
try:
|
| 533 |
+
type_validator(f"{name}[{i}]", item, item_type)
|
| 534 |
+
except TypeError as e:
|
| 535 |
+
raise TypeError(f"Invalid item at index {i} in list '{name}'") from e
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def _validate_dict(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 539 |
+
"""Validate dict[K, V] type."""
|
| 540 |
+
if not isinstance(value, dict):
|
| 541 |
+
raise TypeError(f"Field '{name}' expected a dict, got {type(value).__name__}")
|
| 542 |
+
|
| 543 |
+
# Validate keys and values
|
| 544 |
+
key_type, value_type = args
|
| 545 |
+
for k, v in value.items():
|
| 546 |
+
try:
|
| 547 |
+
type_validator(f"{name}.key", k, key_type)
|
| 548 |
+
type_validator(f"{name}[{k!r}]", v, value_type)
|
| 549 |
+
except TypeError as e:
|
| 550 |
+
raise TypeError(f"Invalid key or value in dict '{name}'") from e
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def _validate_tuple(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 554 |
+
"""Validate Tuple type."""
|
| 555 |
+
if not isinstance(value, tuple):
|
| 556 |
+
raise TypeError(f"Field '{name}' expected a tuple, got {type(value).__name__}")
|
| 557 |
+
|
| 558 |
+
# Handle variable-length tuples: tuple[T, ...]
|
| 559 |
+
if len(args) == 2 and args[1] is Ellipsis:
|
| 560 |
+
for i, item in enumerate(value):
|
| 561 |
+
try:
|
| 562 |
+
type_validator(f"{name}[{i}]", item, args[0])
|
| 563 |
+
except TypeError as e:
|
| 564 |
+
raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e
|
| 565 |
+
# Handle fixed-length tuples: tuple[T1, T2, ...]
|
| 566 |
+
elif len(args) != len(value):
|
| 567 |
+
raise TypeError(f"Field '{name}' expected a tuple of length {len(args)}, got {len(value)}")
|
| 568 |
+
else:
|
| 569 |
+
for i, (item, expected) in enumerate(zip(value, args)):
|
| 570 |
+
try:
|
| 571 |
+
type_validator(f"{name}[{i}]", item, expected)
|
| 572 |
+
except TypeError as e:
|
| 573 |
+
raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def _validate_set(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 577 |
+
"""Validate set[T] type."""
|
| 578 |
+
if not isinstance(value, set):
|
| 579 |
+
raise TypeError(f"Field '{name}' expected a set, got {type(value).__name__}")
|
| 580 |
+
|
| 581 |
+
# Validate each item in the set
|
| 582 |
+
item_type = args[0]
|
| 583 |
+
for i, item in enumerate(value):
|
| 584 |
+
try:
|
| 585 |
+
type_validator(f"{name} item", item, item_type)
|
| 586 |
+
except TypeError as e:
|
| 587 |
+
raise TypeError(f"Invalid item in set '{name}'") from e
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def _validate_sequence(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 591 |
+
"""Validate Sequence or Sequence[T] type."""
|
| 592 |
+
if not isinstance(value, collections.abc.Sequence):
|
| 593 |
+
raise TypeError(f"Field '{name}' expected a Sequence, got {type(value).__name__}")
|
| 594 |
+
|
| 595 |
+
# If no type argument is provided (i.e., just `Sequence`), skip item validation
|
| 596 |
+
if not args:
|
| 597 |
+
return
|
| 598 |
+
|
| 599 |
+
# Validate each item in the sequence
|
| 600 |
+
item_type = args[0]
|
| 601 |
+
for i, item in enumerate(value):
|
| 602 |
+
try:
|
| 603 |
+
type_validator(f"{name}[{i}]", item, item_type)
|
| 604 |
+
except TypeError as e:
|
| 605 |
+
raise TypeError(f"Invalid item at index {i} in sequence '{name}'") from e
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def _validate_simple_type(name: str, value: Any, expected_type: type) -> None:
|
| 609 |
+
"""Validate simple type (int, str, etc.)."""
|
| 610 |
+
if expected_type is int and isinstance(value, bool):
|
| 611 |
+
raise TypeError(
|
| 612 |
+
f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})"
|
| 613 |
+
)
|
| 614 |
+
if not isinstance(value, expected_type):
|
| 615 |
+
raise TypeError(
|
| 616 |
+
f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})"
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def _create_type_validator(field: Field) -> Validator_T:
|
| 621 |
+
"""Create a type validator function for a field."""
|
| 622 |
+
# Hacky: we cannot use a lambda here because of reference issues
|
| 623 |
+
|
| 624 |
+
def validator(value: Any) -> None:
|
| 625 |
+
type_validator(field.name, value, field.type)
|
| 626 |
+
|
| 627 |
+
return validator
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def _is_validator(validator: Any) -> bool:
|
| 631 |
+
"""Check if a function is a validator.
|
| 632 |
+
|
| 633 |
+
A validator is a Callable that can be called with a single positional argument.
|
| 634 |
+
The validator can have more arguments with default values.
|
| 635 |
+
|
| 636 |
+
Basically, returns True if `validator(value)` is possible.
|
| 637 |
+
"""
|
| 638 |
+
if not callable(validator):
|
| 639 |
+
return False
|
| 640 |
+
|
| 641 |
+
signature = inspect.signature(validator)
|
| 642 |
+
parameters = list(signature.parameters.values())
|
| 643 |
+
if len(parameters) == 0:
|
| 644 |
+
return False
|
| 645 |
+
if parameters[0].kind not in (
|
| 646 |
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 647 |
+
inspect.Parameter.POSITIONAL_ONLY,
|
| 648 |
+
inspect.Parameter.VAR_POSITIONAL,
|
| 649 |
+
):
|
| 650 |
+
return False
|
| 651 |
+
for parameter in parameters[1:]:
|
| 652 |
+
if parameter.default == inspect.Parameter.empty:
|
| 653 |
+
return False
|
| 654 |
+
return True
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _is_required_or_notrequired(type_hint: Any) -> bool:
|
| 658 |
+
"""Helper to check if a type is Required/NotRequired."""
|
| 659 |
+
return type_hint in (Required, NotRequired) or (get_origin(type_hint) in (Required, NotRequired))
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
_BASIC_TYPE_VALIDATORS: dict[Any, Callable[[str, Any, tuple[Any, ...]], None]] = {
|
| 663 |
+
Union: _validate_union,
|
| 664 |
+
Literal: _validate_literal,
|
| 665 |
+
list: _validate_list,
|
| 666 |
+
dict: _validate_dict,
|
| 667 |
+
tuple: _validate_tuple,
|
| 668 |
+
set: _validate_set,
|
| 669 |
+
collections.abc.Sequence: _validate_sequence,
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
# TODO: make it first class citizen when bumping to Python 3.10+
|
| 673 |
+
_BASIC_TYPE_VALIDATORS[types.UnionType] = _validate_union # x | y syntax, available only Python 3.10+
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
__all__ = [
|
| 677 |
+
"strict",
|
| 678 |
+
"validate_typed_dict",
|
| 679 |
+
"validated_field",
|
| 680 |
+
"Validator_T",
|
| 681 |
+
"StrictDataclassClassValidationError",
|
| 682 |
+
"StrictDataclassDefinitionError",
|
| 683 |
+
"StrictDataclassFieldValidationError",
|
| 684 |
+
]
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/errors.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contains all custom errors."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from httpx import HTTPError, Response
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# CACHE ERRORS
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CacheNotFound(Exception):
|
| 12 |
+
"""Exception thrown when the Huggingface cache is not found."""
|
| 13 |
+
|
| 14 |
+
cache_dir: str | Path
|
| 15 |
+
|
| 16 |
+
def __init__(self, msg: str, cache_dir: str | Path, *args, **kwargs):
|
| 17 |
+
super().__init__(msg, *args, **kwargs)
|
| 18 |
+
self.cache_dir = cache_dir
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class CorruptedCacheException(Exception):
|
| 22 |
+
"""Exception for any unexpected structure in the Huggingface cache-system."""
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# HEADERS ERRORS
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class LocalTokenNotFoundError(EnvironmentError):
|
| 29 |
+
"""Raised if local token is required but not found."""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# HTTP ERRORS
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class OfflineModeIsEnabled(ConnectionError):
|
| 36 |
+
"""Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class HfHubHTTPError(HTTPError, OSError):
|
| 40 |
+
"""
|
| 41 |
+
HTTPError to inherit from for any custom HTTP Error raised in HF Hub.
|
| 42 |
+
|
| 43 |
+
Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is
|
| 44 |
+
sent back by the server, it will be added to the error message.
|
| 45 |
+
|
| 46 |
+
Added details:
|
| 47 |
+
- Request ID sourced from headers in order of precedence: "X-Request-Id", "X-Amzn-Trace-Id", "X-Amz-Cf-Id".
|
| 48 |
+
- Server error message from the header "X-Error-Message".
|
| 49 |
+
- Server error message if we can found one in the response body.
|
| 50 |
+
|
| 51 |
+
Example:
|
| 52 |
+
```py
|
| 53 |
+
import httpx
|
| 54 |
+
from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
|
| 55 |
+
|
| 56 |
+
response = get_session().post(...)
|
| 57 |
+
try:
|
| 58 |
+
hf_raise_for_status(response)
|
| 59 |
+
except HfHubHTTPError as e:
|
| 60 |
+
print(str(e)) # formatted message
|
| 61 |
+
e.request_id, e.server_message # details returned by server
|
| 62 |
+
|
| 63 |
+
# Complete the error message with additional information once it's raised
|
| 64 |
+
e.append_to_message("\n`create_commit` expects the repository to exist.")
|
| 65 |
+
raise
|
| 66 |
+
```
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(
|
| 70 |
+
self,
|
| 71 |
+
message: str,
|
| 72 |
+
*,
|
| 73 |
+
response: Response,
|
| 74 |
+
server_message: str | None = None,
|
| 75 |
+
):
|
| 76 |
+
self.request_id = (
|
| 77 |
+
response.headers.get("x-request-id")
|
| 78 |
+
or response.headers.get("X-Amzn-Trace-Id")
|
| 79 |
+
or response.headers.get("x-amz-cf-id")
|
| 80 |
+
)
|
| 81 |
+
self.server_message = server_message
|
| 82 |
+
self.response = response
|
| 83 |
+
self.request = response.request
|
| 84 |
+
super().__init__(message)
|
| 85 |
+
|
| 86 |
+
def append_to_message(self, additional_message: str) -> None:
|
| 87 |
+
"""Append additional information to the `HfHubHTTPError` initial message."""
|
| 88 |
+
self.args = (self.args[0] + additional_message,) + self.args[1:]
|
| 89 |
+
|
| 90 |
+
@classmethod
|
| 91 |
+
def _reconstruct_hf_hub_http_error(
|
| 92 |
+
cls, message: str, response: Response, server_message: str | None
|
| 93 |
+
) -> "HfHubHTTPError":
|
| 94 |
+
return cls(message, response=response, server_message=server_message)
|
| 95 |
+
|
| 96 |
+
def __reduce_ex__(self, protocol):
|
| 97 |
+
"""Fix pickling of Exception subclass with kwargs. We need to override __reduce_ex__ of the parent class"""
|
| 98 |
+
return (self.__class__._reconstruct_hf_hub_http_error, (str(self), self.response, self.server_message))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# INFERENCE CLIENT ERRORS
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class InferenceTimeoutError(HTTPError, TimeoutError):
|
| 105 |
+
"""Error raised when a model is unavailable or the request times out."""
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# INFERENCE ENDPOINT ERRORS
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class InferenceEndpointError(Exception):
|
| 112 |
+
"""Generic exception when dealing with Inference Endpoints."""
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):
|
| 116 |
+
"""Exception for timeouts while waiting for Inference Endpoint."""
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# SAFETENSORS ERRORS
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class SafetensorsParsingError(Exception):
|
| 123 |
+
"""Raised when failing to parse a safetensors file metadata.
|
| 124 |
+
|
| 125 |
+
This can be the case if the file is not a safetensors file or does not respect the specification.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class NotASafetensorsRepoError(Exception):
|
| 130 |
+
"""Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a
|
| 131 |
+
`model.safetensors.index.json` file.
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# TEXT GENERATION ERRORS
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class TextGenerationError(HTTPError):
|
| 139 |
+
"""Generic error raised if text-generation went wrong."""
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# Text Generation Inference Errors
|
| 143 |
+
class ValidationError(TextGenerationError):
|
| 144 |
+
"""Server-side validation error."""
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class GenerationError(TextGenerationError):
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class OverloadedError(TextGenerationError):
|
| 152 |
+
pass
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class IncompleteGenerationError(TextGenerationError):
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class UnknownError(TextGenerationError):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# VALIDATION ERRORS
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class HFValidationError(ValueError):
|
| 167 |
+
"""Generic exception thrown by `huggingface_hub` validators.
|
| 168 |
+
|
| 169 |
+
Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# FILE METADATA ERRORS
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class DryRunError(OSError):
|
| 177 |
+
"""Error triggered when a dry run is requested but cannot be performed (e.g. invalid repo)."""
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class FileMetadataError(OSError):
|
| 181 |
+
"""Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).
|
| 182 |
+
|
| 183 |
+
Inherits from `OSError` for backward compatibility.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# BUCKET ERRORS
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class BucketNotFoundError(HfHubHTTPError):
|
| 191 |
+
"""
|
| 192 |
+
Raised when trying to access a bucket that does not exist.
|
| 193 |
+
|
| 194 |
+
Attributes:
|
| 195 |
+
bucket_id (`str` or `None`):
|
| 196 |
+
The bucket id (namespace/name) that was not found, if it could be determined from the request URL.
|
| 197 |
+
|
| 198 |
+
Example:
|
| 199 |
+
|
| 200 |
+
```py
|
| 201 |
+
>>> from huggingface_hub import bucket_info
|
| 202 |
+
>>> bucket_info("<non_existent_bucket>")
|
| 203 |
+
(...)
|
| 204 |
+
huggingface_hub.errors.BucketNotFoundError: 404 Client Error. (Request ID: XXX)
|
| 205 |
+
|
| 206 |
+
Bucket Not Found for url: https://huggingface.co/api/buckets/namespace/name.
|
| 207 |
+
Please make sure you specified the correct bucket id (namespace/name).
|
| 208 |
+
If the bucket is private, make sure you are authenticated and your token has the required permissions.
|
| 209 |
+
```
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
bucket_id: str | None = None
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# REPOSITORY ERRORS
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class RepositoryNotFoundError(HfHubHTTPError):
|
| 219 |
+
"""
|
| 220 |
+
Raised when trying to access a hf.co URL with an invalid repository name, or
|
| 221 |
+
with a private repo name the user does not have access to.
|
| 222 |
+
|
| 223 |
+
Attributes:
|
| 224 |
+
repo_id (`str` or `None`):
|
| 225 |
+
The repo id that was not found, if it could be determined from the request URL.
|
| 226 |
+
repo_type (`str` or `None`):
|
| 227 |
+
The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
|
| 228 |
+
|
| 229 |
+
Example:
|
| 230 |
+
|
| 231 |
+
```py
|
| 232 |
+
>>> from huggingface_hub import model_info
|
| 233 |
+
>>> model_info("<non_existent_repository>")
|
| 234 |
+
(...)
|
| 235 |
+
huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
|
| 236 |
+
|
| 237 |
+
Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
|
| 238 |
+
Please make sure you specified the correct `repo_id` and `repo_type`.
|
| 239 |
+
If the repo is private, make sure you are authenticated and your token has the required permissions.
|
| 240 |
+
Invalid username or password.
|
| 241 |
+
```
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
repo_id: str | None = None
|
| 245 |
+
repo_type: str | None = None
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class GatedRepoError(RepositoryNotFoundError):
|
| 249 |
+
"""
|
| 250 |
+
Raised when trying to access a gated repository for which the user is not on the
|
| 251 |
+
authorized list.
|
| 252 |
+
|
| 253 |
+
Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.
|
| 254 |
+
|
| 255 |
+
Example:
|
| 256 |
+
|
| 257 |
+
```py
|
| 258 |
+
>>> from huggingface_hub import model_info
|
| 259 |
+
>>> model_info("<gated_repository>")
|
| 260 |
+
(...)
|
| 261 |
+
huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
|
| 262 |
+
|
| 263 |
+
Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
|
| 264 |
+
Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
|
| 265 |
+
Visit https://huggingface.co/ardent-figment/gated-model to ask for access.
|
| 266 |
+
```
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class DisabledRepoError(HfHubHTTPError):
|
| 271 |
+
"""
|
| 272 |
+
Raised when trying to access a repository that has been disabled by its author.
|
| 273 |
+
|
| 274 |
+
Example:
|
| 275 |
+
|
| 276 |
+
```py
|
| 277 |
+
>>> from huggingface_hub import dataset_info
|
| 278 |
+
>>> dataset_info("laion/laion-art")
|
| 279 |
+
(...)
|
| 280 |
+
huggingface_hub.errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)
|
| 281 |
+
|
| 282 |
+
Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.
|
| 283 |
+
Access to this resource is disabled.
|
| 284 |
+
```
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# REVISION ERROR
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class RevisionNotFoundError(HfHubHTTPError):
|
| 292 |
+
"""
|
| 293 |
+
Raised when trying to access a hf.co URL with a valid repository but an invalid
|
| 294 |
+
revision.
|
| 295 |
+
|
| 296 |
+
Attributes:
|
| 297 |
+
repo_id (`str` or `None`):
|
| 298 |
+
The repo id, if it could be determined from the request URL.
|
| 299 |
+
repo_type (`str` or `None`):
|
| 300 |
+
The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
|
| 301 |
+
|
| 302 |
+
Example:
|
| 303 |
+
|
| 304 |
+
```py
|
| 305 |
+
>>> from huggingface_hub import hf_hub_download
|
| 306 |
+
>>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
|
| 307 |
+
(...)
|
| 308 |
+
huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
|
| 309 |
+
|
| 310 |
+
Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.
|
| 311 |
+
```
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
repo_id: str | None = None
|
| 315 |
+
repo_type: str | None = None
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# ENTRY ERRORS
|
| 319 |
+
class EntryNotFoundError(Exception):
|
| 320 |
+
"""
|
| 321 |
+
Raised when entry not found, either locally or remotely.
|
| 322 |
+
|
| 323 |
+
Example:
|
| 324 |
+
|
| 325 |
+
```py
|
| 326 |
+
>>> from huggingface_hub import hf_hub_download
|
| 327 |
+
>>> hf_hub_download('bert-base-cased', '<non-existent-file>')
|
| 328 |
+
(...)
|
| 329 |
+
huggingface_hub.errors.RemoteEntryNotFoundError (...)
|
| 330 |
+
>>> hf_hub_download('bert-base-cased', '<non-existent-file>', local_files_only=True)
|
| 331 |
+
(...)
|
| 332 |
+
huggingface_hub.utils.errors.LocalEntryNotFoundError (...)
|
| 333 |
+
```
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class RemoteEntryNotFoundError(HfHubHTTPError, EntryNotFoundError):
|
| 338 |
+
"""
|
| 339 |
+
Raised when trying to access a hf.co URL with a valid repository and revision
|
| 340 |
+
but an invalid filename.
|
| 341 |
+
|
| 342 |
+
Attributes:
|
| 343 |
+
repo_id (`str` or `None`):
|
| 344 |
+
The repo id, if it could be determined from the request URL.
|
| 345 |
+
repo_type (`str` or `None`):
|
| 346 |
+
The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
|
| 347 |
+
|
| 348 |
+
Example:
|
| 349 |
+
|
| 350 |
+
```py
|
| 351 |
+
>>> from huggingface_hub import hf_hub_download
|
| 352 |
+
>>> hf_hub_download('bert-base-cased', '<non-existent-file>')
|
| 353 |
+
(...)
|
| 354 |
+
huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
|
| 355 |
+
|
| 356 |
+
Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.
|
| 357 |
+
```
|
| 358 |
+
"""
|
| 359 |
+
|
| 360 |
+
repo_id: str | None = None
|
| 361 |
+
repo_type: str | None = None
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class LocalEntryNotFoundError(FileNotFoundError, EntryNotFoundError):
|
| 365 |
+
"""
|
| 366 |
+
Raised when trying to access a file or snapshot that is not on the disk when network is
|
| 367 |
+
disabled or unavailable (connection issue). The entry may exist on the Hub.
|
| 368 |
+
|
| 369 |
+
Example:
|
| 370 |
+
|
| 371 |
+
```py
|
| 372 |
+
>>> from huggingface_hub import hf_hub_download
|
| 373 |
+
>>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
|
| 374 |
+
(...)
|
| 375 |
+
huggingface_hub.errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False.
|
| 376 |
+
```
|
| 377 |
+
"""
|
| 378 |
+
|
| 379 |
+
def __init__(self, message: str):
|
| 380 |
+
super().__init__(message)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
# REQUEST ERROR
|
| 384 |
+
class BadRequestError(HfHubHTTPError, ValueError):
|
| 385 |
+
"""
|
| 386 |
+
Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.
|
| 387 |
+
|
| 388 |
+
Example:
|
| 389 |
+
|
| 390 |
+
```py
|
| 391 |
+
>>> resp = httpx.post("hf.co/api/check", ...)
|
| 392 |
+
>>> hf_raise_for_status(resp, endpoint_name="check")
|
| 393 |
+
huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)
|
| 394 |
+
```
|
| 395 |
+
"""
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
# DDUF file format ERROR
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
class DDUFError(Exception):
|
| 402 |
+
"""Base exception for errors related to the DDUF format."""
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class DDUFCorruptedFileError(DDUFError):
|
| 406 |
+
"""Exception thrown when the DDUF file is corrupted."""
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
class DDUFExportError(DDUFError):
|
| 410 |
+
"""Base exception for errors during DDUF export."""
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
class DDUFInvalidEntryNameError(DDUFExportError):
|
| 414 |
+
"""Exception thrown when the entry name is invalid."""
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
# STRICT DATACLASSES ERRORS
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class StrictDataclassError(Exception):
|
| 421 |
+
"""Base exception for strict dataclasses."""
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class StrictDataclassDefinitionError(StrictDataclassError):
|
| 425 |
+
"""Exception thrown when a strict dataclass is defined incorrectly."""
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class StrictDataclassFieldValidationError(StrictDataclassError):
|
| 429 |
+
"""Exception thrown when a strict dataclass fails validation for a given field."""
|
| 430 |
+
|
| 431 |
+
def __init__(self, field: str, cause: Exception):
|
| 432 |
+
error_message = f"Validation error for field '{field}':"
|
| 433 |
+
error_message += f"\n {cause.__class__.__name__}: {cause}"
|
| 434 |
+
super().__init__(error_message)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class StrictDataclassClassValidationError(StrictDataclassError):
|
| 438 |
+
"""Exception thrown when a strict dataclass fails validation on a class validator."""
|
| 439 |
+
|
| 440 |
+
def __init__(self, validator: str, cause: Exception):
|
| 441 |
+
error_message = f"Class validation error for validator '{validator}':"
|
| 442 |
+
error_message += f"\n {cause.__class__.__name__}: {cause}"
|
| 443 |
+
super().__init__(error_message)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
# XET ERRORS
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class XetError(Exception):
|
| 450 |
+
"""Base exception for errors related to Xet Storage."""
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
class XetAuthorizationError(XetError):
|
| 454 |
+
"""Exception thrown when the user does not have the right authorization to use Xet Storage."""
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
class XetRefreshTokenError(XetError):
|
| 458 |
+
"""Exception thrown when the refresh token is invalid."""
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
class XetDownloadError(Exception):
|
| 462 |
+
"""Exception thrown when the download from Xet Storage fails."""
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# CLI ERRORS
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class CLIError(Exception):
|
| 469 |
+
"""CLI error with clean message (no traceback by default)."""
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class CLIExtension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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from pickle import DEFAULT_PROTOCOL, PicklingError
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from packaging import version
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import constants, snapshot_download
|
| 10 |
+
from huggingface_hub.hf_api import HfApi
|
| 11 |
+
from huggingface_hub.utils import (
|
| 12 |
+
SoftTemporaryDirectory,
|
| 13 |
+
get_fastai_version,
|
| 14 |
+
get_fastcore_version,
|
| 15 |
+
get_python_version,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from .utils import logging, validate_hf_hub_args
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _check_fastai_fastcore_versions(
|
| 25 |
+
fastai_min_version: str = "2.4",
|
| 26 |
+
fastcore_min_version: str = "1.3.27",
|
| 27 |
+
):
|
| 28 |
+
"""
|
| 29 |
+
Checks that the installed fastai and fastcore versions are compatible for pickle serialization.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
fastai_min_version (`str`, *optional*):
|
| 33 |
+
The minimum fastai version supported.
|
| 34 |
+
fastcore_min_version (`str`, *optional*):
|
| 35 |
+
The minimum fastcore version supported.
|
| 36 |
+
|
| 37 |
+
> [!TIP]
|
| 38 |
+
> Raises the following error:
|
| 39 |
+
>
|
| 40 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 41 |
+
> if the fastai or fastcore libraries are not available or are of an invalid version.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
if (get_fastcore_version() or get_fastai_version()) == "N/A":
|
| 45 |
+
raise ImportError(
|
| 46 |
+
f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are"
|
| 47 |
+
f" required. Currently using fastai=={get_fastai_version()} and"
|
| 48 |
+
f" fastcore=={get_fastcore_version()}."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
current_fastai_version = version.Version(get_fastai_version())
|
| 52 |
+
current_fastcore_version = version.Version(get_fastcore_version())
|
| 53 |
+
|
| 54 |
+
if current_fastai_version < version.Version(fastai_min_version):
|
| 55 |
+
raise ImportError(
|
| 56 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require a"
|
| 57 |
+
f" fastai>={fastai_min_version} version, but you are using fastai version"
|
| 58 |
+
f" {get_fastai_version()} which is incompatible. Upgrade with `pip install"
|
| 59 |
+
" fastai==2.5.6`."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if current_fastcore_version < version.Version(fastcore_min_version):
|
| 63 |
+
raise ImportError(
|
| 64 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require a"
|
| 65 |
+
f" fastcore>={fastcore_min_version} version, but you are using fastcore"
|
| 66 |
+
f" version {get_fastcore_version()} which is incompatible. Upgrade with"
|
| 67 |
+
" `pip install fastcore==1.3.27`."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _check_fastai_fastcore_pyproject_versions(
|
| 72 |
+
storage_folder: str,
|
| 73 |
+
fastai_min_version: str = "2.4",
|
| 74 |
+
fastcore_min_version: str = "1.3.27",
|
| 75 |
+
):
|
| 76 |
+
"""
|
| 77 |
+
Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions
|
| 78 |
+
that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist
|
| 79 |
+
or does not contain versions for fastai and fastcore, then it logs a warning.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
storage_folder (`str`):
|
| 83 |
+
Folder to look for the `pyproject.toml` file.
|
| 84 |
+
fastai_min_version (`str`, *optional*):
|
| 85 |
+
The minimum fastai version supported.
|
| 86 |
+
fastcore_min_version (`str`, *optional*):
|
| 87 |
+
The minimum fastcore version supported.
|
| 88 |
+
|
| 89 |
+
> [!TIP]
|
| 90 |
+
> Raises the following errors:
|
| 91 |
+
>
|
| 92 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 93 |
+
> if the `toml` module is not installed.
|
| 94 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 95 |
+
> if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
import toml
|
| 100 |
+
except ModuleNotFoundError:
|
| 101 |
+
raise ImportError(
|
| 102 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module."
|
| 103 |
+
" Install it with `pip install toml`."
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages.
|
| 107 |
+
if not os.path.isfile(f"{storage_folder}/pyproject.toml"):
|
| 108 |
+
logger.warning(
|
| 109 |
+
"There is no `pyproject.toml` in the repository that contains the fastai"
|
| 110 |
+
" `Learner`. The `pyproject.toml` would allow us to verify that your fastai"
|
| 111 |
+
" and fastcore versions are compatible with those of the model you want to"
|
| 112 |
+
" load."
|
| 113 |
+
)
|
| 114 |
+
return
|
| 115 |
+
pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml")
|
| 116 |
+
|
| 117 |
+
if "build-system" not in pyproject_toml.keys():
|
| 118 |
+
logger.warning(
|
| 119 |
+
"There is no `build-system` section in the pyproject.toml of the repository"
|
| 120 |
+
" that contains the fastai `Learner`. The `build-system` would allow us to"
|
| 121 |
+
" verify that your fastai and fastcore versions are compatible with those"
|
| 122 |
+
" of the model you want to load."
|
| 123 |
+
)
|
| 124 |
+
return
|
| 125 |
+
build_system_toml = pyproject_toml["build-system"]
|
| 126 |
+
|
| 127 |
+
if "requires" not in build_system_toml.keys():
|
| 128 |
+
logger.warning(
|
| 129 |
+
"There is no `requires` section in the pyproject.toml of the repository"
|
| 130 |
+
" that contains the fastai `Learner`. The `requires` would allow us to"
|
| 131 |
+
" verify that your fastai and fastcore versions are compatible with those"
|
| 132 |
+
" of the model you want to load."
|
| 133 |
+
)
|
| 134 |
+
return
|
| 135 |
+
package_versions = build_system_toml["requires"]
|
| 136 |
+
|
| 137 |
+
# Extracts contains fastai and fastcore versions from `pyproject.toml` if available.
|
| 138 |
+
# If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest.
|
| 139 |
+
fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")]
|
| 140 |
+
if len(fastai_packages) == 0:
|
| 141 |
+
logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.")
|
| 142 |
+
# fastai_version is an empty string if not specified
|
| 143 |
+
else:
|
| 144 |
+
fastai_version = str(fastai_packages[0]).partition("=")[2]
|
| 145 |
+
if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version):
|
| 146 |
+
raise ImportError(
|
| 147 |
+
"`from_pretrained_fastai` requires"
|
| 148 |
+
f" fastai>={fastai_min_version} version but the model to load uses"
|
| 149 |
+
f" {fastai_version} which is incompatible."
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")]
|
| 153 |
+
if len(fastcore_packages) == 0:
|
| 154 |
+
logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.")
|
| 155 |
+
# fastcore_version is an empty string if not specified
|
| 156 |
+
else:
|
| 157 |
+
fastcore_version = str(fastcore_packages[0]).partition("=")[2]
|
| 158 |
+
if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version):
|
| 159 |
+
raise ImportError(
|
| 160 |
+
"`from_pretrained_fastai` requires"
|
| 161 |
+
f" fastcore>={fastcore_min_version} version, but you are using fastcore"
|
| 162 |
+
f" version {fastcore_version} which is incompatible."
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
README_TEMPLATE = """---
|
| 167 |
+
tags:
|
| 168 |
+
- fastai
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
# Amazing!
|
| 172 |
+
|
| 173 |
+
🥳 Congratulations on hosting your fastai model on the Hugging Face Hub!
|
| 174 |
+
|
| 175 |
+
# Some next steps
|
| 176 |
+
1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))!
|
| 177 |
+
|
| 178 |
+
2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)).
|
| 179 |
+
|
| 180 |
+
3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)!
|
| 181 |
+
|
| 182 |
+
Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card.
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
---
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# Model card
|
| 189 |
+
|
| 190 |
+
## Model description
|
| 191 |
+
More information needed
|
| 192 |
+
|
| 193 |
+
## Intended uses & limitations
|
| 194 |
+
More information needed
|
| 195 |
+
|
| 196 |
+
## Training and evaluation data
|
| 197 |
+
More information needed
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
PYPROJECT_TEMPLATE = f"""[build-system]
|
| 201 |
+
requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]
|
| 202 |
+
build-backend = "setuptools.build_meta:__legacy__"
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _create_model_card(repo_dir: Path):
|
| 207 |
+
"""
|
| 208 |
+
Creates a model card for the repository.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
repo_dir (`Path`):
|
| 212 |
+
Directory where model card is created.
|
| 213 |
+
"""
|
| 214 |
+
readme_path = repo_dir / "README.md"
|
| 215 |
+
|
| 216 |
+
if not readme_path.exists():
|
| 217 |
+
with readme_path.open("w", encoding="utf-8") as f:
|
| 218 |
+
f.write(README_TEMPLATE)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _create_model_pyproject(repo_dir: Path):
|
| 222 |
+
"""
|
| 223 |
+
Creates a `pyproject.toml` for the repository.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
repo_dir (`Path`):
|
| 227 |
+
Directory where `pyproject.toml` is created.
|
| 228 |
+
"""
|
| 229 |
+
pyproject_path = repo_dir / "pyproject.toml"
|
| 230 |
+
|
| 231 |
+
if not pyproject_path.exists():
|
| 232 |
+
with pyproject_path.open("w", encoding="utf-8") as f:
|
| 233 |
+
f.write(PYPROJECT_TEMPLATE)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _save_pretrained_fastai(
|
| 237 |
+
learner,
|
| 238 |
+
save_directory: str | Path,
|
| 239 |
+
config: dict[str, Any] | None = None,
|
| 240 |
+
):
|
| 241 |
+
"""
|
| 242 |
+
Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
learner (`Learner`):
|
| 246 |
+
The `fastai.Learner` you'd like to save.
|
| 247 |
+
save_directory (`str` or `Path`):
|
| 248 |
+
Specific directory in which you want to save the fastai learner.
|
| 249 |
+
config (`dict`, *optional*):
|
| 250 |
+
Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'.
|
| 251 |
+
|
| 252 |
+
> [!TIP]
|
| 253 |
+
> Raises the following error:
|
| 254 |
+
>
|
| 255 |
+
> - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError)
|
| 256 |
+
> if the config file provided is not a dictionary.
|
| 257 |
+
"""
|
| 258 |
+
_check_fastai_fastcore_versions()
|
| 259 |
+
|
| 260 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 261 |
+
|
| 262 |
+
# if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE.
|
| 263 |
+
if config is not None:
|
| 264 |
+
if not isinstance(config, dict):
|
| 265 |
+
raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'")
|
| 266 |
+
path = os.path.join(save_directory, constants.CONFIG_NAME)
|
| 267 |
+
with open(path, "w") as f:
|
| 268 |
+
json.dump(config, f)
|
| 269 |
+
|
| 270 |
+
_create_model_card(Path(save_directory))
|
| 271 |
+
_create_model_pyproject(Path(save_directory))
|
| 272 |
+
|
| 273 |
+
# learner.export saves the model in `self.path`.
|
| 274 |
+
learner.path = Path(save_directory)
|
| 275 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 276 |
+
try:
|
| 277 |
+
learner.export(
|
| 278 |
+
fname="model.pkl",
|
| 279 |
+
pickle_protocol=DEFAULT_PROTOCOL,
|
| 280 |
+
)
|
| 281 |
+
except PicklingError:
|
| 282 |
+
raise PicklingError(
|
| 283 |
+
"You are using a lambda function, i.e., an anonymous function. `pickle`"
|
| 284 |
+
" cannot pickle function objects and requires that all functions have"
|
| 285 |
+
" names. One possible solution is to name the function."
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
@validate_hf_hub_args
|
| 290 |
+
def from_pretrained_fastai(
|
| 291 |
+
repo_id: str,
|
| 292 |
+
revision: str | None = None,
|
| 293 |
+
):
|
| 294 |
+
"""
|
| 295 |
+
Load pretrained fastai model from the Hub or from a local directory.
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
repo_id (`str`):
|
| 299 |
+
The location where the pickled fastai.Learner is. It can be either of the two:
|
| 300 |
+
- Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'.
|
| 301 |
+
You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`.
|
| 302 |
+
Revision is the specific model version to use. Since we use a git-based system for storing models and other
|
| 303 |
+
artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id.
|
| 304 |
+
- Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml
|
| 305 |
+
indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`.
|
| 306 |
+
revision (`str`, *optional*):
|
| 307 |
+
Revision at which the repo's files are downloaded. See documentation of `snapshot_download`.
|
| 308 |
+
|
| 309 |
+
Returns:
|
| 310 |
+
The `fastai.Learner` model in the `repo_id` repo.
|
| 311 |
+
"""
|
| 312 |
+
_check_fastai_fastcore_versions()
|
| 313 |
+
|
| 314 |
+
# Load the `repo_id` repo.
|
| 315 |
+
# `snapshot_download` returns the folder where the model was stored.
|
| 316 |
+
# `cache_dir` will be the default '/root/.cache/huggingface/hub'
|
| 317 |
+
if not os.path.isdir(repo_id):
|
| 318 |
+
storage_folder = snapshot_download(
|
| 319 |
+
repo_id=repo_id,
|
| 320 |
+
revision=revision,
|
| 321 |
+
library_name="fastai",
|
| 322 |
+
library_version=get_fastai_version(),
|
| 323 |
+
)
|
| 324 |
+
else:
|
| 325 |
+
storage_folder = repo_id
|
| 326 |
+
|
| 327 |
+
_check_fastai_fastcore_pyproject_versions(storage_folder)
|
| 328 |
+
|
| 329 |
+
from fastai.learner import load_learner # type: ignore
|
| 330 |
+
|
| 331 |
+
return load_learner(os.path.join(storage_folder, "model.pkl"))
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@validate_hf_hub_args
|
| 335 |
+
def push_to_hub_fastai(
|
| 336 |
+
learner,
|
| 337 |
+
*,
|
| 338 |
+
repo_id: str,
|
| 339 |
+
commit_message: str = "Push FastAI model using huggingface_hub.",
|
| 340 |
+
private: bool | None = None,
|
| 341 |
+
token: str | None = None,
|
| 342 |
+
config: dict | None = None,
|
| 343 |
+
branch: str | None = None,
|
| 344 |
+
create_pr: bool | None = None,
|
| 345 |
+
allow_patterns: list[str] | str | None = None,
|
| 346 |
+
ignore_patterns: list[str] | str | None = None,
|
| 347 |
+
delete_patterns: list[str] | str | None = None,
|
| 348 |
+
api_endpoint: str | None = None,
|
| 349 |
+
):
|
| 350 |
+
"""
|
| 351 |
+
Upload learner checkpoint files to the Hub.
|
| 352 |
+
|
| 353 |
+
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
|
| 354 |
+
`delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
|
| 355 |
+
details.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
learner (`Learner`):
|
| 359 |
+
The `fastai.Learner' you'd like to push to the Hub.
|
| 360 |
+
repo_id (`str`):
|
| 361 |
+
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').
|
| 362 |
+
commit_message (`str`, *optional*):
|
| 363 |
+
Message to commit while pushing. Will default to :obj:`"add model"`.
|
| 364 |
+
private (`bool`, *optional*):
|
| 365 |
+
Whether or not the repository created should be private.
|
| 366 |
+
If `None` (default), will default to been public except if the organization's default is private.
|
| 367 |
+
token (`str`, *optional*):
|
| 368 |
+
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.
|
| 369 |
+
config (`dict`, *optional*):
|
| 370 |
+
Configuration object to be saved alongside the model weights.
|
| 371 |
+
branch (`str`, *optional*):
|
| 372 |
+
The git branch on which to push the model. This defaults to
|
| 373 |
+
the default branch as specified in your repository, which
|
| 374 |
+
defaults to `"main"`.
|
| 375 |
+
create_pr (`boolean`, *optional*):
|
| 376 |
+
Whether or not to create a Pull Request from `branch` with that commit.
|
| 377 |
+
Defaults to `False`.
|
| 378 |
+
api_endpoint (`str`, *optional*):
|
| 379 |
+
The API endpoint to use when pushing the model to the hub.
|
| 380 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 381 |
+
If provided, only files matching at least one pattern are pushed.
|
| 382 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 383 |
+
If provided, files matching any of the patterns are not pushed.
|
| 384 |
+
delete_patterns (`list[str]` or `str`, *optional*):
|
| 385 |
+
If provided, remote files matching any of the patterns will be deleted from the repo.
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
The url of the commit of your model in the given repository.
|
| 389 |
+
|
| 390 |
+
> [!TIP]
|
| 391 |
+
> Raises the following error:
|
| 392 |
+
>
|
| 393 |
+
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 394 |
+
> if the user is not log on to the Hugging Face Hub.
|
| 395 |
+
"""
|
| 396 |
+
_check_fastai_fastcore_versions()
|
| 397 |
+
api = HfApi(endpoint=api_endpoint)
|
| 398 |
+
repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
|
| 399 |
+
|
| 400 |
+
# Push the files to the repo in a single commit
|
| 401 |
+
with SoftTemporaryDirectory() as tmp:
|
| 402 |
+
saved_path = Path(tmp) / repo_id
|
| 403 |
+
_save_pretrained_fastai(learner, saved_path, config=config)
|
| 404 |
+
return api.upload_folder(
|
| 405 |
+
repo_id=repo_id,
|
| 406 |
+
token=token,
|
| 407 |
+
folder_path=saved_path,
|
| 408 |
+
commit_message=commit_message,
|
| 409 |
+
revision=branch,
|
| 410 |
+
create_pr=create_pr,
|
| 411 |
+
allow_patterns=allow_patterns,
|
| 412 |
+
ignore_patterns=ignore_patterns,
|
| 413 |
+
delete_patterns=delete_patterns,
|
| 414 |
+
)
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/file_download.py
ADDED
|
@@ -0,0 +1,1936 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import errno
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import shutil
|
| 6 |
+
import stat
|
| 7 |
+
import time
|
| 8 |
+
import uuid
|
| 9 |
+
import warnings
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any, BinaryIO, Literal, NoReturn, overload
|
| 13 |
+
from urllib.parse import quote, urlparse
|
| 14 |
+
|
| 15 |
+
import httpx
|
| 16 |
+
from tqdm.auto import tqdm as base_tqdm
|
| 17 |
+
|
| 18 |
+
from . import constants
|
| 19 |
+
from ._local_folder import (
|
| 20 |
+
_create_cachedir_tag,
|
| 21 |
+
get_local_download_paths,
|
| 22 |
+
read_download_metadata,
|
| 23 |
+
write_download_metadata,
|
| 24 |
+
)
|
| 25 |
+
from .errors import (
|
| 26 |
+
FileMetadataError,
|
| 27 |
+
GatedRepoError,
|
| 28 |
+
HfHubHTTPError,
|
| 29 |
+
LocalEntryNotFoundError,
|
| 30 |
+
RemoteEntryNotFoundError,
|
| 31 |
+
RepositoryNotFoundError,
|
| 32 |
+
RevisionNotFoundError,
|
| 33 |
+
)
|
| 34 |
+
from .utils import (
|
| 35 |
+
OfflineModeIsEnabled,
|
| 36 |
+
SoftTemporaryDirectory,
|
| 37 |
+
WeakFileLock,
|
| 38 |
+
XetFileData,
|
| 39 |
+
build_hf_headers,
|
| 40 |
+
hf_raise_for_status,
|
| 41 |
+
logging,
|
| 42 |
+
parse_xet_file_data_from_response,
|
| 43 |
+
refresh_xet_connection_info,
|
| 44 |
+
tqdm,
|
| 45 |
+
validate_hf_hub_args,
|
| 46 |
+
)
|
| 47 |
+
from .utils._http import (
|
| 48 |
+
_DEFAULT_RETRY_ON_EXCEPTIONS,
|
| 49 |
+
_DEFAULT_RETRY_ON_STATUS_CODES,
|
| 50 |
+
_adjust_range_header,
|
| 51 |
+
_httpx_follow_relative_redirects_with_backoff,
|
| 52 |
+
http_stream_backoff,
|
| 53 |
+
)
|
| 54 |
+
from .utils._runtime import is_xet_available
|
| 55 |
+
from .utils.sha import sha_fileobj
|
| 56 |
+
from .utils.tqdm import _get_progress_bar_context
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
logger = logging.get_logger(__name__)
|
| 60 |
+
|
| 61 |
+
# Return value when trying to load a file from cache but the file does not exist in the distant repo.
|
| 62 |
+
_CACHED_NO_EXIST = object()
|
| 63 |
+
_CACHED_NO_EXIST_T = Any
|
| 64 |
+
|
| 65 |
+
# Regex to get filename from a "Content-Disposition" header for CDN-served files
|
| 66 |
+
HEADER_FILENAME_PATTERN = re.compile(r'filename="(?P<filename>.*?)";')
|
| 67 |
+
|
| 68 |
+
# Regex to check if the revision IS directly a commit_hash
|
| 69 |
+
REGEX_COMMIT_HASH = re.compile(r"^[0-9a-f]{40}$")
|
| 70 |
+
|
| 71 |
+
# Regex to check if the file etag IS a valid sha256
|
| 72 |
+
REGEX_SHA256 = re.compile(r"^[0-9a-f]{64}$")
|
| 73 |
+
|
| 74 |
+
_are_symlinks_supported_in_dir: dict[str, bool] = {}
|
| 75 |
+
|
| 76 |
+
# Internal retry timeout for metadata fetch when no local file exists
|
| 77 |
+
_ETAG_RETRY_TIMEOUT = 60
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def are_symlinks_supported(cache_dir: str | Path | None = None) -> bool:
|
| 81 |
+
"""Return whether the symlinks are supported on the machine.
|
| 82 |
+
|
| 83 |
+
Since symlinks support can change depending on the mounted disk, we need to check
|
| 84 |
+
on the precise cache folder. By default, the default HF cache directory is checked.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
cache_dir (`str`, `Path`, *optional*):
|
| 88 |
+
Path to the folder where cached files are stored.
|
| 89 |
+
|
| 90 |
+
Returns: [bool] Whether symlinks are supported in the directory.
|
| 91 |
+
"""
|
| 92 |
+
# Defaults to HF cache
|
| 93 |
+
if cache_dir is None:
|
| 94 |
+
cache_dir = constants.HF_HUB_CACHE
|
| 95 |
+
cache_dir = str(Path(cache_dir).expanduser().resolve()) # make it unique
|
| 96 |
+
|
| 97 |
+
# If symlinks are explicitly disabled by the user, always return False
|
| 98 |
+
if constants.HF_HUB_DISABLE_SYMLINKS:
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
# Check symlink compatibility only once (per cache directory) at first time use
|
| 102 |
+
if cache_dir not in _are_symlinks_supported_in_dir:
|
| 103 |
+
_are_symlinks_supported_in_dir[cache_dir] = True
|
| 104 |
+
|
| 105 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 106 |
+
with SoftTemporaryDirectory(dir=cache_dir) as tmpdir:
|
| 107 |
+
src_path = Path(tmpdir) / "dummy_file_src"
|
| 108 |
+
src_path.touch()
|
| 109 |
+
dst_path = Path(tmpdir) / "dummy_file_dst"
|
| 110 |
+
|
| 111 |
+
# Relative source path as in `_create_symlink``
|
| 112 |
+
relative_src = os.path.relpath(src_path, start=os.path.dirname(dst_path))
|
| 113 |
+
try:
|
| 114 |
+
os.symlink(relative_src, dst_path)
|
| 115 |
+
except OSError:
|
| 116 |
+
# Likely running on Windows
|
| 117 |
+
_are_symlinks_supported_in_dir[cache_dir] = False
|
| 118 |
+
|
| 119 |
+
if not constants.HF_HUB_DISABLE_SYMLINKS_WARNING:
|
| 120 |
+
message = (
|
| 121 |
+
"`huggingface_hub` cache-system uses symlinks by default to"
|
| 122 |
+
" efficiently store duplicated files but your machine does not"
|
| 123 |
+
f" support them in {cache_dir}. Caching files will still work"
|
| 124 |
+
" but in a degraded version that might require more space on"
|
| 125 |
+
" your disk. This warning can be disabled by setting the"
|
| 126 |
+
" `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For"
|
| 127 |
+
" more details, see"
|
| 128 |
+
" https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations."
|
| 129 |
+
)
|
| 130 |
+
if os.name == "nt":
|
| 131 |
+
message += (
|
| 132 |
+
"\nTo support symlinks on Windows, you either need to"
|
| 133 |
+
" activate Developer Mode or to run Python as an"
|
| 134 |
+
" administrator. In order to activate developer mode,"
|
| 135 |
+
" see this article:"
|
| 136 |
+
" https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development"
|
| 137 |
+
)
|
| 138 |
+
warnings.warn(message)
|
| 139 |
+
|
| 140 |
+
return _are_symlinks_supported_in_dir[cache_dir]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@dataclass(frozen=True)
|
| 144 |
+
class HfFileMetadata:
|
| 145 |
+
"""Data structure containing information about a file versioned on the Hub.
|
| 146 |
+
|
| 147 |
+
Returned by [`get_hf_file_metadata`] based on a URL.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
commit_hash (`str`, *optional*):
|
| 151 |
+
The commit_hash related to the file.
|
| 152 |
+
etag (`str`, *optional*):
|
| 153 |
+
Etag of the file on the server.
|
| 154 |
+
location (`str`):
|
| 155 |
+
Location where to download the file. Can be a Hub url or not (CDN).
|
| 156 |
+
size (`size`):
|
| 157 |
+
Size of the file. In case of an LFS file, contains the size of the actual
|
| 158 |
+
LFS file, not the pointer.
|
| 159 |
+
xet_file_data (`XetFileData`, *optional*):
|
| 160 |
+
Xet information for the file. This is only set if the file is stored using Xet storage.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
commit_hash: str | None
|
| 164 |
+
etag: str | None
|
| 165 |
+
location: str
|
| 166 |
+
size: int | None
|
| 167 |
+
xet_file_data: XetFileData | None
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@dataclass
|
| 171 |
+
class DryRunFileInfo:
|
| 172 |
+
"""Information returned when performing a dry run of a file download.
|
| 173 |
+
|
| 174 |
+
Returned by [`hf_hub_download`] when `dry_run=True`.
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
commit_hash (`str`):
|
| 178 |
+
The commit_hash related to the file.
|
| 179 |
+
file_size (`int`):
|
| 180 |
+
Size of the file. In case of an LFS file, contains the size of the actual LFS file, not the pointer.
|
| 181 |
+
filename (`str`):
|
| 182 |
+
Name of the file in the repo.
|
| 183 |
+
is_cached (`bool`):
|
| 184 |
+
Whether the file is already cached locally.
|
| 185 |
+
will_download (`bool`):
|
| 186 |
+
Whether the file will be downloaded if `hf_hub_download` is called with `dry_run=False`.
|
| 187 |
+
In practice, will_download is `True` if the file is not cached or if `force_download=True`.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
commit_hash: str
|
| 191 |
+
file_size: int
|
| 192 |
+
filename: str
|
| 193 |
+
local_path: str
|
| 194 |
+
is_cached: bool
|
| 195 |
+
will_download: bool
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@validate_hf_hub_args
|
| 199 |
+
def hf_hub_url(
|
| 200 |
+
repo_id: str,
|
| 201 |
+
filename: str,
|
| 202 |
+
*,
|
| 203 |
+
subfolder: str | None = None,
|
| 204 |
+
repo_type: str | None = None,
|
| 205 |
+
revision: str | None = None,
|
| 206 |
+
endpoint: str | None = None,
|
| 207 |
+
) -> str:
|
| 208 |
+
"""Construct the URL of a file from the given information.
|
| 209 |
+
|
| 210 |
+
The resolved address can either be a huggingface.co-hosted url, or a link to
|
| 211 |
+
Cloudfront (a Content Delivery Network, or CDN) for large files which are
|
| 212 |
+
more than a few MBs.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
repo_id (`str`):
|
| 216 |
+
A namespace (user or an organization) name and a repo name separated
|
| 217 |
+
by a `/`.
|
| 218 |
+
filename (`str`):
|
| 219 |
+
The name of the file in the repo.
|
| 220 |
+
subfolder (`str`, *optional*):
|
| 221 |
+
An optional value corresponding to a folder inside the repo.
|
| 222 |
+
repo_type (`str`, *optional*):
|
| 223 |
+
Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo,
|
| 224 |
+
`None` or `"model"` if downloading from a model. Default is `None`.
|
| 225 |
+
revision (`str`, *optional*):
|
| 226 |
+
An optional Git revision id which can be a branch name, a tag, or a
|
| 227 |
+
commit hash.
|
| 228 |
+
|
| 229 |
+
Example:
|
| 230 |
+
|
| 231 |
+
```python
|
| 232 |
+
>>> from huggingface_hub import hf_hub_url
|
| 233 |
+
|
| 234 |
+
>>> hf_hub_url(
|
| 235 |
+
... repo_id="julien-c/EsperBERTo-small", filename="pytorch_model.bin"
|
| 236 |
+
... )
|
| 237 |
+
'https://huggingface.co/julien-c/EsperBERTo-small/resolve/main/pytorch_model.bin'
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
> [!TIP]
|
| 241 |
+
> Notes:
|
| 242 |
+
>
|
| 243 |
+
> Cloudfront is replicated over the globe so downloads are way faster for
|
| 244 |
+
> the end user (and it also lowers our bandwidth costs).
|
| 245 |
+
>
|
| 246 |
+
> Cloudfront aggressively caches files by default (default TTL is 24
|
| 247 |
+
> hours), however this is not an issue here because we implement a
|
| 248 |
+
> git-based versioning system on huggingface.co, which means that we store
|
| 249 |
+
> the files on S3/Cloudfront in a content-addressable way (i.e., the file
|
| 250 |
+
> name is its hash). Using content-addressable filenames means cache can't
|
| 251 |
+
> ever be stale.
|
| 252 |
+
>
|
| 253 |
+
> In terms of client-side caching from this library, we base our caching
|
| 254 |
+
> on the objects' entity tag (`ETag`), which is an identifier of a
|
| 255 |
+
> specific version of a resource [1]_. An object's ETag is: its git-sha1
|
| 256 |
+
> if stored in git, or its sha256 if stored in git-lfs.
|
| 257 |
+
|
| 258 |
+
References:
|
| 259 |
+
|
| 260 |
+
- [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
|
| 261 |
+
"""
|
| 262 |
+
if subfolder == "":
|
| 263 |
+
subfolder = None
|
| 264 |
+
if subfolder is not None:
|
| 265 |
+
filename = f"{subfolder}/{filename}"
|
| 266 |
+
|
| 267 |
+
if repo_type not in constants.REPO_TYPES_WITH_KERNEL:
|
| 268 |
+
raise ValueError("Invalid repo type")
|
| 269 |
+
|
| 270 |
+
if repo_type in constants.REPO_TYPES_URL_PREFIXES:
|
| 271 |
+
repo_id = constants.REPO_TYPES_URL_PREFIXES[repo_type] + repo_id
|
| 272 |
+
|
| 273 |
+
if revision is None:
|
| 274 |
+
revision = constants.DEFAULT_REVISION
|
| 275 |
+
url = constants.HUGGINGFACE_CO_URL_TEMPLATE.format(
|
| 276 |
+
repo_id=repo_id, revision=quote(revision, safe=""), filename=quote(filename)
|
| 277 |
+
)
|
| 278 |
+
# Update endpoint if provided
|
| 279 |
+
if endpoint is not None and url.startswith(constants.ENDPOINT):
|
| 280 |
+
url = endpoint + url[len(constants.ENDPOINT) :]
|
| 281 |
+
return url
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _get_file_length_from_http_response(response: httpx.Response) -> int | None:
|
| 285 |
+
"""
|
| 286 |
+
Get the length of the file from the HTTP response headers.
|
| 287 |
+
|
| 288 |
+
This function extracts the file size from the HTTP response headers, either from the
|
| 289 |
+
`Content-Range` or `Content-Length` header, if available (in that order).
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
response (`httpx.Response`):
|
| 293 |
+
The HTTP response object.
|
| 294 |
+
|
| 295 |
+
Returns:
|
| 296 |
+
`int` or `None`: The length of the file in bytes, or None if not available.
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
# If HTTP response contains compressed body (e.g. gzip), the `Content-Length` header will
|
| 300 |
+
# contain the length of the compressed body, not the uncompressed file size.
|
| 301 |
+
# And at the start of transmission there's no way to know the uncompressed file size for gzip,
|
| 302 |
+
# thus we return None in that case.
|
| 303 |
+
content_encoding = response.headers.get("Content-Encoding", "identity").lower()
|
| 304 |
+
if content_encoding != "identity":
|
| 305 |
+
# gzip/br/deflate/zstd etc
|
| 306 |
+
return None
|
| 307 |
+
|
| 308 |
+
content_range = response.headers.get("Content-Range")
|
| 309 |
+
if content_range is not None:
|
| 310 |
+
return int(content_range.rsplit("/")[-1])
|
| 311 |
+
|
| 312 |
+
content_length = response.headers.get("Content-Length")
|
| 313 |
+
if content_length is not None:
|
| 314 |
+
return int(content_length)
|
| 315 |
+
|
| 316 |
+
return None
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@validate_hf_hub_args
|
| 320 |
+
def http_get(
|
| 321 |
+
url: str,
|
| 322 |
+
temp_file: BinaryIO,
|
| 323 |
+
*,
|
| 324 |
+
resume_size: int = 0,
|
| 325 |
+
headers: dict[str, Any] | None = None,
|
| 326 |
+
expected_size: int | None = None,
|
| 327 |
+
displayed_filename: str | None = None,
|
| 328 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 329 |
+
_nb_retries: int = 5,
|
| 330 |
+
_tqdm_bar: tqdm | None = None,
|
| 331 |
+
) -> None:
|
| 332 |
+
"""
|
| 333 |
+
Download a remote file. Do not gobble up errors, and will return errors tailored to the Hugging Face Hub.
|
| 334 |
+
|
| 335 |
+
If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely a
|
| 336 |
+
transient error (network outage?). We log a warning message and try to resume the download a few times before
|
| 337 |
+
giving up. The method gives up after 5 attempts if no new data has being received from the server.
|
| 338 |
+
|
| 339 |
+
Args:
|
| 340 |
+
url (`str`):
|
| 341 |
+
The URL of the file to download.
|
| 342 |
+
temp_file (`BinaryIO`):
|
| 343 |
+
The file-like object where to save the file.
|
| 344 |
+
resume_size (`int`, *optional*):
|
| 345 |
+
The number of bytes already downloaded. If set to 0 (default), the whole file is download. If set to a
|
| 346 |
+
positive number, the download will resume at the given position.
|
| 347 |
+
headers (`dict`, *optional*):
|
| 348 |
+
Dictionary of HTTP Headers to send with the request.
|
| 349 |
+
expected_size (`int`, *optional*):
|
| 350 |
+
The expected size of the file to download. If set, the download will raise an error if the size of the
|
| 351 |
+
received content is different from the expected one.
|
| 352 |
+
displayed_filename (`str`, *optional*):
|
| 353 |
+
The filename of the file that is being downloaded. Value is used only to display a nice progress bar. If
|
| 354 |
+
not set, the filename is guessed from the URL or the `Content-Disposition` header.
|
| 355 |
+
"""
|
| 356 |
+
if expected_size is not None and resume_size == expected_size:
|
| 357 |
+
# If the file is already fully downloaded, we don't need to download it again.
|
| 358 |
+
return
|
| 359 |
+
|
| 360 |
+
initial_headers = headers
|
| 361 |
+
headers = copy.deepcopy(headers) or {}
|
| 362 |
+
if resume_size > 0:
|
| 363 |
+
headers["Range"] = _adjust_range_header(headers.get("Range"), resume_size)
|
| 364 |
+
elif expected_size and expected_size > constants.MAX_HTTP_DOWNLOAD_SIZE:
|
| 365 |
+
# Any files over 50GB will not be available through basic http requests.
|
| 366 |
+
raise ValueError(
|
| 367 |
+
"The file is too large to be downloaded using the regular download method. "
|
| 368 |
+
" Install `hf_xet` with `pip install hf_xet` for xet-powered downloads."
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
with http_stream_backoff(
|
| 372 |
+
method="GET",
|
| 373 |
+
url=url,
|
| 374 |
+
headers=headers,
|
| 375 |
+
timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT,
|
| 376 |
+
retry_on_exceptions=(),
|
| 377 |
+
retry_on_status_codes=(429,),
|
| 378 |
+
) as response:
|
| 379 |
+
hf_raise_for_status(response)
|
| 380 |
+
|
| 381 |
+
# If we requested a Range but got 200 back, the server ignored our Range header
|
| 382 |
+
# (e.g. CloudFront with Accept-Encoding: gzip). Reset file to avoid corruption.
|
| 383 |
+
if resume_size > 0 and response.status_code == 200:
|
| 384 |
+
temp_file.seek(0)
|
| 385 |
+
temp_file.truncate()
|
| 386 |
+
resume_size = 0
|
| 387 |
+
|
| 388 |
+
total: int | None = _get_file_length_from_http_response(response)
|
| 389 |
+
|
| 390 |
+
if displayed_filename is None:
|
| 391 |
+
displayed_filename = url
|
| 392 |
+
content_disposition = response.headers.get("Content-Disposition")
|
| 393 |
+
if content_disposition is not None:
|
| 394 |
+
match = HEADER_FILENAME_PATTERN.search(content_disposition)
|
| 395 |
+
if match is not None:
|
| 396 |
+
# Means file is on CDN
|
| 397 |
+
displayed_filename = match.groupdict()["filename"]
|
| 398 |
+
|
| 399 |
+
# Truncate filename if too long to display
|
| 400 |
+
if len(displayed_filename) > 40:
|
| 401 |
+
displayed_filename = f"(…){displayed_filename[-40:]}"
|
| 402 |
+
|
| 403 |
+
consistency_error_message = (
|
| 404 |
+
f"Consistency check failed: file should be of size {expected_size} but has size"
|
| 405 |
+
f" {{actual_size}} ({displayed_filename}).\nThis is usually due to network issues while downloading the file."
|
| 406 |
+
" Please retry with `force_download=True`."
|
| 407 |
+
)
|
| 408 |
+
progress_cm = _get_progress_bar_context(
|
| 409 |
+
desc=displayed_filename,
|
| 410 |
+
log_level=logger.getEffectiveLevel(),
|
| 411 |
+
total=total,
|
| 412 |
+
initial=resume_size,
|
| 413 |
+
name="huggingface_hub.http_get",
|
| 414 |
+
tqdm_class=tqdm_class,
|
| 415 |
+
_tqdm_bar=_tqdm_bar,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
with progress_cm as progress:
|
| 419 |
+
new_resume_size = resume_size
|
| 420 |
+
try:
|
| 421 |
+
for chunk in response.iter_bytes(chunk_size=constants.DOWNLOAD_CHUNK_SIZE):
|
| 422 |
+
if chunk: # filter out keep-alive new chunks
|
| 423 |
+
progress.update(len(chunk))
|
| 424 |
+
temp_file.write(chunk)
|
| 425 |
+
new_resume_size += len(chunk)
|
| 426 |
+
# Some data has been downloaded from the server so we reset the number of retries.
|
| 427 |
+
_nb_retries = 5
|
| 428 |
+
except (httpx.ConnectError, httpx.TimeoutException) as e:
|
| 429 |
+
# If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely
|
| 430 |
+
# a transient error (network outage?). We log a warning message and try to resume the download a few times
|
| 431 |
+
# before giving up. Tre retry mechanism is basic but should be enough in most cases.
|
| 432 |
+
if _nb_retries <= 0:
|
| 433 |
+
logger.warning("Error while downloading from %s: %s\nMax retries exceeded.", url, str(e))
|
| 434 |
+
raise
|
| 435 |
+
logger.warning("Error while downloading from %s: %s\nTrying to resume download...", url, str(e))
|
| 436 |
+
time.sleep(1)
|
| 437 |
+
return http_get(
|
| 438 |
+
url=url,
|
| 439 |
+
temp_file=temp_file,
|
| 440 |
+
resume_size=new_resume_size,
|
| 441 |
+
headers=initial_headers,
|
| 442 |
+
expected_size=expected_size,
|
| 443 |
+
tqdm_class=tqdm_class,
|
| 444 |
+
_nb_retries=_nb_retries - 1,
|
| 445 |
+
_tqdm_bar=_tqdm_bar,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
if expected_size is not None and expected_size != temp_file.tell():
|
| 449 |
+
raise OSError(
|
| 450 |
+
consistency_error_message.format(
|
| 451 |
+
actual_size=temp_file.tell(),
|
| 452 |
+
)
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def xet_get(
|
| 457 |
+
*,
|
| 458 |
+
incomplete_path: Path,
|
| 459 |
+
xet_file_data: XetFileData,
|
| 460 |
+
headers: dict[str, str],
|
| 461 |
+
expected_size: int | None = None,
|
| 462 |
+
displayed_filename: str | None = None,
|
| 463 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 464 |
+
_tqdm_bar: tqdm | None = None,
|
| 465 |
+
) -> None:
|
| 466 |
+
"""
|
| 467 |
+
Download a file using Xet storage service.
|
| 468 |
+
|
| 469 |
+
Args:
|
| 470 |
+
incomplete_path (`Path`):
|
| 471 |
+
The path to the file to download.
|
| 472 |
+
xet_file_data (`XetFileData`):
|
| 473 |
+
The file metadata needed to make the request to the xet storage service.
|
| 474 |
+
headers (`dict[str, str]`):
|
| 475 |
+
The headers to send to the xet storage service.
|
| 476 |
+
expected_size (`int`, *optional*):
|
| 477 |
+
The expected size of the file to download. If set, the download will raise an error if the size of the
|
| 478 |
+
received content is different from the expected one.
|
| 479 |
+
displayed_filename (`str`, *optional*):
|
| 480 |
+
The filename of the file that is being downloaded. Value is used only to display a nice progress bar. If
|
| 481 |
+
not set, the filename is guessed from the URL or the `Content-Disposition` header.
|
| 482 |
+
|
| 483 |
+
**How it works:**
|
| 484 |
+
The file download system uses Xet storage, which is a content-addressable storage system that breaks files into chunks
|
| 485 |
+
for efficient storage and transfer.
|
| 486 |
+
|
| 487 |
+
`hf_xet.download_files` manages downloading files by:
|
| 488 |
+
- Taking a list of files to download (each with its unique content hash)
|
| 489 |
+
- Connecting to a storage server (CAS server) that knows how files are chunked
|
| 490 |
+
- Using authentication to ensure secure access
|
| 491 |
+
- Providing progress updates during download
|
| 492 |
+
|
| 493 |
+
Authentication works by regularly refreshing access tokens through `refresh_xet_connection_info` to maintain a valid
|
| 494 |
+
connection to the storage server.
|
| 495 |
+
|
| 496 |
+
The download process works like this:
|
| 497 |
+
1. Create a local cache folder at `~/.cache/huggingface/xet/chunk-cache` to store reusable file chunks
|
| 498 |
+
2. Download files in parallel:
|
| 499 |
+
2.1. Prepare to write the file to disk
|
| 500 |
+
2.2. Ask the server "how is this file split into chunks?" using the file's unique hash
|
| 501 |
+
The server responds with:
|
| 502 |
+
- Which chunks make up the complete file
|
| 503 |
+
- Where each chunk can be downloaded from
|
| 504 |
+
2.3. For each needed chunk:
|
| 505 |
+
- Checks if we already have it in our local cache
|
| 506 |
+
- If not, download it from cloud storage (S3)
|
| 507 |
+
- Save it to cache for future use
|
| 508 |
+
- Assemble the chunks in order to recreate the original file
|
| 509 |
+
|
| 510 |
+
"""
|
| 511 |
+
try:
|
| 512 |
+
from hf_xet import PyXetDownloadInfo, download_files # type: ignore[no-redef]
|
| 513 |
+
except ImportError:
|
| 514 |
+
raise ValueError(
|
| 515 |
+
"To use optimized download using Xet storage, you need to install the hf_xet package. "
|
| 516 |
+
'Try `pip install "huggingface_hub[hf_xet]"` or `pip install hf_xet`.'
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
connection_info = refresh_xet_connection_info(file_data=xet_file_data, headers=headers)
|
| 520 |
+
|
| 521 |
+
def token_refresher() -> tuple[str, int]:
|
| 522 |
+
connection_info = refresh_xet_connection_info(file_data=xet_file_data, headers=headers)
|
| 523 |
+
if connection_info is None:
|
| 524 |
+
raise ValueError("Failed to refresh token using xet metadata.")
|
| 525 |
+
return connection_info.access_token, connection_info.expiration_unix_epoch
|
| 526 |
+
|
| 527 |
+
xet_download_info = [
|
| 528 |
+
PyXetDownloadInfo(
|
| 529 |
+
destination_path=str(incomplete_path.absolute()), hash=xet_file_data.file_hash, file_size=expected_size
|
| 530 |
+
)
|
| 531 |
+
]
|
| 532 |
+
|
| 533 |
+
if not displayed_filename:
|
| 534 |
+
displayed_filename = incomplete_path.name
|
| 535 |
+
|
| 536 |
+
# Truncate filename if too long to display
|
| 537 |
+
if len(displayed_filename) > 40:
|
| 538 |
+
displayed_filename = f"{displayed_filename[:40]}(…)"
|
| 539 |
+
|
| 540 |
+
progress_cm = _get_progress_bar_context(
|
| 541 |
+
desc=displayed_filename,
|
| 542 |
+
log_level=logger.getEffectiveLevel(),
|
| 543 |
+
total=expected_size,
|
| 544 |
+
initial=0,
|
| 545 |
+
name="huggingface_hub.xet_get",
|
| 546 |
+
tqdm_class=tqdm_class,
|
| 547 |
+
_tqdm_bar=_tqdm_bar,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
xet_headers = headers.copy()
|
| 551 |
+
xet_headers.pop("authorization", None)
|
| 552 |
+
|
| 553 |
+
with progress_cm as progress:
|
| 554 |
+
|
| 555 |
+
def progress_updater(progress_bytes: float):
|
| 556 |
+
progress.update(progress_bytes)
|
| 557 |
+
|
| 558 |
+
download_files(
|
| 559 |
+
xet_download_info,
|
| 560 |
+
endpoint=connection_info.endpoint,
|
| 561 |
+
token_info=(connection_info.access_token, connection_info.expiration_unix_epoch),
|
| 562 |
+
token_refresher=token_refresher,
|
| 563 |
+
progress_updater=[progress_updater],
|
| 564 |
+
request_headers=xet_headers,
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def _normalize_etag(etag: str | None) -> str | None:
|
| 569 |
+
"""Normalize ETag HTTP header, so it can be used to create nice filepaths.
|
| 570 |
+
|
| 571 |
+
The HTTP spec allows two forms of ETag:
|
| 572 |
+
ETag: W/"<etag_value>"
|
| 573 |
+
ETag: "<etag_value>"
|
| 574 |
+
|
| 575 |
+
For now, we only expect the second form from the server, but we want to be future-proof so we support both. For
|
| 576 |
+
more context, see `TestNormalizeEtag` tests and https://github.com/huggingface/huggingface_hub/pull/1428.
|
| 577 |
+
|
| 578 |
+
Args:
|
| 579 |
+
etag (`str`, *optional*): HTTP header
|
| 580 |
+
|
| 581 |
+
Returns:
|
| 582 |
+
`str` or `None`: string that can be used as a nice directory name.
|
| 583 |
+
Returns `None` if input is None.
|
| 584 |
+
"""
|
| 585 |
+
if etag is None:
|
| 586 |
+
return None
|
| 587 |
+
return etag.lstrip("W/").strip('"')
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def _create_relative_symlink(src: str, dst: str, new_blob: bool = False) -> None:
|
| 591 |
+
"""Alias method used in `transformers` conversion script."""
|
| 592 |
+
return _create_symlink(src=src, dst=dst, new_blob=new_blob)
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _create_symlink(src: str, dst: str, new_blob: bool = False) -> None:
|
| 596 |
+
"""Create a symbolic link named dst pointing to src.
|
| 597 |
+
|
| 598 |
+
By default, it will try to create a symlink using a relative path. Relative paths have 2 advantages:
|
| 599 |
+
- If the cache_folder is moved (example: back-up on a shared drive), relative paths within the cache folder will
|
| 600 |
+
not break.
|
| 601 |
+
- Relative paths seems to be better handled on Windows. Issue was reported 3 times in less than a week when
|
| 602 |
+
changing from relative to absolute paths. See https://github.com/huggingface/huggingface_hub/issues/1398,
|
| 603 |
+
https://github.com/huggingface/diffusers/issues/2729 and https://github.com/huggingface/transformers/pull/22228.
|
| 604 |
+
NOTE: The issue with absolute paths doesn't happen on admin mode.
|
| 605 |
+
When creating a symlink from the cache to a local folder, it is possible that a relative path cannot be created.
|
| 606 |
+
This happens when paths are not on the same volume. In that case, we use absolute paths.
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
The result layout looks something like
|
| 610 |
+
└── [ 128] snapshots
|
| 611 |
+
├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
|
| 612 |
+
│ ├── [ 52] README.md -> ../../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
|
| 613 |
+
│ └── [ 76] pytorch_model.bin -> ../../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
|
| 614 |
+
|
| 615 |
+
If symlinks cannot be created on this platform (most likely to be Windows), the workaround is to avoid symlinks by
|
| 616 |
+
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
|
| 617 |
+
(`new_blob=False`), we don't know if the blob file is already referenced elsewhere. To avoid breaking existing
|
| 618 |
+
cache, the file is duplicated on the disk.
|
| 619 |
+
|
| 620 |
+
In case symlinks are not supported, a warning message is displayed to the user once when loading `huggingface_hub`.
|
| 621 |
+
The warning message can be disabled with the `DISABLE_SYMLINKS_WARNING` environment variable.
|
| 622 |
+
"""
|
| 623 |
+
try:
|
| 624 |
+
os.remove(dst)
|
| 625 |
+
except OSError:
|
| 626 |
+
pass
|
| 627 |
+
|
| 628 |
+
abs_src = os.path.abspath(os.path.expanduser(src))
|
| 629 |
+
abs_dst = os.path.abspath(os.path.expanduser(dst))
|
| 630 |
+
abs_dst_folder = os.path.dirname(abs_dst)
|
| 631 |
+
|
| 632 |
+
# Use relative_dst in priority
|
| 633 |
+
try:
|
| 634 |
+
relative_src = os.path.relpath(abs_src, abs_dst_folder)
|
| 635 |
+
except ValueError:
|
| 636 |
+
# Raised on Windows if src and dst are not on the same volume. This is the case when creating a symlink to a
|
| 637 |
+
# local_dir instead of within the cache directory.
|
| 638 |
+
# See https://docs.python.org/3/library/os.path.html#os.path.relpath
|
| 639 |
+
relative_src = None
|
| 640 |
+
|
| 641 |
+
try:
|
| 642 |
+
commonpath = os.path.commonpath([abs_src, abs_dst])
|
| 643 |
+
_support_symlinks = are_symlinks_supported(commonpath)
|
| 644 |
+
except ValueError:
|
| 645 |
+
# Raised if src and dst are not on the same volume. Symlinks will still work on Linux/Macos.
|
| 646 |
+
# See https://docs.python.org/3/library/os.path.html#os.path.commonpath
|
| 647 |
+
_support_symlinks = os.name != "nt" and not constants.HF_HUB_DISABLE_SYMLINKS
|
| 648 |
+
except PermissionError:
|
| 649 |
+
# Permission error means src and dst are not in the same volume (e.g. destination path has been provided
|
| 650 |
+
# by the user via `local_dir`. Let's test symlink support there)
|
| 651 |
+
_support_symlinks = are_symlinks_supported(abs_dst_folder)
|
| 652 |
+
except OSError as e:
|
| 653 |
+
# OS error (errno=30) means that the commonpath is readonly on Linux/MacOS.
|
| 654 |
+
if e.errno == errno.EROFS:
|
| 655 |
+
_support_symlinks = are_symlinks_supported(abs_dst_folder)
|
| 656 |
+
else:
|
| 657 |
+
raise
|
| 658 |
+
|
| 659 |
+
# Symlinks are supported => let's create a symlink.
|
| 660 |
+
if _support_symlinks:
|
| 661 |
+
src_rel_or_abs = relative_src or abs_src
|
| 662 |
+
logger.debug(f"Creating pointer from {src_rel_or_abs} to {abs_dst}")
|
| 663 |
+
try:
|
| 664 |
+
os.symlink(src_rel_or_abs, abs_dst)
|
| 665 |
+
return
|
| 666 |
+
except FileExistsError:
|
| 667 |
+
if os.path.islink(abs_dst) and os.path.realpath(abs_dst) == os.path.realpath(abs_src):
|
| 668 |
+
# `abs_dst` already exists and is a symlink to the `abs_src` blob. It is most likely that the file has
|
| 669 |
+
# been cached twice concurrently (exactly between `os.remove` and `os.symlink`). Do nothing.
|
| 670 |
+
return
|
| 671 |
+
else:
|
| 672 |
+
# Very unlikely to happen. Means a file `dst` has been created exactly between `os.remove` and
|
| 673 |
+
# `os.symlink` and is not a symlink to the `abs_src` blob file. Raise exception.
|
| 674 |
+
raise
|
| 675 |
+
except PermissionError:
|
| 676 |
+
# Permission error means src and dst are not in the same volume (e.g. download to local dir) and symlink
|
| 677 |
+
# is supported on both volumes but not between them. Let's just make a hard copy in that case.
|
| 678 |
+
pass
|
| 679 |
+
|
| 680 |
+
# Symlinks are not supported => let's move or copy the file.
|
| 681 |
+
if new_blob:
|
| 682 |
+
logger.debug(f"Symlink not supported. Moving file from {abs_src} to {abs_dst}")
|
| 683 |
+
shutil.move(abs_src, abs_dst, copy_function=_copy_no_matter_what)
|
| 684 |
+
else:
|
| 685 |
+
logger.debug(f"Symlink not supported. Copying file from {abs_src} to {abs_dst}")
|
| 686 |
+
shutil.copyfile(abs_src, abs_dst)
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def _cache_commit_hash_for_specific_revision(storage_folder: str, revision: str, commit_hash: str) -> None:
|
| 690 |
+
"""Cache reference between a revision (tag, branch or truncated commit hash) and the corresponding commit hash.
|
| 691 |
+
|
| 692 |
+
Does nothing if `revision` is already a proper `commit_hash` or reference is already cached.
|
| 693 |
+
"""
|
| 694 |
+
if revision != commit_hash:
|
| 695 |
+
ref_path = Path(storage_folder) / "refs" / revision
|
| 696 |
+
ref_path.parent.mkdir(parents=True, exist_ok=True)
|
| 697 |
+
if not ref_path.exists() or commit_hash != ref_path.read_text():
|
| 698 |
+
# Update ref only if has been updated. Could cause useless error in case
|
| 699 |
+
# repo is already cached and user doesn't have write access to cache folder.
|
| 700 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1216.
|
| 701 |
+
ref_path.write_text(commit_hash)
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
@validate_hf_hub_args
|
| 705 |
+
def repo_folder_name(*, repo_id: str, repo_type: str) -> str:
|
| 706 |
+
"""Return a serialized version of a hf.co repo name and type, safe for disk storage
|
| 707 |
+
as a single non-nested folder.
|
| 708 |
+
|
| 709 |
+
Example: models--julien-c--EsperBERTo-small
|
| 710 |
+
"""
|
| 711 |
+
# remove all `/` occurrences to correctly convert repo to directory name
|
| 712 |
+
parts = [f"{repo_type}s", *repo_id.split("/")]
|
| 713 |
+
return constants.REPO_ID_SEPARATOR.join(parts)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def _check_disk_space(expected_size: int, target_dir: str | Path) -> None:
|
| 717 |
+
"""Check disk usage and log a warning if there is not enough disk space to download the file.
|
| 718 |
+
|
| 719 |
+
Args:
|
| 720 |
+
expected_size (`int`):
|
| 721 |
+
The expected size of the file in bytes.
|
| 722 |
+
target_dir (`str`):
|
| 723 |
+
The directory where the file will be stored after downloading.
|
| 724 |
+
"""
|
| 725 |
+
|
| 726 |
+
target_dir = Path(target_dir) # format as `Path`
|
| 727 |
+
for path in [target_dir] + list(target_dir.parents): # first check target_dir, then each parents one by one
|
| 728 |
+
try:
|
| 729 |
+
target_dir_free = shutil.disk_usage(path).free
|
| 730 |
+
if target_dir_free < expected_size:
|
| 731 |
+
warnings.warn(
|
| 732 |
+
"Not enough free disk space to download the file. "
|
| 733 |
+
f"The expected file size is: {expected_size / 1e6:.2f} MB. "
|
| 734 |
+
f"The target location {target_dir} only has {target_dir_free / 1e6:.2f} MB free disk space."
|
| 735 |
+
)
|
| 736 |
+
return
|
| 737 |
+
except OSError: # raise on anything: file does not exist or space disk cannot be checked
|
| 738 |
+
pass
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
@overload
|
| 742 |
+
def hf_hub_download(
|
| 743 |
+
repo_id: str,
|
| 744 |
+
filename: str,
|
| 745 |
+
*,
|
| 746 |
+
subfolder: str | None = None,
|
| 747 |
+
repo_type: str | None = None,
|
| 748 |
+
revision: str | None = None,
|
| 749 |
+
library_name: str | None = None,
|
| 750 |
+
library_version: str | None = None,
|
| 751 |
+
cache_dir: str | Path | None = None,
|
| 752 |
+
local_dir: str | Path | None = None,
|
| 753 |
+
user_agent: dict | str | None = None,
|
| 754 |
+
force_download: bool = False,
|
| 755 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 756 |
+
token: bool | str | None = None,
|
| 757 |
+
local_files_only: bool = False,
|
| 758 |
+
headers: dict[str, str] | None = None,
|
| 759 |
+
endpoint: str | None = None,
|
| 760 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 761 |
+
dry_run: Literal[False] = False,
|
| 762 |
+
) -> str: ...
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
@overload
|
| 766 |
+
def hf_hub_download(
|
| 767 |
+
repo_id: str,
|
| 768 |
+
filename: str,
|
| 769 |
+
*,
|
| 770 |
+
subfolder: str | None = None,
|
| 771 |
+
repo_type: str | None = None,
|
| 772 |
+
revision: str | None = None,
|
| 773 |
+
library_name: str | None = None,
|
| 774 |
+
library_version: str | None = None,
|
| 775 |
+
cache_dir: str | Path | None = None,
|
| 776 |
+
local_dir: str | Path | None = None,
|
| 777 |
+
user_agent: dict | str | None = None,
|
| 778 |
+
force_download: bool = False,
|
| 779 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 780 |
+
token: bool | str | None = None,
|
| 781 |
+
local_files_only: bool = False,
|
| 782 |
+
headers: dict[str, str] | None = None,
|
| 783 |
+
endpoint: str | None = None,
|
| 784 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 785 |
+
dry_run: Literal[True] = True,
|
| 786 |
+
) -> DryRunFileInfo: ...
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
@overload
|
| 790 |
+
def hf_hub_download(
|
| 791 |
+
repo_id: str,
|
| 792 |
+
filename: str,
|
| 793 |
+
*,
|
| 794 |
+
subfolder: str | None = None,
|
| 795 |
+
repo_type: str | None = None,
|
| 796 |
+
revision: str | None = None,
|
| 797 |
+
library_name: str | None = None,
|
| 798 |
+
library_version: str | None = None,
|
| 799 |
+
cache_dir: str | Path | None = None,
|
| 800 |
+
local_dir: str | Path | None = None,
|
| 801 |
+
user_agent: dict | str | None = None,
|
| 802 |
+
force_download: bool = False,
|
| 803 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 804 |
+
token: bool | str | None = None,
|
| 805 |
+
local_files_only: bool = False,
|
| 806 |
+
headers: dict[str, str] | None = None,
|
| 807 |
+
endpoint: str | None = None,
|
| 808 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 809 |
+
dry_run: bool = False,
|
| 810 |
+
) -> str | DryRunFileInfo: ...
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
@validate_hf_hub_args
|
| 814 |
+
def hf_hub_download(
|
| 815 |
+
repo_id: str,
|
| 816 |
+
filename: str,
|
| 817 |
+
*,
|
| 818 |
+
subfolder: str | None = None,
|
| 819 |
+
repo_type: str | None = None,
|
| 820 |
+
revision: str | None = None,
|
| 821 |
+
library_name: str | None = None,
|
| 822 |
+
library_version: str | None = None,
|
| 823 |
+
cache_dir: str | Path | None = None,
|
| 824 |
+
local_dir: str | Path | None = None,
|
| 825 |
+
user_agent: dict | str | None = None,
|
| 826 |
+
force_download: bool = False,
|
| 827 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 828 |
+
token: bool | str | None = None,
|
| 829 |
+
local_files_only: bool = False,
|
| 830 |
+
headers: dict[str, str] | None = None,
|
| 831 |
+
endpoint: str | None = None,
|
| 832 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 833 |
+
dry_run: bool = False,
|
| 834 |
+
) -> str | DryRunFileInfo:
|
| 835 |
+
"""Download a given file if it's not already present in the local cache.
|
| 836 |
+
|
| 837 |
+
The new cache file layout looks like this:
|
| 838 |
+
- The cache directory contains one subfolder per repo_id (namespaced by repo type)
|
| 839 |
+
- inside each repo folder:
|
| 840 |
+
- refs is a list of the latest known revision => commit_hash pairs
|
| 841 |
+
- blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
|
| 842 |
+
whether they're LFS files or not)
|
| 843 |
+
- snapshots contains one subfolder per commit, each "commit" contains the subset of the files
|
| 844 |
+
that have been resolved at that particular commit. Each filename is a symlink to the blob
|
| 845 |
+
at that particular commit.
|
| 846 |
+
|
| 847 |
+
```
|
| 848 |
+
[ 96] .
|
| 849 |
+
└── [ 160] models--julien-c--EsperBERTo-small
|
| 850 |
+
├── [ 160] blobs
|
| 851 |
+
│ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
|
| 852 |
+
│ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
|
| 853 |
+
│ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
|
| 854 |
+
├── [ 96] refs
|
| 855 |
+
│ └── [ 40] main
|
| 856 |
+
└── [ 128] snapshots
|
| 857 |
+
├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
|
| 858 |
+
│ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
|
| 859 |
+
│ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
|
| 860 |
+
└── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
|
| 861 |
+
├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
|
| 862 |
+
└── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
|
| 863 |
+
```
|
| 864 |
+
|
| 865 |
+
If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
|
| 866 |
+
option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
|
| 867 |
+
to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
|
| 868 |
+
cache-system, it's optimized for regularly pulling the latest version of a repository.
|
| 869 |
+
|
| 870 |
+
Args:
|
| 871 |
+
repo_id (`str`):
|
| 872 |
+
A user or an organization name and a repo name separated by a `/`.
|
| 873 |
+
filename (`str`):
|
| 874 |
+
The name of the file in the repo.
|
| 875 |
+
subfolder (`str`, *optional*):
|
| 876 |
+
An optional value corresponding to a folder inside the model repo.
|
| 877 |
+
repo_type (`str`, *optional*):
|
| 878 |
+
Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo,
|
| 879 |
+
`None` or `"model"` if downloading from a model. Default is `None`.
|
| 880 |
+
revision (`str`, *optional*):
|
| 881 |
+
An optional Git revision id which can be a branch name, a tag, or a
|
| 882 |
+
commit hash.
|
| 883 |
+
library_name (`str`, *optional*):
|
| 884 |
+
The name of the library to which the object corresponds.
|
| 885 |
+
library_version (`str`, *optional*):
|
| 886 |
+
The version of the library.
|
| 887 |
+
cache_dir (`str`, `Path`, *optional*):
|
| 888 |
+
Path to the folder where cached files are stored.
|
| 889 |
+
local_dir (`str` or `Path`, *optional*):
|
| 890 |
+
If provided, the downloaded file will be placed under this directory.
|
| 891 |
+
user_agent (`dict`, `str`, *optional*):
|
| 892 |
+
The user-agent info in the form of a dictionary or a string.
|
| 893 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 894 |
+
Whether the file should be downloaded even if it already exists in
|
| 895 |
+
the local cache.
|
| 896 |
+
etag_timeout (`float`, *optional*, defaults to `10`):
|
| 897 |
+
When fetching ETag, how many seconds to wait for the server to send
|
| 898 |
+
data before giving up which is passed to `requests.request`.
|
| 899 |
+
token (`str`, `bool`, *optional*):
|
| 900 |
+
A token to be used for the download.
|
| 901 |
+
- If `True`, the token is read from the HuggingFace config
|
| 902 |
+
folder.
|
| 903 |
+
- If a string, it's used as the authentication token.
|
| 904 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 905 |
+
If `True`, avoid downloading the file and return the path to the
|
| 906 |
+
local cached file if it exists.
|
| 907 |
+
headers (`dict`, *optional*):
|
| 908 |
+
Additional headers to be sent with the request.
|
| 909 |
+
tqdm_class (`tqdm`, *optional*):
|
| 910 |
+
If provided, overwrites the default behavior for the progress bar. Passed
|
| 911 |
+
argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
|
| 912 |
+
Defaults to the custom HF progress bar that can be disabled by setting
|
| 913 |
+
`HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
|
| 914 |
+
dry_run (`bool`, *optional*, defaults to `False`):
|
| 915 |
+
If `True`, perform a dry run without actually downloading the file. Returns a
|
| 916 |
+
[`DryRunFileInfo`] object containing information about what would be downloaded.
|
| 917 |
+
|
| 918 |
+
Returns:
|
| 919 |
+
`str` or [`DryRunFileInfo`]:
|
| 920 |
+
- If `dry_run=False`: Local path of file or if networking is off, last version of file cached on disk.
|
| 921 |
+
- If `dry_run=True`: A [`DryRunFileInfo`] object containing download information.
|
| 922 |
+
|
| 923 |
+
Raises:
|
| 924 |
+
[`~utils.RepositoryNotFoundError`]
|
| 925 |
+
If the repository to download from cannot be found. This may be because it doesn't exist,
|
| 926 |
+
or because it is set to `private` and you do not have access.
|
| 927 |
+
[`~utils.RevisionNotFoundError`]
|
| 928 |
+
If the revision to download from cannot be found.
|
| 929 |
+
[`~utils.RemoteEntryNotFoundError`]
|
| 930 |
+
If the file to download cannot be found.
|
| 931 |
+
[`~utils.LocalEntryNotFoundError`]
|
| 932 |
+
If network is disabled or unavailable and file is not found in cache.
|
| 933 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 934 |
+
If `token=True` but the token cannot be found.
|
| 935 |
+
[`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
|
| 936 |
+
If ETag cannot be determined.
|
| 937 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 938 |
+
If some parameter value is invalid.
|
| 939 |
+
|
| 940 |
+
"""
|
| 941 |
+
if constants.HF_HUB_ETAG_TIMEOUT != constants.DEFAULT_ETAG_TIMEOUT:
|
| 942 |
+
# Respect environment variable above user value
|
| 943 |
+
etag_timeout = constants.HF_HUB_ETAG_TIMEOUT
|
| 944 |
+
|
| 945 |
+
if cache_dir is None:
|
| 946 |
+
cache_dir = constants.HF_HUB_CACHE
|
| 947 |
+
if revision is None:
|
| 948 |
+
revision = constants.DEFAULT_REVISION
|
| 949 |
+
if isinstance(cache_dir, Path):
|
| 950 |
+
cache_dir = str(cache_dir)
|
| 951 |
+
if isinstance(local_dir, Path):
|
| 952 |
+
local_dir = str(local_dir)
|
| 953 |
+
|
| 954 |
+
if subfolder == "":
|
| 955 |
+
subfolder = None
|
| 956 |
+
if subfolder is not None:
|
| 957 |
+
# This is used to create a URL, and not a local path, hence the forward slash.
|
| 958 |
+
filename = f"{subfolder}/{filename}"
|
| 959 |
+
|
| 960 |
+
if repo_type is None:
|
| 961 |
+
repo_type = "model"
|
| 962 |
+
if repo_type not in constants.REPO_TYPES_WITH_KERNEL:
|
| 963 |
+
raise ValueError(
|
| 964 |
+
f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}"
|
| 965 |
+
)
|
| 966 |
+
|
| 967 |
+
hf_headers = build_hf_headers(
|
| 968 |
+
token=token,
|
| 969 |
+
library_name=library_name,
|
| 970 |
+
library_version=library_version,
|
| 971 |
+
user_agent=user_agent,
|
| 972 |
+
headers=headers,
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
if local_dir is not None:
|
| 976 |
+
return _hf_hub_download_to_local_dir(
|
| 977 |
+
# Destination
|
| 978 |
+
local_dir=local_dir,
|
| 979 |
+
# File info
|
| 980 |
+
repo_id=repo_id,
|
| 981 |
+
repo_type=repo_type,
|
| 982 |
+
filename=filename,
|
| 983 |
+
revision=revision,
|
| 984 |
+
# HTTP info
|
| 985 |
+
endpoint=endpoint,
|
| 986 |
+
etag_timeout=etag_timeout,
|
| 987 |
+
headers=hf_headers,
|
| 988 |
+
token=token,
|
| 989 |
+
# Additional options
|
| 990 |
+
cache_dir=cache_dir,
|
| 991 |
+
force_download=force_download,
|
| 992 |
+
local_files_only=local_files_only,
|
| 993 |
+
tqdm_class=tqdm_class,
|
| 994 |
+
dry_run=dry_run,
|
| 995 |
+
)
|
| 996 |
+
else:
|
| 997 |
+
return _hf_hub_download_to_cache_dir(
|
| 998 |
+
# Destination
|
| 999 |
+
cache_dir=cache_dir,
|
| 1000 |
+
# File info
|
| 1001 |
+
repo_id=repo_id,
|
| 1002 |
+
filename=filename,
|
| 1003 |
+
repo_type=repo_type,
|
| 1004 |
+
revision=revision,
|
| 1005 |
+
# HTTP info
|
| 1006 |
+
endpoint=endpoint,
|
| 1007 |
+
etag_timeout=etag_timeout,
|
| 1008 |
+
headers=hf_headers,
|
| 1009 |
+
token=token,
|
| 1010 |
+
# Additional options
|
| 1011 |
+
local_files_only=local_files_only,
|
| 1012 |
+
force_download=force_download,
|
| 1013 |
+
tqdm_class=tqdm_class,
|
| 1014 |
+
dry_run=dry_run,
|
| 1015 |
+
)
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
def _hf_hub_download_to_cache_dir(
|
| 1019 |
+
*,
|
| 1020 |
+
# Destination
|
| 1021 |
+
cache_dir: str,
|
| 1022 |
+
# File info
|
| 1023 |
+
repo_id: str,
|
| 1024 |
+
filename: str,
|
| 1025 |
+
repo_type: str,
|
| 1026 |
+
revision: str,
|
| 1027 |
+
# HTTP info
|
| 1028 |
+
endpoint: str | None,
|
| 1029 |
+
etag_timeout: float,
|
| 1030 |
+
headers: dict[str, str],
|
| 1031 |
+
token: bool | str | None,
|
| 1032 |
+
# Additional options
|
| 1033 |
+
local_files_only: bool,
|
| 1034 |
+
force_download: bool,
|
| 1035 |
+
tqdm_class: type[base_tqdm] | None,
|
| 1036 |
+
dry_run: bool,
|
| 1037 |
+
) -> str | DryRunFileInfo:
|
| 1038 |
+
"""Download a given file to a cache folder, if not already present.
|
| 1039 |
+
|
| 1040 |
+
Method should not be called directly. Please use `hf_hub_download` instead.
|
| 1041 |
+
"""
|
| 1042 |
+
locks_dir = os.path.join(cache_dir, ".locks")
|
| 1043 |
+
storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
|
| 1044 |
+
|
| 1045 |
+
# cross-platform transcription of filename, to be used as a local file path.
|
| 1046 |
+
relative_filename = os.path.join(*filename.split("/"))
|
| 1047 |
+
if os.name == "nt":
|
| 1048 |
+
if relative_filename.startswith("..\\") or "\\..\\" in relative_filename:
|
| 1049 |
+
raise ValueError(
|
| 1050 |
+
f"Invalid filename: cannot handle filename '{relative_filename}' on Windows. Please ask the repository"
|
| 1051 |
+
" owner to rename this file."
|
| 1052 |
+
)
|
| 1053 |
+
|
| 1054 |
+
# if user provides a commit_hash and they already have the file on disk, shortcut everything.
|
| 1055 |
+
if REGEX_COMMIT_HASH.match(revision):
|
| 1056 |
+
pointer_path = _get_pointer_path(storage_folder, revision, relative_filename)
|
| 1057 |
+
if os.path.exists(pointer_path):
|
| 1058 |
+
if dry_run:
|
| 1059 |
+
return DryRunFileInfo(
|
| 1060 |
+
commit_hash=revision,
|
| 1061 |
+
file_size=os.path.getsize(pointer_path),
|
| 1062 |
+
filename=filename,
|
| 1063 |
+
is_cached=True,
|
| 1064 |
+
local_path=pointer_path,
|
| 1065 |
+
will_download=force_download,
|
| 1066 |
+
)
|
| 1067 |
+
if not force_download:
|
| 1068 |
+
return pointer_path
|
| 1069 |
+
|
| 1070 |
+
# Try to get metadata (etag, commit_hash, url, size) from the server.
|
| 1071 |
+
# If we can't, a HEAD request error is returned.
|
| 1072 |
+
(url_to_download, etag, commit_hash, expected_size, xet_file_data, head_call_error) = _get_metadata_or_catch_error(
|
| 1073 |
+
repo_id=repo_id,
|
| 1074 |
+
filename=filename,
|
| 1075 |
+
repo_type=repo_type,
|
| 1076 |
+
revision=revision,
|
| 1077 |
+
endpoint=endpoint,
|
| 1078 |
+
etag_timeout=etag_timeout,
|
| 1079 |
+
headers=headers,
|
| 1080 |
+
token=token,
|
| 1081 |
+
local_files_only=local_files_only,
|
| 1082 |
+
storage_folder=storage_folder,
|
| 1083 |
+
relative_filename=relative_filename,
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
# etag can be None for several reasons:
|
| 1087 |
+
# 1. we passed local_files_only.
|
| 1088 |
+
# 2. we don't have a connection
|
| 1089 |
+
# 3. Hub is down (HTTP 500, 503, 504)
|
| 1090 |
+
# 4. repo is not found -for example private or gated- and invalid/missing token sent
|
| 1091 |
+
# 5. Hub is blocked by a firewall or proxy is not set correctly.
|
| 1092 |
+
# => Try to get the last downloaded one from the specified revision.
|
| 1093 |
+
#
|
| 1094 |
+
# If the specified revision is a commit hash, look inside "snapshots".
|
| 1095 |
+
# If the specified revision is a branch or tag, look inside "refs".
|
| 1096 |
+
if head_call_error is not None:
|
| 1097 |
+
# Couldn't make a HEAD call => let's try to find a local file
|
| 1098 |
+
if not force_download:
|
| 1099 |
+
commit_hash = None
|
| 1100 |
+
if REGEX_COMMIT_HASH.match(revision):
|
| 1101 |
+
commit_hash = revision
|
| 1102 |
+
else:
|
| 1103 |
+
ref_path = os.path.join(storage_folder, "refs", revision)
|
| 1104 |
+
if os.path.isfile(ref_path):
|
| 1105 |
+
with open(ref_path) as f:
|
| 1106 |
+
commit_hash = f.read()
|
| 1107 |
+
|
| 1108 |
+
# Return pointer file if exists
|
| 1109 |
+
if commit_hash is not None:
|
| 1110 |
+
pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename)
|
| 1111 |
+
if os.path.exists(pointer_path):
|
| 1112 |
+
if dry_run:
|
| 1113 |
+
return DryRunFileInfo(
|
| 1114 |
+
commit_hash=commit_hash,
|
| 1115 |
+
file_size=os.path.getsize(pointer_path),
|
| 1116 |
+
filename=filename,
|
| 1117 |
+
is_cached=True,
|
| 1118 |
+
local_path=pointer_path,
|
| 1119 |
+
will_download=force_download,
|
| 1120 |
+
)
|
| 1121 |
+
if not force_download:
|
| 1122 |
+
return pointer_path
|
| 1123 |
+
|
| 1124 |
+
if isinstance(head_call_error, _DEFAULT_RETRY_ON_EXCEPTIONS) or (
|
| 1125 |
+
isinstance(head_call_error, HfHubHTTPError)
|
| 1126 |
+
and head_call_error.response.status_code in _DEFAULT_RETRY_ON_STATUS_CODES
|
| 1127 |
+
):
|
| 1128 |
+
logger.info("No local file found. Retrying..")
|
| 1129 |
+
(url_to_download, etag, commit_hash, expected_size, xet_file_data, head_call_error) = (
|
| 1130 |
+
_get_metadata_or_catch_error(
|
| 1131 |
+
repo_id=repo_id,
|
| 1132 |
+
filename=filename,
|
| 1133 |
+
repo_type=repo_type,
|
| 1134 |
+
revision=revision,
|
| 1135 |
+
endpoint=endpoint,
|
| 1136 |
+
etag_timeout=_ETAG_RETRY_TIMEOUT,
|
| 1137 |
+
headers=headers,
|
| 1138 |
+
token=token,
|
| 1139 |
+
local_files_only=local_files_only,
|
| 1140 |
+
storage_folder=storage_folder,
|
| 1141 |
+
relative_filename=relative_filename,
|
| 1142 |
+
retry_on_errors=True,
|
| 1143 |
+
)
|
| 1144 |
+
)
|
| 1145 |
+
|
| 1146 |
+
# If still error, raise
|
| 1147 |
+
if head_call_error is not None:
|
| 1148 |
+
_raise_on_head_call_error(head_call_error, force_download, local_files_only)
|
| 1149 |
+
|
| 1150 |
+
# From now on, etag, commit_hash, url and size are not None.
|
| 1151 |
+
assert etag is not None, "etag must have been retrieved from server"
|
| 1152 |
+
assert commit_hash is not None, "commit_hash must have been retrieved from server"
|
| 1153 |
+
assert url_to_download is not None, "file location must have been retrieved from server"
|
| 1154 |
+
assert expected_size is not None, "expected_size must have been retrieved from server"
|
| 1155 |
+
blob_path = os.path.join(storage_folder, "blobs", etag)
|
| 1156 |
+
pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename)
|
| 1157 |
+
|
| 1158 |
+
if dry_run:
|
| 1159 |
+
is_cached = os.path.exists(pointer_path) or os.path.exists(blob_path)
|
| 1160 |
+
return DryRunFileInfo(
|
| 1161 |
+
commit_hash=commit_hash,
|
| 1162 |
+
file_size=expected_size,
|
| 1163 |
+
filename=filename,
|
| 1164 |
+
is_cached=is_cached,
|
| 1165 |
+
local_path=pointer_path,
|
| 1166 |
+
will_download=force_download or not is_cached,
|
| 1167 |
+
)
|
| 1168 |
+
|
| 1169 |
+
os.makedirs(os.path.dirname(blob_path), exist_ok=True)
|
| 1170 |
+
os.makedirs(os.path.dirname(pointer_path), exist_ok=True)
|
| 1171 |
+
|
| 1172 |
+
# Tag cache_dir so backup tools can skip it (CACHEDIR.TAG standard).
|
| 1173 |
+
_create_cachedir_tag(Path(cache_dir))
|
| 1174 |
+
|
| 1175 |
+
# if passed revision is not identical to commit_hash
|
| 1176 |
+
# then revision has to be a branch name or tag name.
|
| 1177 |
+
# In that case store a ref.
|
| 1178 |
+
_cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash)
|
| 1179 |
+
|
| 1180 |
+
# Prevent parallel downloads of the same file with a lock.
|
| 1181 |
+
# etag could be duplicated across repos,
|
| 1182 |
+
lock_path = os.path.join(locks_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type), f"{etag}.lock")
|
| 1183 |
+
|
| 1184 |
+
# Some Windows versions do not allow for paths longer than 255 characters.
|
| 1185 |
+
# In this case, we must specify it as an extended path by using the "\\?\" prefix.
|
| 1186 |
+
if (
|
| 1187 |
+
os.name == "nt"
|
| 1188 |
+
and len(os.path.abspath(lock_path)) > 255
|
| 1189 |
+
and not os.path.abspath(lock_path).startswith("\\\\?\\")
|
| 1190 |
+
):
|
| 1191 |
+
lock_path = "\\\\?\\" + os.path.abspath(lock_path)
|
| 1192 |
+
|
| 1193 |
+
if (
|
| 1194 |
+
os.name == "nt"
|
| 1195 |
+
and len(os.path.abspath(blob_path)) > 255
|
| 1196 |
+
and not os.path.abspath(blob_path).startswith("\\\\?\\")
|
| 1197 |
+
):
|
| 1198 |
+
blob_path = "\\\\?\\" + os.path.abspath(blob_path)
|
| 1199 |
+
|
| 1200 |
+
Path(lock_path).parent.mkdir(parents=True, exist_ok=True)
|
| 1201 |
+
|
| 1202 |
+
# pointer already exists -> immediate return
|
| 1203 |
+
if not force_download and os.path.exists(pointer_path):
|
| 1204 |
+
return pointer_path
|
| 1205 |
+
|
| 1206 |
+
# Blob exists but pointer must be (safely) created -> take the lock
|
| 1207 |
+
if not force_download and os.path.exists(blob_path):
|
| 1208 |
+
with WeakFileLock(lock_path):
|
| 1209 |
+
if not os.path.exists(pointer_path):
|
| 1210 |
+
_create_symlink(blob_path, pointer_path, new_blob=False)
|
| 1211 |
+
return pointer_path
|
| 1212 |
+
|
| 1213 |
+
# Local file doesn't exist or etag isn't a match => retrieve file from remote (or cache)
|
| 1214 |
+
|
| 1215 |
+
with WeakFileLock(lock_path):
|
| 1216 |
+
_download_to_tmp_and_move(
|
| 1217 |
+
incomplete_path=Path(blob_path + ".incomplete"),
|
| 1218 |
+
destination_path=Path(blob_path),
|
| 1219 |
+
url_to_download=url_to_download,
|
| 1220 |
+
headers=headers,
|
| 1221 |
+
expected_size=expected_size,
|
| 1222 |
+
filename=filename,
|
| 1223 |
+
force_download=force_download,
|
| 1224 |
+
etag=etag,
|
| 1225 |
+
xet_file_data=xet_file_data,
|
| 1226 |
+
tqdm_class=tqdm_class,
|
| 1227 |
+
)
|
| 1228 |
+
if not os.path.exists(pointer_path):
|
| 1229 |
+
_create_symlink(blob_path, pointer_path, new_blob=True)
|
| 1230 |
+
|
| 1231 |
+
return pointer_path
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
def _hf_hub_download_to_local_dir(
|
| 1235 |
+
*,
|
| 1236 |
+
# Destination
|
| 1237 |
+
local_dir: str | Path,
|
| 1238 |
+
# File info
|
| 1239 |
+
repo_id: str,
|
| 1240 |
+
repo_type: str,
|
| 1241 |
+
filename: str,
|
| 1242 |
+
revision: str,
|
| 1243 |
+
# HTTP info
|
| 1244 |
+
endpoint: str | None,
|
| 1245 |
+
etag_timeout: float,
|
| 1246 |
+
headers: dict[str, str],
|
| 1247 |
+
token: bool | str | None,
|
| 1248 |
+
# Additional options
|
| 1249 |
+
cache_dir: str,
|
| 1250 |
+
force_download: bool,
|
| 1251 |
+
local_files_only: bool,
|
| 1252 |
+
tqdm_class: type[base_tqdm] | None,
|
| 1253 |
+
dry_run: bool,
|
| 1254 |
+
) -> str | DryRunFileInfo:
|
| 1255 |
+
"""Download a given file to a local folder, if not already present.
|
| 1256 |
+
|
| 1257 |
+
Method should not be called directly. Please use `hf_hub_download` instead.
|
| 1258 |
+
"""
|
| 1259 |
+
# Some Windows versions do not allow for paths longer than 255 characters.
|
| 1260 |
+
# In this case, we must specify it as an extended path by using the "\\?\" prefix.
|
| 1261 |
+
if os.name == "nt" and len(os.path.abspath(local_dir)) > 255:
|
| 1262 |
+
local_dir = "\\\\?\\" + os.path.abspath(local_dir)
|
| 1263 |
+
local_dir = Path(local_dir)
|
| 1264 |
+
paths = get_local_download_paths(local_dir=local_dir, filename=filename)
|
| 1265 |
+
local_metadata = read_download_metadata(local_dir=local_dir, filename=filename)
|
| 1266 |
+
|
| 1267 |
+
# Local file exists + metadata exists + commit_hash matches => return file
|
| 1268 |
+
if (
|
| 1269 |
+
REGEX_COMMIT_HASH.match(revision)
|
| 1270 |
+
and paths.file_path.is_file()
|
| 1271 |
+
and local_metadata is not None
|
| 1272 |
+
and local_metadata.commit_hash == revision
|
| 1273 |
+
):
|
| 1274 |
+
local_file = str(paths.file_path)
|
| 1275 |
+
if dry_run:
|
| 1276 |
+
return DryRunFileInfo(
|
| 1277 |
+
commit_hash=revision,
|
| 1278 |
+
file_size=os.path.getsize(local_file),
|
| 1279 |
+
filename=filename,
|
| 1280 |
+
is_cached=True,
|
| 1281 |
+
local_path=local_file,
|
| 1282 |
+
will_download=force_download,
|
| 1283 |
+
)
|
| 1284 |
+
if not force_download:
|
| 1285 |
+
return local_file
|
| 1286 |
+
|
| 1287 |
+
# Local file doesn't exist or commit_hash doesn't match => we need the etag
|
| 1288 |
+
(url_to_download, etag, commit_hash, expected_size, xet_file_data, head_call_error) = _get_metadata_or_catch_error(
|
| 1289 |
+
repo_id=repo_id,
|
| 1290 |
+
filename=filename,
|
| 1291 |
+
repo_type=repo_type,
|
| 1292 |
+
revision=revision,
|
| 1293 |
+
endpoint=endpoint,
|
| 1294 |
+
etag_timeout=etag_timeout,
|
| 1295 |
+
headers=headers,
|
| 1296 |
+
token=token,
|
| 1297 |
+
local_files_only=local_files_only,
|
| 1298 |
+
)
|
| 1299 |
+
|
| 1300 |
+
if head_call_error is not None:
|
| 1301 |
+
# No HEAD call but local file exists => default to local file
|
| 1302 |
+
if paths.file_path.is_file():
|
| 1303 |
+
if dry_run or not force_download:
|
| 1304 |
+
logger.warning(
|
| 1305 |
+
f"Couldn't access the Hub to check for update but local file already exists. Defaulting to existing file. (error: {head_call_error})"
|
| 1306 |
+
)
|
| 1307 |
+
local_path = str(paths.file_path)
|
| 1308 |
+
if dry_run and local_metadata is not None:
|
| 1309 |
+
return DryRunFileInfo(
|
| 1310 |
+
commit_hash=local_metadata.commit_hash,
|
| 1311 |
+
file_size=os.path.getsize(local_path),
|
| 1312 |
+
filename=filename,
|
| 1313 |
+
is_cached=True,
|
| 1314 |
+
local_path=local_path,
|
| 1315 |
+
will_download=force_download,
|
| 1316 |
+
)
|
| 1317 |
+
if not force_download:
|
| 1318 |
+
return local_path
|
| 1319 |
+
elif not force_download:
|
| 1320 |
+
if isinstance(head_call_error, _DEFAULT_RETRY_ON_EXCEPTIONS) or (
|
| 1321 |
+
isinstance(head_call_error, HfHubHTTPError)
|
| 1322 |
+
and head_call_error.response.status_code in _DEFAULT_RETRY_ON_STATUS_CODES
|
| 1323 |
+
):
|
| 1324 |
+
logger.info("No local file found. Retrying..")
|
| 1325 |
+
(url_to_download, etag, commit_hash, expected_size, xet_file_data, head_call_error) = (
|
| 1326 |
+
_get_metadata_or_catch_error(
|
| 1327 |
+
repo_id=repo_id,
|
| 1328 |
+
filename=filename,
|
| 1329 |
+
repo_type=repo_type,
|
| 1330 |
+
revision=revision,
|
| 1331 |
+
endpoint=endpoint,
|
| 1332 |
+
etag_timeout=_ETAG_RETRY_TIMEOUT,
|
| 1333 |
+
headers=headers,
|
| 1334 |
+
token=token,
|
| 1335 |
+
local_files_only=local_files_only,
|
| 1336 |
+
retry_on_errors=True,
|
| 1337 |
+
)
|
| 1338 |
+
)
|
| 1339 |
+
|
| 1340 |
+
# If still error, raise
|
| 1341 |
+
if head_call_error is not None:
|
| 1342 |
+
_raise_on_head_call_error(head_call_error, force_download, local_files_only)
|
| 1343 |
+
|
| 1344 |
+
# From now on, etag, commit_hash, url and size are not None.
|
| 1345 |
+
assert etag is not None, "etag must have been retrieved from server"
|
| 1346 |
+
assert commit_hash is not None, "commit_hash must have been retrieved from server"
|
| 1347 |
+
assert url_to_download is not None, "file location must have been retrieved from server"
|
| 1348 |
+
assert expected_size is not None, "expected_size must have been retrieved from server"
|
| 1349 |
+
|
| 1350 |
+
# Local file exists => check if it's up-to-date
|
| 1351 |
+
if not force_download and paths.file_path.is_file():
|
| 1352 |
+
# etag matches => update metadata and return file
|
| 1353 |
+
if local_metadata is not None and local_metadata.etag == etag:
|
| 1354 |
+
write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag)
|
| 1355 |
+
if dry_run:
|
| 1356 |
+
return DryRunFileInfo(
|
| 1357 |
+
commit_hash=commit_hash,
|
| 1358 |
+
file_size=expected_size,
|
| 1359 |
+
filename=filename,
|
| 1360 |
+
is_cached=True,
|
| 1361 |
+
local_path=str(paths.file_path),
|
| 1362 |
+
will_download=False,
|
| 1363 |
+
)
|
| 1364 |
+
return str(paths.file_path)
|
| 1365 |
+
|
| 1366 |
+
# metadata is outdated + etag is a sha256
|
| 1367 |
+
# => means it's an LFS file (large)
|
| 1368 |
+
# => let's compute local hash and compare
|
| 1369 |
+
# => if match, update metadata and return file
|
| 1370 |
+
if local_metadata is None and REGEX_SHA256.match(etag) is not None:
|
| 1371 |
+
with open(paths.file_path, "rb") as f:
|
| 1372 |
+
file_hash = sha_fileobj(f).hex()
|
| 1373 |
+
if file_hash == etag:
|
| 1374 |
+
write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag)
|
| 1375 |
+
if dry_run:
|
| 1376 |
+
return DryRunFileInfo(
|
| 1377 |
+
commit_hash=commit_hash,
|
| 1378 |
+
file_size=expected_size,
|
| 1379 |
+
filename=filename,
|
| 1380 |
+
is_cached=True,
|
| 1381 |
+
local_path=str(paths.file_path),
|
| 1382 |
+
will_download=False,
|
| 1383 |
+
)
|
| 1384 |
+
return str(paths.file_path)
|
| 1385 |
+
|
| 1386 |
+
# Local file doesn't exist or etag isn't a match => retrieve file from remote (or cache)
|
| 1387 |
+
|
| 1388 |
+
# If we are lucky enough, the file is already in the cache => copy it
|
| 1389 |
+
if not force_download:
|
| 1390 |
+
cached_path = try_to_load_from_cache(
|
| 1391 |
+
repo_id=repo_id,
|
| 1392 |
+
filename=filename,
|
| 1393 |
+
cache_dir=cache_dir,
|
| 1394 |
+
revision=commit_hash,
|
| 1395 |
+
repo_type=repo_type,
|
| 1396 |
+
)
|
| 1397 |
+
if isinstance(cached_path, str):
|
| 1398 |
+
with WeakFileLock(paths.lock_path):
|
| 1399 |
+
paths.file_path.parent.mkdir(parents=True, exist_ok=True)
|
| 1400 |
+
shutil.copyfile(cached_path, paths.file_path)
|
| 1401 |
+
write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag)
|
| 1402 |
+
if dry_run:
|
| 1403 |
+
return DryRunFileInfo(
|
| 1404 |
+
commit_hash=commit_hash,
|
| 1405 |
+
file_size=expected_size,
|
| 1406 |
+
filename=filename,
|
| 1407 |
+
is_cached=True,
|
| 1408 |
+
local_path=str(paths.file_path),
|
| 1409 |
+
will_download=False,
|
| 1410 |
+
)
|
| 1411 |
+
return str(paths.file_path)
|
| 1412 |
+
|
| 1413 |
+
if dry_run:
|
| 1414 |
+
is_cached = paths.file_path.is_file()
|
| 1415 |
+
return DryRunFileInfo(
|
| 1416 |
+
commit_hash=commit_hash,
|
| 1417 |
+
file_size=expected_size,
|
| 1418 |
+
filename=filename,
|
| 1419 |
+
is_cached=is_cached,
|
| 1420 |
+
local_path=str(paths.file_path),
|
| 1421 |
+
will_download=force_download or not is_cached,
|
| 1422 |
+
)
|
| 1423 |
+
|
| 1424 |
+
# Otherwise, let's download the file!
|
| 1425 |
+
with WeakFileLock(paths.lock_path):
|
| 1426 |
+
paths.file_path.unlink(missing_ok=True) # delete outdated file first
|
| 1427 |
+
_download_to_tmp_and_move(
|
| 1428 |
+
incomplete_path=paths.incomplete_path(etag),
|
| 1429 |
+
destination_path=paths.file_path,
|
| 1430 |
+
url_to_download=url_to_download,
|
| 1431 |
+
headers=headers,
|
| 1432 |
+
expected_size=expected_size,
|
| 1433 |
+
filename=filename,
|
| 1434 |
+
force_download=force_download,
|
| 1435 |
+
etag=etag,
|
| 1436 |
+
xet_file_data=xet_file_data,
|
| 1437 |
+
tqdm_class=tqdm_class,
|
| 1438 |
+
)
|
| 1439 |
+
|
| 1440 |
+
write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag)
|
| 1441 |
+
return str(paths.file_path)
|
| 1442 |
+
|
| 1443 |
+
|
| 1444 |
+
@validate_hf_hub_args
|
| 1445 |
+
def try_to_load_from_cache(
|
| 1446 |
+
repo_id: str,
|
| 1447 |
+
filename: str,
|
| 1448 |
+
cache_dir: str | Path | None = None,
|
| 1449 |
+
revision: str | None = None,
|
| 1450 |
+
repo_type: str | None = None,
|
| 1451 |
+
) -> str | _CACHED_NO_EXIST_T | None:
|
| 1452 |
+
"""
|
| 1453 |
+
Explores the cache to return the latest cached file for a given revision if found.
|
| 1454 |
+
|
| 1455 |
+
This function will not raise any exception if the file in not cached.
|
| 1456 |
+
|
| 1457 |
+
Args:
|
| 1458 |
+
cache_dir (`str` or `os.PathLike`):
|
| 1459 |
+
The folder where the cached files lie.
|
| 1460 |
+
repo_id (`str`):
|
| 1461 |
+
The ID of the repo on huggingface.co.
|
| 1462 |
+
filename (`str`):
|
| 1463 |
+
The filename to look for inside `repo_id`.
|
| 1464 |
+
revision (`str`, *optional*):
|
| 1465 |
+
The specific model version to use. Will default to `"main"` if it's not provided and no `commit_hash` is
|
| 1466 |
+
provided either.
|
| 1467 |
+
repo_type (`str`, *optional*):
|
| 1468 |
+
The type of the repository. Will default to `"model"`.
|
| 1469 |
+
|
| 1470 |
+
Returns:
|
| 1471 |
+
`Optional[str]` or `_CACHED_NO_EXIST`:
|
| 1472 |
+
Will return `None` if the file was not cached. Otherwise:
|
| 1473 |
+
- The exact path to the cached file if it's found in the cache
|
| 1474 |
+
- A special value `_CACHED_NO_EXIST` if the file does not exist at the given commit hash and this fact was
|
| 1475 |
+
cached.
|
| 1476 |
+
|
| 1477 |
+
Example:
|
| 1478 |
+
|
| 1479 |
+
```python
|
| 1480 |
+
from huggingface_hub import try_to_load_from_cache, _CACHED_NO_EXIST
|
| 1481 |
+
|
| 1482 |
+
filepath = try_to_load_from_cache()
|
| 1483 |
+
if isinstance(filepath, str):
|
| 1484 |
+
# file exists and is cached
|
| 1485 |
+
...
|
| 1486 |
+
elif filepath is _CACHED_NO_EXIST:
|
| 1487 |
+
# non-existence of file is cached
|
| 1488 |
+
...
|
| 1489 |
+
else:
|
| 1490 |
+
# file is not cached
|
| 1491 |
+
...
|
| 1492 |
+
```
|
| 1493 |
+
"""
|
| 1494 |
+
if revision is None:
|
| 1495 |
+
revision = "main"
|
| 1496 |
+
if repo_type is None:
|
| 1497 |
+
repo_type = "model"
|
| 1498 |
+
if repo_type not in constants.REPO_TYPES_WITH_KERNEL:
|
| 1499 |
+
raise ValueError(
|
| 1500 |
+
f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}"
|
| 1501 |
+
)
|
| 1502 |
+
if cache_dir is None:
|
| 1503 |
+
cache_dir = constants.HF_HUB_CACHE
|
| 1504 |
+
|
| 1505 |
+
repo_cache = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
|
| 1506 |
+
if not os.path.isdir(repo_cache):
|
| 1507 |
+
# No cache for this model
|
| 1508 |
+
return None
|
| 1509 |
+
|
| 1510 |
+
refs_dir = os.path.join(repo_cache, "refs")
|
| 1511 |
+
snapshots_dir = os.path.join(repo_cache, "snapshots")
|
| 1512 |
+
no_exist_dir = os.path.join(repo_cache, ".no_exist")
|
| 1513 |
+
|
| 1514 |
+
# Resolve refs (for instance to convert main to the associated commit sha)
|
| 1515 |
+
if os.path.isdir(refs_dir):
|
| 1516 |
+
revision_file = os.path.join(refs_dir, revision)
|
| 1517 |
+
if os.path.isfile(revision_file):
|
| 1518 |
+
with open(revision_file) as f:
|
| 1519 |
+
revision = f.read()
|
| 1520 |
+
|
| 1521 |
+
# Check if file is cached as "no_exist"
|
| 1522 |
+
if os.path.isfile(os.path.join(no_exist_dir, revision, filename)):
|
| 1523 |
+
return _CACHED_NO_EXIST
|
| 1524 |
+
|
| 1525 |
+
# Check if revision folder exists
|
| 1526 |
+
if not os.path.exists(snapshots_dir):
|
| 1527 |
+
return None
|
| 1528 |
+
cached_shas = os.listdir(snapshots_dir)
|
| 1529 |
+
if revision not in cached_shas:
|
| 1530 |
+
# No cache for this revision and we won't try to return a random revision
|
| 1531 |
+
return None
|
| 1532 |
+
|
| 1533 |
+
# Check if file exists in cache
|
| 1534 |
+
cached_file = os.path.join(snapshots_dir, revision, filename)
|
| 1535 |
+
return cached_file if os.path.isfile(cached_file) else None
|
| 1536 |
+
|
| 1537 |
+
|
| 1538 |
+
@validate_hf_hub_args
|
| 1539 |
+
def get_hf_file_metadata(
|
| 1540 |
+
url: str,
|
| 1541 |
+
token: bool | str | None = None,
|
| 1542 |
+
timeout: float | None = constants.HF_HUB_ETAG_TIMEOUT,
|
| 1543 |
+
library_name: str | None = None,
|
| 1544 |
+
library_version: str | None = None,
|
| 1545 |
+
user_agent: dict | str | None = None,
|
| 1546 |
+
headers: dict[str, str] | None = None,
|
| 1547 |
+
endpoint: str | None = None,
|
| 1548 |
+
retry_on_errors: bool = False,
|
| 1549 |
+
) -> HfFileMetadata:
|
| 1550 |
+
"""Fetch metadata of a file versioned on the Hub for a given url.
|
| 1551 |
+
|
| 1552 |
+
Args:
|
| 1553 |
+
url (`str`):
|
| 1554 |
+
File url, for example returned by [`hf_hub_url`].
|
| 1555 |
+
token (`str` or `bool`, *optional*):
|
| 1556 |
+
A token to be used for the download.
|
| 1557 |
+
- If `True`, the token is read from the HuggingFace config
|
| 1558 |
+
folder.
|
| 1559 |
+
- If `False` or `None`, no token is provided.
|
| 1560 |
+
- If a string, it's used as the authentication token.
|
| 1561 |
+
timeout (`float`, *optional*, defaults to 10):
|
| 1562 |
+
How many seconds to wait for the server to send metadata before giving up.
|
| 1563 |
+
library_name (`str`, *optional*):
|
| 1564 |
+
The name of the library to which the object corresponds.
|
| 1565 |
+
library_version (`str`, *optional*):
|
| 1566 |
+
The version of the library.
|
| 1567 |
+
user_agent (`dict`, `str`, *optional*):
|
| 1568 |
+
The user-agent info in the form of a dictionary or a string.
|
| 1569 |
+
headers (`dict`, *optional*):
|
| 1570 |
+
Additional headers to be sent with the request.
|
| 1571 |
+
endpoint (`str`, *optional*):
|
| 1572 |
+
Endpoint of the Hub. Defaults to <https://huggingface.co>.
|
| 1573 |
+
retry_on_errors (`bool`, *optional*, defaults to `False`):
|
| 1574 |
+
Whether to retry on errors (429, 5xx, timeout, network errors).
|
| 1575 |
+
If False, no retry for fast fallback to local cache.
|
| 1576 |
+
|
| 1577 |
+
Returns:
|
| 1578 |
+
A [`HfFileMetadata`] object containing metadata such as location, etag, size and
|
| 1579 |
+
commit_hash.
|
| 1580 |
+
"""
|
| 1581 |
+
hf_headers = build_hf_headers(
|
| 1582 |
+
token=token,
|
| 1583 |
+
library_name=library_name,
|
| 1584 |
+
library_version=library_version,
|
| 1585 |
+
user_agent=user_agent,
|
| 1586 |
+
headers=headers,
|
| 1587 |
+
)
|
| 1588 |
+
hf_headers["Accept-Encoding"] = "identity" # prevent any compression => we want to know the real size of the file
|
| 1589 |
+
|
| 1590 |
+
# Retrieve metadata
|
| 1591 |
+
response = _httpx_follow_relative_redirects_with_backoff(
|
| 1592 |
+
method="HEAD", url=url, headers=hf_headers, timeout=timeout, retry_on_errors=retry_on_errors
|
| 1593 |
+
)
|
| 1594 |
+
hf_raise_for_status(response)
|
| 1595 |
+
|
| 1596 |
+
# Return
|
| 1597 |
+
return HfFileMetadata(
|
| 1598 |
+
commit_hash=response.headers.get(constants.HUGGINGFACE_HEADER_X_REPO_COMMIT),
|
| 1599 |
+
# We favor a custom header indicating the etag of the linked resource, and we fall back to the regular etag header.
|
| 1600 |
+
etag=_normalize_etag(
|
| 1601 |
+
response.headers.get(constants.HUGGINGFACE_HEADER_X_LINKED_ETAG) or response.headers.get("ETag")
|
| 1602 |
+
),
|
| 1603 |
+
# Either from response headers (if redirected) or defaults to request url
|
| 1604 |
+
# Do not use directly `url` as we might have followed relative redirects.
|
| 1605 |
+
location=response.headers.get("Location") or str(response.request.url), # type: ignore
|
| 1606 |
+
size=_int_or_none(
|
| 1607 |
+
response.headers.get(constants.HUGGINGFACE_HEADER_X_LINKED_SIZE) or response.headers.get("Content-Length")
|
| 1608 |
+
),
|
| 1609 |
+
xet_file_data=parse_xet_file_data_from_response(response, endpoint=endpoint), # type: ignore
|
| 1610 |
+
)
|
| 1611 |
+
|
| 1612 |
+
|
| 1613 |
+
def _get_metadata_or_catch_error(
|
| 1614 |
+
*,
|
| 1615 |
+
repo_id: str,
|
| 1616 |
+
filename: str,
|
| 1617 |
+
repo_type: str,
|
| 1618 |
+
revision: str,
|
| 1619 |
+
endpoint: str | None,
|
| 1620 |
+
etag_timeout: float | None,
|
| 1621 |
+
headers: dict[str, str], # mutated inplace!
|
| 1622 |
+
token: bool | str | None,
|
| 1623 |
+
local_files_only: bool,
|
| 1624 |
+
relative_filename: str | None = None, # only used to store `.no_exists` in cache
|
| 1625 |
+
storage_folder: str | None = None, # only used to store `.no_exists` in cache
|
| 1626 |
+
retry_on_errors: bool = False,
|
| 1627 |
+
) -> (
|
| 1628 |
+
# Either an exception is caught and returned
|
| 1629 |
+
tuple[None, None, None, None, None, Exception]
|
| 1630 |
+
|
|
| 1631 |
+
# Or the metadata is returned as
|
| 1632 |
+
# `(url_to_download, etag, commit_hash, expected_size, xet_file_data, None)`
|
| 1633 |
+
tuple[str, str, str, int, XetFileData | None, None]
|
| 1634 |
+
):
|
| 1635 |
+
"""Get metadata for a file on the Hub, safely handling network issues.
|
| 1636 |
+
|
| 1637 |
+
Returns either the etag, commit_hash and expected size of the file, or the error
|
| 1638 |
+
raised while fetching the metadata.
|
| 1639 |
+
|
| 1640 |
+
NOTE: This function mutates `headers` inplace! It removes the `authorization` header
|
| 1641 |
+
if the file is a LFS blob and the domain of the url is different from the
|
| 1642 |
+
domain of the location (typically an S3 bucket).
|
| 1643 |
+
"""
|
| 1644 |
+
if local_files_only:
|
| 1645 |
+
return (
|
| 1646 |
+
None,
|
| 1647 |
+
None,
|
| 1648 |
+
None,
|
| 1649 |
+
None,
|
| 1650 |
+
None,
|
| 1651 |
+
OfflineModeIsEnabled(
|
| 1652 |
+
f"Cannot access file since 'local_files_only=True' as been set. (repo_id: {repo_id}, repo_type: {repo_type}, revision: {revision}, filename: {filename})"
|
| 1653 |
+
),
|
| 1654 |
+
)
|
| 1655 |
+
|
| 1656 |
+
url = hf_hub_url(repo_id, filename, repo_type=repo_type, revision=revision, endpoint=endpoint)
|
| 1657 |
+
url_to_download: str = url
|
| 1658 |
+
etag: str | None = None
|
| 1659 |
+
commit_hash: str | None = None
|
| 1660 |
+
expected_size: int | None = None
|
| 1661 |
+
head_error_call: Exception | None = None
|
| 1662 |
+
xet_file_data: XetFileData | None = None
|
| 1663 |
+
|
| 1664 |
+
# Try to get metadata from the server.
|
| 1665 |
+
# Do not raise yet if the file is not found or not accessible.
|
| 1666 |
+
if not local_files_only:
|
| 1667 |
+
try:
|
| 1668 |
+
try:
|
| 1669 |
+
metadata = get_hf_file_metadata(
|
| 1670 |
+
url=url,
|
| 1671 |
+
timeout=etag_timeout,
|
| 1672 |
+
headers=headers,
|
| 1673 |
+
token=token,
|
| 1674 |
+
endpoint=endpoint,
|
| 1675 |
+
retry_on_errors=retry_on_errors,
|
| 1676 |
+
)
|
| 1677 |
+
except RemoteEntryNotFoundError as http_error:
|
| 1678 |
+
if storage_folder is not None and relative_filename is not None:
|
| 1679 |
+
# Cache the non-existence of the file
|
| 1680 |
+
commit_hash = http_error.response.headers.get(constants.HUGGINGFACE_HEADER_X_REPO_COMMIT)
|
| 1681 |
+
if commit_hash is not None:
|
| 1682 |
+
no_exist_file_path = Path(storage_folder) / ".no_exist" / commit_hash / relative_filename
|
| 1683 |
+
try:
|
| 1684 |
+
no_exist_file_path.parent.mkdir(parents=True, exist_ok=True)
|
| 1685 |
+
no_exist_file_path.touch()
|
| 1686 |
+
except OSError as e:
|
| 1687 |
+
logger.error(
|
| 1688 |
+
f"Could not cache non-existence of file. Will ignore error and continue. Error: {e}"
|
| 1689 |
+
)
|
| 1690 |
+
_cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash)
|
| 1691 |
+
raise
|
| 1692 |
+
|
| 1693 |
+
# Commit hash must exist
|
| 1694 |
+
commit_hash = metadata.commit_hash
|
| 1695 |
+
if commit_hash is None:
|
| 1696 |
+
raise FileMetadataError(
|
| 1697 |
+
"Distant resource does not seem to be on huggingface.co. It is possible that a configuration issue"
|
| 1698 |
+
" prevents you from downloading resources from https://huggingface.co. Please check your firewall"
|
| 1699 |
+
" and proxy settings and make sure your SSL certificates are updated."
|
| 1700 |
+
)
|
| 1701 |
+
|
| 1702 |
+
# Etag must exist
|
| 1703 |
+
# If we don't have any of those, raise an error.
|
| 1704 |
+
etag = metadata.etag
|
| 1705 |
+
if etag is None:
|
| 1706 |
+
raise FileMetadataError(
|
| 1707 |
+
"Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility."
|
| 1708 |
+
)
|
| 1709 |
+
|
| 1710 |
+
# Size must exist
|
| 1711 |
+
expected_size = metadata.size
|
| 1712 |
+
if expected_size is None:
|
| 1713 |
+
raise FileMetadataError("Distant resource does not have a Content-Length.")
|
| 1714 |
+
|
| 1715 |
+
xet_file_data = metadata.xet_file_data
|
| 1716 |
+
|
| 1717 |
+
# In case of a redirect, save an extra redirect on the request.get call,
|
| 1718 |
+
# and ensure we download the exact atomic version even if it changed
|
| 1719 |
+
# between the HEAD and the GET (unlikely, but hey).
|
| 1720 |
+
#
|
| 1721 |
+
# If url domain is different => we are downloading from a CDN => url is signed => don't send auth
|
| 1722 |
+
# If url domain is the same => redirect due to repo rename AND downloading a regular file => keep auth
|
| 1723 |
+
if xet_file_data is None and url != metadata.location:
|
| 1724 |
+
url_to_download = metadata.location
|
| 1725 |
+
if urlparse(url).netloc != urlparse(metadata.location).netloc:
|
| 1726 |
+
# Remove authorization header when downloading a LFS blob
|
| 1727 |
+
headers.pop("authorization", None)
|
| 1728 |
+
except httpx.ProxyError:
|
| 1729 |
+
# Actually raise on proxy error
|
| 1730 |
+
raise
|
| 1731 |
+
except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled) as error:
|
| 1732 |
+
# Otherwise, our Internet connection is down.
|
| 1733 |
+
# etag is None
|
| 1734 |
+
head_error_call = error
|
| 1735 |
+
except (RevisionNotFoundError, RemoteEntryNotFoundError):
|
| 1736 |
+
# The repo was found but the revision or entry doesn't exist on the Hub (never existed or got deleted)
|
| 1737 |
+
raise
|
| 1738 |
+
except HfHubHTTPError as error:
|
| 1739 |
+
# Multiple reasons for an http error:
|
| 1740 |
+
# - Repository is private and invalid/missing token sent
|
| 1741 |
+
# - Repository is gated and invalid/missing token sent
|
| 1742 |
+
# - Hub is down (error 500 or 504)
|
| 1743 |
+
# => let's switch to 'local_files_only=True' to check if the files are already cached.
|
| 1744 |
+
# (if it's not the case, the error will be re-raised)
|
| 1745 |
+
head_error_call = error
|
| 1746 |
+
except FileMetadataError as error:
|
| 1747 |
+
# Multiple reasons for a FileMetadataError:
|
| 1748 |
+
# - Wrong network configuration (proxy, firewall, SSL certificates)
|
| 1749 |
+
# - Inconsistency on the Hub
|
| 1750 |
+
# => let's switch to 'local_files_only=True' to check if the files are already cached.
|
| 1751 |
+
# (if it's not the case, the error will be re-raised)
|
| 1752 |
+
head_error_call = error
|
| 1753 |
+
|
| 1754 |
+
if not (local_files_only or etag is not None or head_error_call is not None):
|
| 1755 |
+
raise RuntimeError("etag is empty due to uncovered problems")
|
| 1756 |
+
|
| 1757 |
+
return (url_to_download, etag, commit_hash, expected_size, xet_file_data, head_error_call) # type: ignore
|
| 1758 |
+
|
| 1759 |
+
|
| 1760 |
+
def _raise_on_head_call_error(head_call_error: Exception, force_download: bool, local_files_only: bool) -> NoReturn:
|
| 1761 |
+
"""Raise an appropriate error when the HEAD call failed and we cannot locate a local file."""
|
| 1762 |
+
# No head call => we cannot force download.
|
| 1763 |
+
if force_download:
|
| 1764 |
+
if local_files_only:
|
| 1765 |
+
raise ValueError("Cannot pass 'force_download=True' and 'local_files_only=True' at the same time.")
|
| 1766 |
+
elif isinstance(head_call_error, OfflineModeIsEnabled):
|
| 1767 |
+
raise ValueError("Cannot pass 'force_download=True' when offline mode is enabled.") from head_call_error
|
| 1768 |
+
else:
|
| 1769 |
+
raise ValueError("Force download failed due to the above error.") from head_call_error
|
| 1770 |
+
|
| 1771 |
+
# No head call + couldn't find an appropriate file on disk => raise an error.
|
| 1772 |
+
if local_files_only:
|
| 1773 |
+
raise LocalEntryNotFoundError(
|
| 1774 |
+
"Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable"
|
| 1775 |
+
" hf.co look-ups and downloads online, set 'local_files_only' to False."
|
| 1776 |
+
)
|
| 1777 |
+
elif isinstance(head_call_error, (RepositoryNotFoundError, GatedRepoError)) or (
|
| 1778 |
+
isinstance(head_call_error, HfHubHTTPError) and head_call_error.response.status_code == 401
|
| 1779 |
+
):
|
| 1780 |
+
# Repo not found or gated => let's raise the actual error
|
| 1781 |
+
# Unauthorized => likely a token issue => let's raise the actual error
|
| 1782 |
+
raise head_call_error
|
| 1783 |
+
else:
|
| 1784 |
+
# Otherwise: most likely a connection issue or Hub downtime => let's warn the user
|
| 1785 |
+
raise LocalEntryNotFoundError(
|
| 1786 |
+
"An error happened while trying to locate the file on the Hub and we cannot find the requested files"
|
| 1787 |
+
" in the local cache. Please check your connection and try again or make sure your Internet connection"
|
| 1788 |
+
" is on."
|
| 1789 |
+
) from head_call_error
|
| 1790 |
+
|
| 1791 |
+
|
| 1792 |
+
def _download_to_tmp_and_move(
|
| 1793 |
+
incomplete_path: Path,
|
| 1794 |
+
destination_path: Path,
|
| 1795 |
+
url_to_download: str,
|
| 1796 |
+
headers: dict[str, str],
|
| 1797 |
+
expected_size: int | None,
|
| 1798 |
+
filename: str,
|
| 1799 |
+
force_download: bool,
|
| 1800 |
+
etag: str | None,
|
| 1801 |
+
xet_file_data: XetFileData | None,
|
| 1802 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 1803 |
+
) -> None:
|
| 1804 |
+
"""Download content from a URL to a destination path.
|
| 1805 |
+
|
| 1806 |
+
Internal logic:
|
| 1807 |
+
- return early if file is already downloaded
|
| 1808 |
+
- resume download if possible (from incomplete file)
|
| 1809 |
+
- do not resume download if `force_download=True`
|
| 1810 |
+
- check disk space before downloading
|
| 1811 |
+
- download content to a temporary file
|
| 1812 |
+
- set correct permissions on temporary file
|
| 1813 |
+
- move the temporary file to the destination path
|
| 1814 |
+
|
| 1815 |
+
Both `incomplete_path` and `destination_path` must be on the same volume to avoid a local copy.
|
| 1816 |
+
"""
|
| 1817 |
+
if destination_path.exists() and not force_download:
|
| 1818 |
+
# Do nothing if already exists (except if force_download=True)
|
| 1819 |
+
return
|
| 1820 |
+
|
| 1821 |
+
if incomplete_path.exists() and force_download:
|
| 1822 |
+
# By default, we will try to resume the download if possible.
|
| 1823 |
+
# However, if the user has set `force_download=True`, then we should
|
| 1824 |
+
# not resume the download => delete the incomplete file.
|
| 1825 |
+
logger.debug(f"Removing incomplete file '{incomplete_path}' (force_download=True)")
|
| 1826 |
+
incomplete_path.unlink(missing_ok=True)
|
| 1827 |
+
|
| 1828 |
+
with incomplete_path.open("ab") as f:
|
| 1829 |
+
resume_size = f.tell()
|
| 1830 |
+
message = f"Downloading '{filename}' to '{incomplete_path}'"
|
| 1831 |
+
if resume_size > 0 and expected_size is not None:
|
| 1832 |
+
message += f" (resume from {resume_size}/{expected_size})"
|
| 1833 |
+
logger.debug(message)
|
| 1834 |
+
|
| 1835 |
+
if expected_size is not None: # might be None if HTTP header not set correctly
|
| 1836 |
+
# Check disk space in both tmp and destination path
|
| 1837 |
+
_check_disk_space(expected_size, incomplete_path.parent)
|
| 1838 |
+
_check_disk_space(expected_size, destination_path.parent)
|
| 1839 |
+
|
| 1840 |
+
if xet_file_data is not None and is_xet_available():
|
| 1841 |
+
logger.debug("Xet Storage is enabled for this repo. Downloading file from Xet Storage..")
|
| 1842 |
+
xet_get(
|
| 1843 |
+
incomplete_path=incomplete_path,
|
| 1844 |
+
xet_file_data=xet_file_data,
|
| 1845 |
+
headers=headers,
|
| 1846 |
+
expected_size=expected_size,
|
| 1847 |
+
displayed_filename=filename,
|
| 1848 |
+
tqdm_class=tqdm_class,
|
| 1849 |
+
)
|
| 1850 |
+
else:
|
| 1851 |
+
if xet_file_data is not None and not constants.HF_HUB_DISABLE_XET:
|
| 1852 |
+
logger.warning(
|
| 1853 |
+
"Xet Storage is enabled for this repo, but the 'hf_xet' package is not installed. "
|
| 1854 |
+
"Falling back to regular HTTP download. "
|
| 1855 |
+
"For better performance, install the package with: `pip install huggingface_hub[hf_xet]` or `pip install hf_xet`"
|
| 1856 |
+
)
|
| 1857 |
+
|
| 1858 |
+
http_get(
|
| 1859 |
+
url_to_download,
|
| 1860 |
+
f,
|
| 1861 |
+
resume_size=resume_size,
|
| 1862 |
+
headers=headers,
|
| 1863 |
+
expected_size=expected_size,
|
| 1864 |
+
tqdm_class=tqdm_class,
|
| 1865 |
+
)
|
| 1866 |
+
|
| 1867 |
+
logger.debug(f"Download complete. Moving file to {destination_path}")
|
| 1868 |
+
_chmod_and_move(incomplete_path, destination_path)
|
| 1869 |
+
|
| 1870 |
+
|
| 1871 |
+
def _int_or_none(value: str | None) -> int | None:
|
| 1872 |
+
try:
|
| 1873 |
+
return int(value) # type: ignore
|
| 1874 |
+
except (TypeError, ValueError):
|
| 1875 |
+
return None
|
| 1876 |
+
|
| 1877 |
+
|
| 1878 |
+
def _chmod_and_move(src: Path, dst: Path) -> None:
|
| 1879 |
+
"""Set correct permission before moving a blob from tmp directory to cache dir.
|
| 1880 |
+
|
| 1881 |
+
Do not take into account the `umask` from the process as there is no convenient way
|
| 1882 |
+
to get it that is thread-safe.
|
| 1883 |
+
|
| 1884 |
+
See:
|
| 1885 |
+
- About umask: https://docs.python.org/3/library/os.html#os.umask
|
| 1886 |
+
- Thread-safety: https://stackoverflow.com/a/70343066
|
| 1887 |
+
- About solution: https://github.com/huggingface/huggingface_hub/pull/1220#issuecomment-1326211591
|
| 1888 |
+
- Fix issue: https://github.com/huggingface/huggingface_hub/issues/1141
|
| 1889 |
+
- Fix issue: https://github.com/huggingface/huggingface_hub/issues/1215
|
| 1890 |
+
"""
|
| 1891 |
+
# Get umask by creating a temporary file in the cached repo folder.
|
| 1892 |
+
tmp_file = dst.parent.parent / f"tmp_{uuid.uuid4()}"
|
| 1893 |
+
try:
|
| 1894 |
+
tmp_file.touch()
|
| 1895 |
+
cache_dir_mode = Path(tmp_file).stat().st_mode
|
| 1896 |
+
os.chmod(str(src), stat.S_IMODE(cache_dir_mode))
|
| 1897 |
+
except OSError as e:
|
| 1898 |
+
logger.warning(
|
| 1899 |
+
f"Could not set the permissions on the file '{src}'. Error: {e}.\nContinuing without setting permissions."
|
| 1900 |
+
)
|
| 1901 |
+
finally:
|
| 1902 |
+
try:
|
| 1903 |
+
tmp_file.unlink()
|
| 1904 |
+
except OSError:
|
| 1905 |
+
# fails if `tmp_file.touch()` failed => do nothing
|
| 1906 |
+
# See https://github.com/huggingface/huggingface_hub/issues/2359
|
| 1907 |
+
pass
|
| 1908 |
+
|
| 1909 |
+
shutil.move(str(src), str(dst), copy_function=_copy_no_matter_what)
|
| 1910 |
+
|
| 1911 |
+
|
| 1912 |
+
def _copy_no_matter_what(src: str, dst: str) -> None:
|
| 1913 |
+
"""Copy file from src to dst.
|
| 1914 |
+
|
| 1915 |
+
If `shutil.copy2` fails, fallback to `shutil.copyfile`.
|
| 1916 |
+
"""
|
| 1917 |
+
try:
|
| 1918 |
+
# Copy file with metadata and permission
|
| 1919 |
+
# Can fail e.g. if dst is an S3 mount
|
| 1920 |
+
shutil.copy2(src, dst)
|
| 1921 |
+
except OSError:
|
| 1922 |
+
# Copy only file content
|
| 1923 |
+
shutil.copyfile(src, dst)
|
| 1924 |
+
|
| 1925 |
+
|
| 1926 |
+
def _get_pointer_path(storage_folder: str, revision: str, relative_filename: str) -> str:
|
| 1927 |
+
# Using `os.path.abspath` instead of `Path.resolve()` to avoid resolving symlinks
|
| 1928 |
+
snapshot_path = os.path.join(storage_folder, "snapshots")
|
| 1929 |
+
pointer_path = os.path.join(snapshot_path, revision, relative_filename)
|
| 1930 |
+
if Path(os.path.abspath(snapshot_path)) not in Path(os.path.abspath(pointer_path)).parents:
|
| 1931 |
+
raise ValueError(
|
| 1932 |
+
"Invalid pointer path: cannot create pointer path in snapshot folder if"
|
| 1933 |
+
f" `storage_folder='{storage_folder}'`, `revision='{revision}'` and"
|
| 1934 |
+
f" `relative_filename='{relative_filename}'`."
|
| 1935 |
+
)
|
| 1936 |
+
return pointer_path
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import threading
|
| 4 |
+
from collections import deque
|
| 5 |
+
from collections.abc import Iterable, Iterator
|
| 6 |
+
from contextlib import ExitStack
|
| 7 |
+
from copy import deepcopy
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from itertools import chain
|
| 11 |
+
from pathlib import Path, PurePosixPath
|
| 12 |
+
from typing import Any, NoReturn, Union
|
| 13 |
+
from urllib.parse import quote, unquote
|
| 14 |
+
|
| 15 |
+
import fsspec
|
| 16 |
+
import httpx
|
| 17 |
+
from fsspec.callbacks import _DEFAULT_CALLBACK, NoOpCallback, TqdmCallback
|
| 18 |
+
from fsspec.utils import isfilelike
|
| 19 |
+
|
| 20 |
+
from . import constants
|
| 21 |
+
from ._commit_api import CommitOperationCopy, CommitOperationDelete
|
| 22 |
+
from .errors import (
|
| 23 |
+
BucketNotFoundError,
|
| 24 |
+
EntryNotFoundError,
|
| 25 |
+
HfHubHTTPError,
|
| 26 |
+
RepositoryNotFoundError,
|
| 27 |
+
RevisionNotFoundError,
|
| 28 |
+
)
|
| 29 |
+
from .file_download import hf_hub_url, http_get
|
| 30 |
+
from .hf_api import SPECIAL_REFS_REVISION_REGEX, BucketFile, BucketFolder, HfApi, LastCommitInfo, RepoFile, RepoFolder
|
| 31 |
+
from .utils import HFValidationError, hf_raise_for_status, http_backoff, http_stream_backoff
|
| 32 |
+
from .utils.insecure_hashlib import md5
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class HfFileSystemResolvedPath:
|
| 37 |
+
"""Top level Data structure containing information about a resolved Hugging Face file system path."""
|
| 38 |
+
|
| 39 |
+
root: str
|
| 40 |
+
path: str
|
| 41 |
+
|
| 42 |
+
def unresolve(self) -> str:
|
| 43 |
+
return f"{self.root}/{self.path}".rstrip("/")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class HfFileSystemResolvedRepositoryPath(HfFileSystemResolvedPath):
|
| 48 |
+
"""Data structure containing information about a resolved path in a repository."""
|
| 49 |
+
|
| 50 |
+
repo_type: str
|
| 51 |
+
repo_id: str
|
| 52 |
+
revision: str
|
| 53 |
+
path_in_repo: str
|
| 54 |
+
root: str = field(init=False)
|
| 55 |
+
path: str = field(init=False)
|
| 56 |
+
# The part placed after '@' in the initial path. It can be a quoted or unquoted refs revision.
|
| 57 |
+
# Used to reconstruct the unresolved path to return to the user.
|
| 58 |
+
_raw_revision: str | None = field(default=None, repr=False)
|
| 59 |
+
|
| 60 |
+
def __post_init__(self):
|
| 61 |
+
repo_path = constants.REPO_TYPES_URL_PREFIXES.get(self.repo_type, "") + self.repo_id
|
| 62 |
+
if self._raw_revision:
|
| 63 |
+
self.root = f"{repo_path}@{self._raw_revision}"
|
| 64 |
+
elif self.revision != constants.DEFAULT_REVISION:
|
| 65 |
+
self.root = f"{repo_path}@{safe_revision(self.revision)}"
|
| 66 |
+
else:
|
| 67 |
+
self.root = repo_path
|
| 68 |
+
self.path = self.path_in_repo
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@dataclass
|
| 72 |
+
class HfFileSystemResolvedBucketPath(HfFileSystemResolvedPath):
|
| 73 |
+
"""Data structure containing information about a resolved path in a bucket."""
|
| 74 |
+
|
| 75 |
+
bucket_id: str
|
| 76 |
+
root: str = field(init=False)
|
| 77 |
+
|
| 78 |
+
def __post_init__(self):
|
| 79 |
+
self.root = "buckets/" + self.bucket_id
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# We need to improve fsspec.spec._Cached which is AbstractFileSystem's metaclass
|
| 83 |
+
_cached_base: Any = type(fsspec.AbstractFileSystem)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class _Cached(_cached_base):
|
| 87 |
+
"""
|
| 88 |
+
Metaclass for caching HfFileSystem instances according to the args.
|
| 89 |
+
|
| 90 |
+
This creates an additional reference to the filesystem, which prevents the
|
| 91 |
+
filesystem from being garbage collected when all *user* references go away.
|
| 92 |
+
A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also*
|
| 93 |
+
be made for a filesystem instance to be garbage collected.
|
| 94 |
+
|
| 95 |
+
This is a slightly modified version of `fsspec.spec._Cached` to improve it.
|
| 96 |
+
In particular in `_tokenize` the pid isn't taken into account for the
|
| 97 |
+
`fs_token` used to identify cached instances. The `fs_token` logic is also
|
| 98 |
+
robust to defaults values and the order of the args. Finally new instances
|
| 99 |
+
reuse the states from sister instances in the main thread.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def __init__(cls, *args, **kwargs):
|
| 103 |
+
# Hack: override https://github.com/fsspec/filesystem_spec/blob/dcb167e8f50e6273d4cfdfc4cab8fc5aa4c958bf/fsspec/spec.py#L53
|
| 104 |
+
super().__init__(*args, **kwargs)
|
| 105 |
+
# Note: we intentionally create a reference here, to avoid garbage
|
| 106 |
+
# collecting instances when all other references are gone. To really
|
| 107 |
+
# delete a FileSystem, the cache must be cleared.
|
| 108 |
+
cls._cache = {}
|
| 109 |
+
|
| 110 |
+
def __call__(cls, *args, **kwargs):
|
| 111 |
+
# Hack: override https://github.com/fsspec/filesystem_spec/blob/dcb167e8f50e6273d4cfdfc4cab8fc5aa4c958bf/fsspec/spec.py#L65
|
| 112 |
+
skip = kwargs.pop("skip_instance_cache", False)
|
| 113 |
+
fs_token = cls._tokenize(cls, threading.get_ident(), *args, **kwargs)
|
| 114 |
+
fs_token_main_thread = cls._tokenize(cls, threading.main_thread().ident, *args, **kwargs)
|
| 115 |
+
if not skip and cls.cachable and fs_token in cls._cache:
|
| 116 |
+
# reuse cached instance
|
| 117 |
+
cls._latest = fs_token
|
| 118 |
+
return cls._cache[fs_token]
|
| 119 |
+
else:
|
| 120 |
+
# create new instance
|
| 121 |
+
obj = type.__call__(cls, *args, **kwargs)
|
| 122 |
+
if not skip and cls.cachable and fs_token_main_thread in cls._cache:
|
| 123 |
+
# reuse the cache from the main thread instance in the new instance
|
| 124 |
+
instance_state = cls._cache[fs_token_main_thread]._get_instance_state()
|
| 125 |
+
for attr, state_value in instance_state.items():
|
| 126 |
+
setattr(obj, attr, state_value)
|
| 127 |
+
obj._fs_token_ = fs_token
|
| 128 |
+
obj.storage_args = args
|
| 129 |
+
obj.storage_options = kwargs
|
| 130 |
+
if cls.cachable and not skip:
|
| 131 |
+
cls._latest = fs_token
|
| 132 |
+
cls._cache[fs_token] = obj
|
| 133 |
+
return obj
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class HfFileSystem(fsspec.AbstractFileSystem, metaclass=_Cached):
|
| 137 |
+
"""
|
| 138 |
+
Access a remote Hugging Face Hub repository as if were a local file system.
|
| 139 |
+
|
| 140 |
+
> [!WARNING]
|
| 141 |
+
> [`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading
|
| 142 |
+
> Hugging Face datasets directly with `pandas`). However, it introduces additional overhead due to this compatibility
|
| 143 |
+
> layer. For better performance and reliability, it's recommended to use `HfApi` methods when possible.
|
| 144 |
+
|
| 145 |
+
The file system supports paths for the `hf://` protocol, which follows those URL schemes:
|
| 146 |
+
|
| 147 |
+
* Models, Datasets and Spaces repositories:
|
| 148 |
+
|
| 149 |
+
```
|
| 150 |
+
hf://<repo-id>[@<revision>]/<path/in/repo>
|
| 151 |
+
hf://datasets/<repo-id>[@<revision>]/<path/in/repo>
|
| 152 |
+
hf://spaces/<repo-id>[@<revision>]/<path/in/repo>
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
* Buckets (generic storage):
|
| 156 |
+
|
| 157 |
+
```
|
| 158 |
+
hf://buckets/<bucket-id>/<path/in/bucket>
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
Note: when using the [`HfFileSystem`] directly, passing the `hf://` protocol prefix is optional in paths.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
endpoint (`str`, *optional*):
|
| 165 |
+
Endpoint of the Hub. Defaults to <https://huggingface.co>.
|
| 166 |
+
token (`bool` or `str`, *optional*):
|
| 167 |
+
A valid user access token (string). Defaults to the locally saved
|
| 168 |
+
token, which is the recommended method for authentication (see
|
| 169 |
+
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
|
| 170 |
+
To disable authentication, pass `False`.
|
| 171 |
+
block_size (`int`, *optional*):
|
| 172 |
+
Block size for reading and writing files.
|
| 173 |
+
expand_info (`bool`, *optional*):
|
| 174 |
+
Whether to expand the information of the files.
|
| 175 |
+
**storage_options (`dict`, *optional*):
|
| 176 |
+
Additional options for the filesystem. See [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.__init__).
|
| 177 |
+
|
| 178 |
+
Usage:
|
| 179 |
+
|
| 180 |
+
```python
|
| 181 |
+
>>> from huggingface_hub import hffs
|
| 182 |
+
|
| 183 |
+
>>> # List files
|
| 184 |
+
>>> hffs.glob("my-username/my-model/*.bin")
|
| 185 |
+
['my-username/my-model/pytorch_model.bin']
|
| 186 |
+
>>> hffs.ls("datasets/my-username/my-dataset", detail=False)
|
| 187 |
+
['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json']
|
| 188 |
+
|
| 189 |
+
>>> # Read/write files
|
| 190 |
+
>>> with hffs.open("my-username/my-model/pytorch_model.bin") as f:
|
| 191 |
+
... data = f.read()
|
| 192 |
+
>>> with hffs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
|
| 193 |
+
... f.write(data)
|
| 194 |
+
```
|
| 195 |
+
|
| 196 |
+
Specify a token for authentication:
|
| 197 |
+
```python
|
| 198 |
+
>>> from huggingface_hub import HfFileSystem
|
| 199 |
+
>>> hffs = HfFileSystem(token=token)
|
| 200 |
+
```
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
root_marker = ""
|
| 204 |
+
protocol = "hf"
|
| 205 |
+
|
| 206 |
+
def __init__(
|
| 207 |
+
self,
|
| 208 |
+
*args,
|
| 209 |
+
endpoint: str | None = None,
|
| 210 |
+
token: bool | str | None = None,
|
| 211 |
+
block_size: int | None = None,
|
| 212 |
+
expand_info: bool | None = None,
|
| 213 |
+
**storage_options,
|
| 214 |
+
):
|
| 215 |
+
super().__init__(*args, **storage_options)
|
| 216 |
+
self.endpoint = endpoint or constants.ENDPOINT
|
| 217 |
+
self.token = token
|
| 218 |
+
self._api = HfApi(endpoint=endpoint, token=token)
|
| 219 |
+
self.block_size = block_size
|
| 220 |
+
self.expand_info = expand_info
|
| 221 |
+
# Maps (repo_type, repo_id, revision) to a 2-tuple with:
|
| 222 |
+
# * the 1st element indicating whether the repository and the revision exist
|
| 223 |
+
# * the 2nd element being the exception raised if the repository or revision doesn't exist
|
| 224 |
+
self._repo_and_revision_exists_cache: dict[tuple[str, str, str | None], tuple[bool, Exception | None]] = {}
|
| 225 |
+
# Same for buckets
|
| 226 |
+
self._bucket_exists_cache: dict[str, tuple[bool, Exception | None]] = {}
|
| 227 |
+
# Note: special case for buckets: revision is always None
|
| 228 |
+
# Maps parent directory path to path infos
|
| 229 |
+
self.dircache: dict[str, list[dict[str, Any]]] = {}
|
| 230 |
+
|
| 231 |
+
@classmethod
|
| 232 |
+
def _tokenize(cls, threading_ident: int, *args, **kwargs) -> str:
|
| 233 |
+
"""Deterministic token for caching"""
|
| 234 |
+
# make fs_token robust to default values and to kwargs order
|
| 235 |
+
kwargs["endpoint"] = kwargs.get("endpoint") or constants.ENDPOINT
|
| 236 |
+
kwargs["token"] = kwargs.get("token")
|
| 237 |
+
kwargs = {key: kwargs[key] for key in sorted(kwargs)}
|
| 238 |
+
# contrary to fsspec, we don't include pid here
|
| 239 |
+
tokenize_args = (cls, threading_ident, args, kwargs)
|
| 240 |
+
h = md5(str(tokenize_args).encode())
|
| 241 |
+
return h.hexdigest()
|
| 242 |
+
|
| 243 |
+
def _repo_and_revision_exist(
|
| 244 |
+
self, repo_type: str, repo_id: str, revision: str | None
|
| 245 |
+
) -> tuple[bool, Exception | None]:
|
| 246 |
+
if (repo_type, repo_id, revision) not in self._repo_and_revision_exists_cache:
|
| 247 |
+
try:
|
| 248 |
+
self._api.repo_info(
|
| 249 |
+
repo_id, revision=revision, repo_type=repo_type, timeout=constants.HF_HUB_ETAG_TIMEOUT
|
| 250 |
+
)
|
| 251 |
+
except (RepositoryNotFoundError, HFValidationError) as e:
|
| 252 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e
|
| 253 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = False, e
|
| 254 |
+
except RevisionNotFoundError as e:
|
| 255 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e
|
| 256 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None
|
| 257 |
+
else:
|
| 258 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = True, None
|
| 259 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None
|
| 260 |
+
return self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)]
|
| 261 |
+
|
| 262 |
+
def _bucket_exists(self, bucket_id: str) -> tuple[bool, Exception | None]:
|
| 263 |
+
if bucket_id not in self._bucket_exists_cache:
|
| 264 |
+
try:
|
| 265 |
+
self._api.bucket_info(bucket_id)
|
| 266 |
+
except BucketNotFoundError as e:
|
| 267 |
+
self._bucket_exists_cache[bucket_id] = False, e
|
| 268 |
+
else:
|
| 269 |
+
self._bucket_exists_cache[bucket_id] = True, None
|
| 270 |
+
return self._bucket_exists_cache[bucket_id]
|
| 271 |
+
|
| 272 |
+
def resolve_path(
|
| 273 |
+
self, path: str, revision: str | None = None
|
| 274 |
+
) -> HfFileSystemResolvedRepositoryPath | HfFileSystemResolvedBucketPath:
|
| 275 |
+
"""
|
| 276 |
+
Resolve a Hugging Face file system path into its components.
|
| 277 |
+
|
| 278 |
+
Args:
|
| 279 |
+
path (`str`):
|
| 280 |
+
Path to resolve.
|
| 281 |
+
revision (`str`, *optional*):
|
| 282 |
+
The revision of the repo to resolve. Defaults to the revision specified in the path.
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
[`HfFileSystemResolvedPath`]: Resolved path information containing `repo_type`, `repo_id`, `revision` and `path_in_repo`.
|
| 286 |
+
|
| 287 |
+
Raises:
|
| 288 |
+
`ValueError`:
|
| 289 |
+
If path contains conflicting revision information.
|
| 290 |
+
`NotImplementedError`:
|
| 291 |
+
If trying to list repositories.
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
def _align_revision_in_path_with_revision(revision_in_path: str | None, revision: str | None) -> str | None:
|
| 295 |
+
if revision is not None:
|
| 296 |
+
if revision_in_path is not None and revision_in_path != revision:
|
| 297 |
+
raise ValueError(
|
| 298 |
+
f'Revision specified in path ("{revision_in_path}") and in `revision` argument ("{revision}")'
|
| 299 |
+
" are not the same."
|
| 300 |
+
)
|
| 301 |
+
else:
|
| 302 |
+
revision = revision_in_path
|
| 303 |
+
return revision
|
| 304 |
+
|
| 305 |
+
path = self._strip_protocol(path)
|
| 306 |
+
if not path:
|
| 307 |
+
# can't list repositories at root
|
| 308 |
+
raise NotImplementedError("Access to buckets and repositories lists is not implemented.")
|
| 309 |
+
elif path.split("/")[0] == "buckets":
|
| 310 |
+
bucket_id = "/".join(path.split("/")[1:3])
|
| 311 |
+
path = "/".join(path.split("/")[3:])
|
| 312 |
+
bucket_exists, err = self._bucket_exists(bucket_id)
|
| 313 |
+
if not bucket_exists:
|
| 314 |
+
_raise_file_not_found(path, err)
|
| 315 |
+
return HfFileSystemResolvedBucketPath(bucket_id=bucket_id, path=path)
|
| 316 |
+
elif path.split("/")[0] + "/" in constants.REPO_TYPES_URL_PREFIXES.values():
|
| 317 |
+
if "/" not in path:
|
| 318 |
+
# can't list repositories at the repository type level
|
| 319 |
+
raise NotImplementedError("Access to repositories lists is not implemented.")
|
| 320 |
+
repo_type, path = path.split("/", 1)
|
| 321 |
+
repo_type = constants.REPO_TYPES_MAPPING[repo_type]
|
| 322 |
+
else:
|
| 323 |
+
repo_type = constants.REPO_TYPE_MODEL
|
| 324 |
+
if path.count("/") > 0:
|
| 325 |
+
if "@" in "/".join(path.split("/")[:2]):
|
| 326 |
+
repo_id, revision_in_path = path.split("@", 1)
|
| 327 |
+
if "/" in revision_in_path:
|
| 328 |
+
match = SPECIAL_REFS_REVISION_REGEX.search(revision_in_path)
|
| 329 |
+
if match is not None and revision in (None, match.group()):
|
| 330 |
+
# Handle `refs/convert/parquet` and PR revisions separately
|
| 331 |
+
path_in_repo = SPECIAL_REFS_REVISION_REGEX.sub("", revision_in_path).lstrip("/")
|
| 332 |
+
revision_in_path = match.group()
|
| 333 |
+
else:
|
| 334 |
+
revision_in_path, path_in_repo = revision_in_path.split("/", 1)
|
| 335 |
+
else:
|
| 336 |
+
path_in_repo = ""
|
| 337 |
+
revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision)
|
| 338 |
+
repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision)
|
| 339 |
+
if not repo_and_revision_exist:
|
| 340 |
+
_raise_file_not_found(path, err)
|
| 341 |
+
else:
|
| 342 |
+
revision_in_path = None
|
| 343 |
+
repo_id_with_namespace = "/".join(path.split("/")[:2])
|
| 344 |
+
path_in_repo_with_namespace = "/".join(path.split("/")[2:])
|
| 345 |
+
repo_id_without_namespace = path.split("/")[0]
|
| 346 |
+
path_in_repo_without_namespace = "/".join(path.split("/")[1:])
|
| 347 |
+
repo_id = repo_id_with_namespace
|
| 348 |
+
path_in_repo = path_in_repo_with_namespace
|
| 349 |
+
repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision)
|
| 350 |
+
if not repo_and_revision_exist:
|
| 351 |
+
if isinstance(err, (RepositoryNotFoundError, HFValidationError)):
|
| 352 |
+
repo_id = repo_id_without_namespace
|
| 353 |
+
path_in_repo = path_in_repo_without_namespace
|
| 354 |
+
repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision)
|
| 355 |
+
if not repo_and_revision_exist:
|
| 356 |
+
_raise_file_not_found(path, err)
|
| 357 |
+
else:
|
| 358 |
+
_raise_file_not_found(path, err)
|
| 359 |
+
else:
|
| 360 |
+
repo_id = path
|
| 361 |
+
path_in_repo = ""
|
| 362 |
+
if "@" in path:
|
| 363 |
+
repo_id, revision_in_path = path.split("@", 1)
|
| 364 |
+
revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision)
|
| 365 |
+
else:
|
| 366 |
+
revision_in_path = None
|
| 367 |
+
repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision)
|
| 368 |
+
if not repo_and_revision_exist:
|
| 369 |
+
raise NotImplementedError("Access to repositories lists is not implemented.")
|
| 370 |
+
|
| 371 |
+
revision = revision if revision is not None else constants.DEFAULT_REVISION
|
| 372 |
+
return HfFileSystemResolvedRepositoryPath(
|
| 373 |
+
repo_type, repo_id, revision, path_in_repo, _raw_revision=revision_in_path
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
def invalidate_cache(self, path: str | None = None) -> None:
|
| 377 |
+
"""
|
| 378 |
+
Clear the cache for a given path.
|
| 379 |
+
|
| 380 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.invalidate_cache).
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
path (`str`, *optional*):
|
| 384 |
+
Path to clear from cache. If not provided, clear the entire cache.
|
| 385 |
+
|
| 386 |
+
"""
|
| 387 |
+
if not path:
|
| 388 |
+
self.dircache.clear()
|
| 389 |
+
self._repo_and_revision_exists_cache.clear()
|
| 390 |
+
else:
|
| 391 |
+
resolved_path = self.resolve_path(path)
|
| 392 |
+
path = resolved_path.unresolve()
|
| 393 |
+
while path:
|
| 394 |
+
self.dircache.pop(path, None)
|
| 395 |
+
path = self._parent(path)
|
| 396 |
+
|
| 397 |
+
# Only clear repo cache if path is to repo root
|
| 398 |
+
if not resolved_path.path:
|
| 399 |
+
if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath):
|
| 400 |
+
self._repo_and_revision_exists_cache.pop(
|
| 401 |
+
(resolved_path.repo_type, resolved_path.repo_id, None), None
|
| 402 |
+
)
|
| 403 |
+
self._repo_and_revision_exists_cache.pop(
|
| 404 |
+
(resolved_path.repo_type, resolved_path.repo_id, resolved_path.revision), None
|
| 405 |
+
)
|
| 406 |
+
else:
|
| 407 |
+
self._bucket_exists_cache.pop(resolved_path.bucket_id, None)
|
| 408 |
+
|
| 409 |
+
def _open( # type: ignore
|
| 410 |
+
self,
|
| 411 |
+
path: str,
|
| 412 |
+
mode: str = "rb",
|
| 413 |
+
block_size: int | None = None,
|
| 414 |
+
revision: str | None = None,
|
| 415 |
+
**kwargs,
|
| 416 |
+
) -> Union["HfFileSystemFile", "HfFileSystemStreamFile"]:
|
| 417 |
+
block_size = block_size if block_size is not None else self.block_size
|
| 418 |
+
if block_size is not None:
|
| 419 |
+
kwargs["block_size"] = block_size
|
| 420 |
+
if "a" in mode:
|
| 421 |
+
raise NotImplementedError("Appending to remote files is not yet supported.")
|
| 422 |
+
if block_size == 0:
|
| 423 |
+
return HfFileSystemStreamFile(self, path, mode=mode, revision=revision, **kwargs)
|
| 424 |
+
else:
|
| 425 |
+
return HfFileSystemFile(self, path, mode=mode, revision=revision, **kwargs)
|
| 426 |
+
|
| 427 |
+
def _rm(self, path: str, revision: str | None = None, **kwargs) -> None:
|
| 428 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 429 |
+
if isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 430 |
+
self._api.batch_bucket_files(resolved_path.bucket_id, delete=[resolved_path.path])
|
| 431 |
+
else:
|
| 432 |
+
self._api.delete_file(
|
| 433 |
+
path_in_repo=resolved_path.path_in_repo,
|
| 434 |
+
repo_id=resolved_path.repo_id,
|
| 435 |
+
token=self.token,
|
| 436 |
+
repo_type=resolved_path.repo_type,
|
| 437 |
+
revision=resolved_path.revision,
|
| 438 |
+
commit_message=kwargs.get("commit_message"),
|
| 439 |
+
commit_description=kwargs.get("commit_description"),
|
| 440 |
+
)
|
| 441 |
+
self.invalidate_cache(path=resolved_path.unresolve())
|
| 442 |
+
|
| 443 |
+
def rm(
|
| 444 |
+
self,
|
| 445 |
+
path: str,
|
| 446 |
+
recursive: bool = False,
|
| 447 |
+
maxdepth: int | None = None,
|
| 448 |
+
revision: str | None = None,
|
| 449 |
+
**kwargs,
|
| 450 |
+
) -> None:
|
| 451 |
+
"""
|
| 452 |
+
Delete files from a repository.
|
| 453 |
+
|
| 454 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.rm).
|
| 455 |
+
|
| 456 |
+
> [!WARNING]
|
| 457 |
+
> Note: When possible, use `HfApi.delete_file()` for better performance.
|
| 458 |
+
|
| 459 |
+
Args:
|
| 460 |
+
path (`str`):
|
| 461 |
+
Path to delete.
|
| 462 |
+
recursive (`bool`, *optional*):
|
| 463 |
+
If True, delete directory and all its contents. Defaults to False.
|
| 464 |
+
maxdepth (`int`, *optional*):
|
| 465 |
+
Maximum number of subdirectories to visit when deleting recursively.
|
| 466 |
+
revision (`str`, *optional*):
|
| 467 |
+
The git revision to delete from.
|
| 468 |
+
|
| 469 |
+
"""
|
| 470 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 471 |
+
paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth, revision=revision)
|
| 472 |
+
if isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 473 |
+
delete = [self.resolve_path(path).path for path in paths if not self.isdir(path)]
|
| 474 |
+
self._api.batch_bucket_files(resolved_path.bucket_id, delete=delete)
|
| 475 |
+
else:
|
| 476 |
+
paths_in_repo = [self.resolve_path(path).path for path in paths if not self.isdir(path)]
|
| 477 |
+
operations = [CommitOperationDelete(path_in_repo=path_in_repo) for path_in_repo in paths_in_repo]
|
| 478 |
+
commit_message = f"Delete {path} "
|
| 479 |
+
commit_message += "recursively " if recursive else ""
|
| 480 |
+
commit_message += f"up to depth {maxdepth} " if maxdepth is not None else ""
|
| 481 |
+
# TODO: use `commit_description` to list all the deleted paths?
|
| 482 |
+
self._api.create_commit(
|
| 483 |
+
repo_id=resolved_path.repo_id,
|
| 484 |
+
repo_type=resolved_path.repo_type,
|
| 485 |
+
token=self.token,
|
| 486 |
+
operations=operations,
|
| 487 |
+
revision=resolved_path.revision,
|
| 488 |
+
commit_message=kwargs.get("commit_message", commit_message),
|
| 489 |
+
commit_description=kwargs.get("commit_description"),
|
| 490 |
+
)
|
| 491 |
+
self.invalidate_cache(path=resolved_path.unresolve())
|
| 492 |
+
|
| 493 |
+
def ls(
|
| 494 |
+
self, path: str, detail: bool = True, refresh: bool = False, revision: str | None = None, **kwargs
|
| 495 |
+
) -> list[str | dict[str, Any]]:
|
| 496 |
+
"""
|
| 497 |
+
List the contents of a directory.
|
| 498 |
+
|
| 499 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.ls).
|
| 500 |
+
|
| 501 |
+
> [!WARNING]
|
| 502 |
+
> Note: When possible, use `HfApi.list_repo_tree()` for better performance.
|
| 503 |
+
|
| 504 |
+
Args:
|
| 505 |
+
path (`str`):
|
| 506 |
+
Path to the directory.
|
| 507 |
+
detail (`bool`, *optional*):
|
| 508 |
+
If True, returns a list of dictionaries containing file information. If False,
|
| 509 |
+
returns a list of file paths. Defaults to True.
|
| 510 |
+
refresh (`bool`, *optional*):
|
| 511 |
+
If True, bypass the cache and fetch the latest data. Defaults to False.
|
| 512 |
+
revision (`str`, *optional*):
|
| 513 |
+
The git revision to list from.
|
| 514 |
+
|
| 515 |
+
Returns:
|
| 516 |
+
`list[Union[str, dict[str, Any]]]`: List of file paths (if detail=False) or list of file information
|
| 517 |
+
dictionaries (if detail=True).
|
| 518 |
+
"""
|
| 519 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 520 |
+
path = resolved_path.unresolve()
|
| 521 |
+
try:
|
| 522 |
+
out = self._ls_tree(path, refresh=refresh, revision=revision, **kwargs)
|
| 523 |
+
except EntryNotFoundError:
|
| 524 |
+
# Path could be a file
|
| 525 |
+
if not resolved_path.path:
|
| 526 |
+
_raise_file_not_found(path, None)
|
| 527 |
+
try:
|
| 528 |
+
out = self._ls_tree(self._parent(path), refresh=refresh, revision=revision, **kwargs)
|
| 529 |
+
except EntryNotFoundError:
|
| 530 |
+
out = []
|
| 531 |
+
out = [o for o in out if o["name"] == path]
|
| 532 |
+
if len(out) == 0:
|
| 533 |
+
_raise_file_not_found(path, None)
|
| 534 |
+
return out if detail else [o["name"] for o in out]
|
| 535 |
+
|
| 536 |
+
def _ls_tree(
|
| 537 |
+
self,
|
| 538 |
+
path: str,
|
| 539 |
+
recursive: bool = False,
|
| 540 |
+
refresh: bool = False,
|
| 541 |
+
revision: str | None = None,
|
| 542 |
+
expand_info: bool | None = None,
|
| 543 |
+
maxdepth: int | None = None,
|
| 544 |
+
):
|
| 545 |
+
expand_info = (
|
| 546 |
+
expand_info if expand_info is not None else (self.expand_info if self.expand_info is not None else False)
|
| 547 |
+
)
|
| 548 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 549 |
+
path = resolved_path.unresolve()
|
| 550 |
+
root_path = resolved_path.root
|
| 551 |
+
maxdepth = maxdepth if recursive else 1
|
| 552 |
+
|
| 553 |
+
out = []
|
| 554 |
+
if path in self.dircache and not refresh:
|
| 555 |
+
cached_path_infos = self.dircache[path]
|
| 556 |
+
out.extend(cached_path_infos)
|
| 557 |
+
dirs_not_in_dircache = []
|
| 558 |
+
if recursive:
|
| 559 |
+
# Use BFS to traverse the cache and build the "recursive "output
|
| 560 |
+
# (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)
|
| 561 |
+
depth = 2
|
| 562 |
+
dirs_to_visit = deque(
|
| 563 |
+
[(depth, path_info) for path_info in cached_path_infos if path_info["type"] == "directory"]
|
| 564 |
+
)
|
| 565 |
+
while dirs_to_visit:
|
| 566 |
+
depth, dir_info = dirs_to_visit.popleft()
|
| 567 |
+
if maxdepth is None or depth <= maxdepth:
|
| 568 |
+
if dir_info["name"] not in self.dircache:
|
| 569 |
+
dirs_not_in_dircache.append(dir_info["name"])
|
| 570 |
+
else:
|
| 571 |
+
cached_path_infos = self.dircache[dir_info["name"]]
|
| 572 |
+
out.extend(cached_path_infos)
|
| 573 |
+
dirs_to_visit.extend(
|
| 574 |
+
[
|
| 575 |
+
(depth + 1, path_info)
|
| 576 |
+
for path_info in cached_path_infos
|
| 577 |
+
if path_info["type"] == "directory"
|
| 578 |
+
]
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
dirs_not_expanded = []
|
| 582 |
+
if expand_info and isinstance(resolved_path, HfFileSystemResolvedRepositoryPath):
|
| 583 |
+
# Check if there are directories in repos with non-expanded entries
|
| 584 |
+
dirs_not_expanded = [self._parent(o["name"]) for o in out if o["last_commit"] is None]
|
| 585 |
+
|
| 586 |
+
if (recursive and dirs_not_in_dircache) or (expand_info and dirs_not_expanded):
|
| 587 |
+
# If the dircache is incomplete, find the common path of the missing and non-expanded entries
|
| 588 |
+
# and extend the output with the result of `_ls_tree(common_path, recursive=True)`
|
| 589 |
+
common_prefix = os.path.commonprefix(dirs_not_in_dircache + dirs_not_expanded)
|
| 590 |
+
# Get the parent directory if the common prefix itself is not a directory
|
| 591 |
+
common_path = (
|
| 592 |
+
common_prefix.rstrip("/")
|
| 593 |
+
if common_prefix.endswith("/")
|
| 594 |
+
or common_prefix == root_path
|
| 595 |
+
or common_prefix in chain(dirs_not_in_dircache, dirs_not_expanded)
|
| 596 |
+
else self._parent(common_prefix)
|
| 597 |
+
)
|
| 598 |
+
if maxdepth is not None:
|
| 599 |
+
common_path_depth = common_path[len(path) :].count("/")
|
| 600 |
+
maxdepth -= common_path_depth
|
| 601 |
+
out = [o for o in out if not o["name"].startswith(common_path + "/")]
|
| 602 |
+
for cached_path in list(self.dircache):
|
| 603 |
+
if cached_path.startswith(common_path + "/"):
|
| 604 |
+
self.dircache.pop(cached_path, None)
|
| 605 |
+
self.dircache.pop(common_path, None)
|
| 606 |
+
out.extend(
|
| 607 |
+
self._ls_tree(
|
| 608 |
+
common_path,
|
| 609 |
+
recursive=recursive,
|
| 610 |
+
refresh=True,
|
| 611 |
+
revision=revision,
|
| 612 |
+
expand_info=expand_info,
|
| 613 |
+
maxdepth=maxdepth,
|
| 614 |
+
)
|
| 615 |
+
)
|
| 616 |
+
else:
|
| 617 |
+
tree: Iterable[RepoFile | RepoFolder | BucketFile | BucketFolder]
|
| 618 |
+
if isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 619 |
+
tree = self._list_bucket_tree_with_folders(
|
| 620 |
+
resolved_path.bucket_id,
|
| 621 |
+
prefix=resolved_path.path,
|
| 622 |
+
recursive=recursive,
|
| 623 |
+
)
|
| 624 |
+
else:
|
| 625 |
+
tree = self._api.list_repo_tree(
|
| 626 |
+
resolved_path.repo_id,
|
| 627 |
+
resolved_path.path,
|
| 628 |
+
recursive=recursive,
|
| 629 |
+
expand=expand_info,
|
| 630 |
+
revision=resolved_path.revision,
|
| 631 |
+
repo_type=resolved_path.repo_type,
|
| 632 |
+
)
|
| 633 |
+
for path_info in tree:
|
| 634 |
+
cache_path = root_path + "/" + path_info.path
|
| 635 |
+
if isinstance(path_info, RepoFile):
|
| 636 |
+
cache_path_info = {
|
| 637 |
+
"name": cache_path,
|
| 638 |
+
"size": path_info.size,
|
| 639 |
+
"type": "file",
|
| 640 |
+
"blob_id": path_info.blob_id,
|
| 641 |
+
"lfs": path_info.lfs,
|
| 642 |
+
"xet_hash": path_info.xet_hash,
|
| 643 |
+
"last_commit": path_info.last_commit,
|
| 644 |
+
"security": path_info.security,
|
| 645 |
+
}
|
| 646 |
+
elif isinstance(path_info, BucketFile):
|
| 647 |
+
cache_path_info = {
|
| 648 |
+
"name": cache_path,
|
| 649 |
+
"size": path_info.size,
|
| 650 |
+
"type": "file",
|
| 651 |
+
"xet_hash": path_info.xet_hash,
|
| 652 |
+
"mtime": path_info.mtime,
|
| 653 |
+
"uploaded_at": path_info.uploaded_at,
|
| 654 |
+
}
|
| 655 |
+
elif isinstance(path_info, RepoFolder):
|
| 656 |
+
cache_path_info = {
|
| 657 |
+
"name": cache_path,
|
| 658 |
+
"size": 0,
|
| 659 |
+
"type": "directory",
|
| 660 |
+
"tree_id": path_info.tree_id,
|
| 661 |
+
"last_commit": path_info.last_commit,
|
| 662 |
+
}
|
| 663 |
+
else:
|
| 664 |
+
cache_path_info = {
|
| 665 |
+
"name": cache_path,
|
| 666 |
+
"size": 0,
|
| 667 |
+
"type": "directory",
|
| 668 |
+
"uploaded_at": path_info.uploaded_at,
|
| 669 |
+
}
|
| 670 |
+
parent_path = self._parent(cache_path_info["name"])
|
| 671 |
+
self.dircache.setdefault(parent_path, []).append(cache_path_info)
|
| 672 |
+
depth = cache_path[len(path) :].count("/")
|
| 673 |
+
if maxdepth is None or depth <= maxdepth:
|
| 674 |
+
out.append(cache_path_info)
|
| 675 |
+
return out
|
| 676 |
+
|
| 677 |
+
def _list_bucket_tree_with_folders(
|
| 678 |
+
self, bucket_id: str, prefix: str, recursive: bool
|
| 679 |
+
) -> Iterable[BucketFile | BucketFolder]:
|
| 680 |
+
"""Same as `HfApi.list_bucket_tree` but always includes folders"""
|
| 681 |
+
bucket_files = self._api.list_bucket_tree(bucket_id, prefix, recursive=recursive)
|
| 682 |
+
bucket_folders: dict[str, BucketFolder] = {}
|
| 683 |
+
min_depth = 1 + prefix.count("/") if prefix else 0
|
| 684 |
+
out: list[BucketFile | BucketFolder] = []
|
| 685 |
+
|
| 686 |
+
for bucket_entry in bucket_files:
|
| 687 |
+
out.append(bucket_entry)
|
| 688 |
+
|
| 689 |
+
# If recursive=False, both files and folders are returned by the server => nothing to do
|
| 690 |
+
if not recursive:
|
| 691 |
+
continue
|
| 692 |
+
|
| 693 |
+
# Otherwise, let's rebuild BucketFolders manually
|
| 694 |
+
for parent_bucket_folder_str in list(PurePosixPath(bucket_entry.path).parents)[: -min_depth - 1]:
|
| 695 |
+
parent_bucket_folder = BucketFolder(
|
| 696 |
+
type="directory", path=str(parent_bucket_folder_str), uploaded_at=bucket_entry.uploaded_at
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
# If folder not visited yet, add it
|
| 700 |
+
if parent_bucket_folder.path not in bucket_folders:
|
| 701 |
+
out.append(parent_bucket_folder)
|
| 702 |
+
bucket_folders[parent_bucket_folder.path] = parent_bucket_folder
|
| 703 |
+
continue
|
| 704 |
+
|
| 705 |
+
# Otherwise, get back BucketFolder object and update its 'uploaded_at'
|
| 706 |
+
if parent_bucket_folder.uploaded_at is not None:
|
| 707 |
+
bucket_folder = bucket_folders[parent_bucket_folder.path]
|
| 708 |
+
if bucket_folder.uploaded_at is None or (
|
| 709 |
+
bucket_folder.uploaded_at < parent_bucket_folder.uploaded_at
|
| 710 |
+
):
|
| 711 |
+
bucket_folder.uploaded_at = parent_bucket_folder.uploaded_at
|
| 712 |
+
|
| 713 |
+
if not out:
|
| 714 |
+
raise EntryNotFoundError(f"File not found in bucket '{bucket_id}': '{prefix}'")
|
| 715 |
+
return out
|
| 716 |
+
|
| 717 |
+
def walk(self, path: str, *args, **kwargs) -> Iterator[tuple[str, list[str], list[str]]]:
|
| 718 |
+
"""
|
| 719 |
+
Return all files below the given path.
|
| 720 |
+
|
| 721 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.walk).
|
| 722 |
+
|
| 723 |
+
Args:
|
| 724 |
+
path (`str`):
|
| 725 |
+
Root path to list files from.
|
| 726 |
+
|
| 727 |
+
Returns:
|
| 728 |
+
`Iterator[tuple[str, list[str], list[str]]]`: An iterator of (path, list of directory names, list of file names) tuples.
|
| 729 |
+
"""
|
| 730 |
+
path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve()
|
| 731 |
+
yield from super().walk(path, *args, **kwargs)
|
| 732 |
+
|
| 733 |
+
def glob(self, path: str, maxdepth: int | None = None, **kwargs) -> list[str]:
|
| 734 |
+
"""
|
| 735 |
+
Find files by glob-matching.
|
| 736 |
+
|
| 737 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.glob).
|
| 738 |
+
|
| 739 |
+
Args:
|
| 740 |
+
path (`str`):
|
| 741 |
+
Path pattern to match.
|
| 742 |
+
|
| 743 |
+
Returns:
|
| 744 |
+
`list[str]`: List of paths matching the pattern.
|
| 745 |
+
"""
|
| 746 |
+
path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve()
|
| 747 |
+
return super().glob(path, maxdepth=maxdepth, **kwargs)
|
| 748 |
+
|
| 749 |
+
def find(
|
| 750 |
+
self,
|
| 751 |
+
path: str,
|
| 752 |
+
maxdepth: int | None = None,
|
| 753 |
+
withdirs: bool = False,
|
| 754 |
+
detail: bool = False,
|
| 755 |
+
refresh: bool = False,
|
| 756 |
+
revision: str | None = None,
|
| 757 |
+
**kwargs,
|
| 758 |
+
) -> list[str] | dict[str, dict[str, Any]]:
|
| 759 |
+
"""
|
| 760 |
+
List all files below path.
|
| 761 |
+
|
| 762 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.find).
|
| 763 |
+
|
| 764 |
+
Args:
|
| 765 |
+
path (`str`):
|
| 766 |
+
Root path to list files from.
|
| 767 |
+
maxdepth (`int`, *optional*):
|
| 768 |
+
Maximum depth to descend into subdirectories.
|
| 769 |
+
withdirs (`bool`, *optional*):
|
| 770 |
+
Include directory paths in the output. Defaults to False.
|
| 771 |
+
detail (`bool`, *optional*):
|
| 772 |
+
If True, returns a dict mapping paths to file information. Defaults to False.
|
| 773 |
+
refresh (`bool`, *optional*):
|
| 774 |
+
If True, bypass the cache and fetch the latest data. Defaults to False.
|
| 775 |
+
revision (`str`, *optional*):
|
| 776 |
+
The git revision to list from.
|
| 777 |
+
|
| 778 |
+
Returns:
|
| 779 |
+
`Union[list[str], dict[str, dict[str, Any]]]`: List of paths or dict of file information.
|
| 780 |
+
"""
|
| 781 |
+
if maxdepth is not None and maxdepth < 1:
|
| 782 |
+
raise ValueError("maxdepth must be at least 1")
|
| 783 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 784 |
+
path = resolved_path.unresolve()
|
| 785 |
+
try:
|
| 786 |
+
out = self._ls_tree(path, recursive=True, refresh=refresh, maxdepth=maxdepth, **kwargs)
|
| 787 |
+
except EntryNotFoundError:
|
| 788 |
+
# Path could be a file
|
| 789 |
+
try:
|
| 790 |
+
if self.info(path, revision=revision, **kwargs)["type"] == "file":
|
| 791 |
+
out = {path: {}}
|
| 792 |
+
else:
|
| 793 |
+
out = {}
|
| 794 |
+
except FileNotFoundError:
|
| 795 |
+
out = {}
|
| 796 |
+
else:
|
| 797 |
+
if not withdirs:
|
| 798 |
+
out = [o for o in out if o["type"] != "directory"]
|
| 799 |
+
else:
|
| 800 |
+
# If `withdirs=True`, include the directory itself to be consistent with the spec
|
| 801 |
+
path_info = self.info(path, **kwargs)
|
| 802 |
+
out = [path_info] + out if path_info["type"] == "directory" else out
|
| 803 |
+
out = {o["name"]: o for o in out}
|
| 804 |
+
names = sorted(out)
|
| 805 |
+
if not detail:
|
| 806 |
+
return names
|
| 807 |
+
else:
|
| 808 |
+
return {name: out[name] for name in names}
|
| 809 |
+
|
| 810 |
+
def cp_file(self, path1: str, path2: str, revision: str | None = None, **kwargs) -> None:
|
| 811 |
+
"""
|
| 812 |
+
Copy a file within or between repositories.
|
| 813 |
+
|
| 814 |
+
> [!WARNING]
|
| 815 |
+
> Note: When possible, use `HfApi.upload_file()` for better performance.
|
| 816 |
+
|
| 817 |
+
Args:
|
| 818 |
+
path1 (`str`):
|
| 819 |
+
Source path to copy from.
|
| 820 |
+
path2 (`str`):
|
| 821 |
+
Destination path to copy to.
|
| 822 |
+
revision (`str`, *optional*):
|
| 823 |
+
The git revision to copy from.
|
| 824 |
+
|
| 825 |
+
"""
|
| 826 |
+
resolved_path1 = self.resolve_path(path1, revision=revision)
|
| 827 |
+
resolved_path2 = self.resolve_path(path2, revision=revision)
|
| 828 |
+
if isinstance(resolved_path1, HfFileSystemResolvedBucketPath) or isinstance(
|
| 829 |
+
resolved_path2, HfFileSystemResolvedBucketPath
|
| 830 |
+
):
|
| 831 |
+
raise NotImplementedError("Copy from/to buckets is not available yet")
|
| 832 |
+
|
| 833 |
+
same_repo = (
|
| 834 |
+
resolved_path1.repo_type == resolved_path2.repo_type and resolved_path1.repo_id == resolved_path2.repo_id
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
if same_repo:
|
| 838 |
+
commit_message = f"Copy {path1} to {path2}"
|
| 839 |
+
self._api.create_commit(
|
| 840 |
+
repo_id=resolved_path1.repo_id,
|
| 841 |
+
repo_type=resolved_path1.repo_type,
|
| 842 |
+
revision=resolved_path2.revision,
|
| 843 |
+
commit_message=kwargs.get("commit_message", commit_message),
|
| 844 |
+
commit_description=kwargs.get("commit_description", ""),
|
| 845 |
+
operations=[
|
| 846 |
+
CommitOperationCopy(
|
| 847 |
+
src_path_in_repo=resolved_path1.path_in_repo,
|
| 848 |
+
path_in_repo=resolved_path2.path_in_repo,
|
| 849 |
+
src_revision=resolved_path1.revision,
|
| 850 |
+
)
|
| 851 |
+
],
|
| 852 |
+
)
|
| 853 |
+
else:
|
| 854 |
+
with self.open(path1, "rb", revision=resolved_path1.revision) as f:
|
| 855 |
+
content = f.read()
|
| 856 |
+
commit_message = f"Copy {path1} to {path2}"
|
| 857 |
+
self._api.upload_file(
|
| 858 |
+
path_or_fileobj=content,
|
| 859 |
+
path_in_repo=resolved_path2.path_in_repo,
|
| 860 |
+
repo_id=resolved_path2.repo_id,
|
| 861 |
+
token=self.token,
|
| 862 |
+
repo_type=resolved_path2.repo_type,
|
| 863 |
+
revision=resolved_path2.revision,
|
| 864 |
+
commit_message=kwargs.get("commit_message", commit_message),
|
| 865 |
+
commit_description=kwargs.get("commit_description"),
|
| 866 |
+
)
|
| 867 |
+
self.invalidate_cache(path=resolved_path1.unresolve())
|
| 868 |
+
self.invalidate_cache(path=resolved_path2.unresolve())
|
| 869 |
+
|
| 870 |
+
def modified(self, path: str, **kwargs) -> datetime:
|
| 871 |
+
"""
|
| 872 |
+
Get the last modified time of a file.
|
| 873 |
+
|
| 874 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.modified).
|
| 875 |
+
|
| 876 |
+
Args:
|
| 877 |
+
path (`str`):
|
| 878 |
+
Path to the file.
|
| 879 |
+
|
| 880 |
+
Returns:
|
| 881 |
+
`datetime`: Last modified time of the file.
|
| 882 |
+
"""
|
| 883 |
+
info = self.info(path, **{**kwargs, "expand_info": True}) # type: ignore
|
| 884 |
+
if "last_commit" in info:
|
| 885 |
+
if info["last_commit"] is None:
|
| 886 |
+
raise NotImplementedError(f"'modified' is not implemented for repository paths like '{path}'")
|
| 887 |
+
return info["last_commit"].date
|
| 888 |
+
elif "mtime" in info and info["mtime"]:
|
| 889 |
+
return info["mtime"]
|
| 890 |
+
elif "uploaded_at" in info and info["uploaded_at"]:
|
| 891 |
+
return info["uploaded_at"]
|
| 892 |
+
else:
|
| 893 |
+
raise NotImplementedError(f"Cannot determined 'modified' for path '{path}' (info: {info})")
|
| 894 |
+
|
| 895 |
+
def info(self, path: str, refresh: bool = False, revision: str | None = None, **kwargs) -> dict[str, Any]:
|
| 896 |
+
"""
|
| 897 |
+
Get information about a file or directory.
|
| 898 |
+
|
| 899 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.info).
|
| 900 |
+
|
| 901 |
+
> [!WARNING]
|
| 902 |
+
> Note: When possible, use `HfApi.get_paths_info()` or `HfApi.repo_info()` for better performance
|
| 903 |
+
> (or `HfApi.get_bucket_paths_info()` or `HfApi.bucket_info()` for buckets)
|
| 904 |
+
|
| 905 |
+
Args:
|
| 906 |
+
path (`str`):
|
| 907 |
+
Path to get info for.
|
| 908 |
+
refresh (`bool`, *optional*):
|
| 909 |
+
If True, bypass the cache and fetch the latest data. Defaults to False.
|
| 910 |
+
revision (`str`, *optional*):
|
| 911 |
+
The git revision to get info from.
|
| 912 |
+
|
| 913 |
+
Returns:
|
| 914 |
+
`dict[str, Any]`: Dictionary containing file information (type, size, commit info, etc.).
|
| 915 |
+
|
| 916 |
+
"""
|
| 917 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 918 |
+
path = resolved_path.unresolve()
|
| 919 |
+
expand_info = kwargs.get(
|
| 920 |
+
"expand_info", self.expand_info if self.expand_info is not None else False
|
| 921 |
+
) # don't expose it as a parameter in the public API to follow the spec
|
| 922 |
+
out: dict[str, Any] | None
|
| 923 |
+
if not resolved_path.path:
|
| 924 |
+
# Path is the root directory
|
| 925 |
+
out = {
|
| 926 |
+
"name": path,
|
| 927 |
+
"size": 0,
|
| 928 |
+
"type": "directory",
|
| 929 |
+
}
|
| 930 |
+
if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath):
|
| 931 |
+
out["last_commit"] = None
|
| 932 |
+
if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath) and expand_info:
|
| 933 |
+
last_commit = self._api.list_repo_commits(
|
| 934 |
+
resolved_path.repo_id, repo_type=resolved_path.repo_type, revision=resolved_path.revision
|
| 935 |
+
)[-1]
|
| 936 |
+
out = {
|
| 937 |
+
**out,
|
| 938 |
+
"tree_id": None, # TODO: tree_id of the root directory?
|
| 939 |
+
"last_commit": LastCommitInfo(
|
| 940 |
+
oid=last_commit.commit_id, title=last_commit.title, date=last_commit.created_at
|
| 941 |
+
),
|
| 942 |
+
}
|
| 943 |
+
elif isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 944 |
+
parent_path = self._parent(path)
|
| 945 |
+
# Fill the cache with cheap call
|
| 946 |
+
self.ls(parent_path, refresh=refresh)
|
| 947 |
+
out1 = [o for o in self.dircache[parent_path] if o["name"] == path]
|
| 948 |
+
if not out1:
|
| 949 |
+
_raise_file_not_found(path, None)
|
| 950 |
+
out = out1[0]
|
| 951 |
+
else:
|
| 952 |
+
out = None
|
| 953 |
+
parent_path = self._parent(path)
|
| 954 |
+
if not expand_info and parent_path not in self.dircache:
|
| 955 |
+
# Fill the cache with cheap call
|
| 956 |
+
self.ls(parent_path)
|
| 957 |
+
if parent_path in self.dircache:
|
| 958 |
+
# Check if the path is in the cache
|
| 959 |
+
out1 = [o for o in self.dircache[parent_path] if o["name"] == path]
|
| 960 |
+
if not out1:
|
| 961 |
+
_raise_file_not_found(path, None)
|
| 962 |
+
out = out1[0]
|
| 963 |
+
if refresh or out is None or (expand_info and out and out["last_commit"] is None):
|
| 964 |
+
paths_info = self._api.get_paths_info(
|
| 965 |
+
resolved_path.repo_id,
|
| 966 |
+
resolved_path.path_in_repo,
|
| 967 |
+
expand=expand_info,
|
| 968 |
+
revision=resolved_path.revision,
|
| 969 |
+
repo_type=resolved_path.repo_type,
|
| 970 |
+
)
|
| 971 |
+
if not paths_info:
|
| 972 |
+
_raise_file_not_found(path, None)
|
| 973 |
+
path_info = paths_info[0]
|
| 974 |
+
root_path = HfFileSystemResolvedRepositoryPath(
|
| 975 |
+
resolved_path.repo_type,
|
| 976 |
+
resolved_path.repo_id,
|
| 977 |
+
resolved_path.revision,
|
| 978 |
+
path_in_repo="",
|
| 979 |
+
_raw_revision=resolved_path._raw_revision,
|
| 980 |
+
).unresolve()
|
| 981 |
+
if isinstance(path_info, RepoFile):
|
| 982 |
+
out = {
|
| 983 |
+
"name": root_path + "/" + path_info.path,
|
| 984 |
+
"size": path_info.size,
|
| 985 |
+
"type": "file",
|
| 986 |
+
"blob_id": path_info.blob_id,
|
| 987 |
+
"lfs": path_info.lfs,
|
| 988 |
+
"xet_hash": path_info.xet_hash,
|
| 989 |
+
"last_commit": path_info.last_commit,
|
| 990 |
+
"security": path_info.security,
|
| 991 |
+
}
|
| 992 |
+
else:
|
| 993 |
+
out = {
|
| 994 |
+
"name": root_path + "/" + path_info.path,
|
| 995 |
+
"size": 0,
|
| 996 |
+
"type": "directory",
|
| 997 |
+
"tree_id": path_info.tree_id,
|
| 998 |
+
"last_commit": path_info.last_commit,
|
| 999 |
+
}
|
| 1000 |
+
if not expand_info:
|
| 1001 |
+
out = {k: out[k] for k in ["name", "size", "type"]}
|
| 1002 |
+
assert out is not None
|
| 1003 |
+
return out
|
| 1004 |
+
|
| 1005 |
+
def exists(self, path, **kwargs):
|
| 1006 |
+
"""
|
| 1007 |
+
Check if a file exists.
|
| 1008 |
+
|
| 1009 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.exists).
|
| 1010 |
+
|
| 1011 |
+
> [!WARNING]
|
| 1012 |
+
> Note: When possible, use `HfApi.file_exists()` for better performance.
|
| 1013 |
+
|
| 1014 |
+
Args:
|
| 1015 |
+
path (`str`):
|
| 1016 |
+
Path to check.
|
| 1017 |
+
|
| 1018 |
+
Returns:
|
| 1019 |
+
`bool`: True if file exists, False otherwise.
|
| 1020 |
+
"""
|
| 1021 |
+
try:
|
| 1022 |
+
if kwargs.get("refresh", False):
|
| 1023 |
+
self.invalidate_cache(path)
|
| 1024 |
+
|
| 1025 |
+
self.info(path, **kwargs)
|
| 1026 |
+
return True
|
| 1027 |
+
except OSError:
|
| 1028 |
+
return False
|
| 1029 |
+
|
| 1030 |
+
def isdir(self, path):
|
| 1031 |
+
"""
|
| 1032 |
+
Check if a path is a directory.
|
| 1033 |
+
|
| 1034 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isdir).
|
| 1035 |
+
|
| 1036 |
+
Args:
|
| 1037 |
+
path (`str`):
|
| 1038 |
+
Path to check.
|
| 1039 |
+
|
| 1040 |
+
Returns:
|
| 1041 |
+
`bool`: True if path is a directory, False otherwise.
|
| 1042 |
+
"""
|
| 1043 |
+
try:
|
| 1044 |
+
return self.info(path)["type"] == "directory"
|
| 1045 |
+
except OSError:
|
| 1046 |
+
return False
|
| 1047 |
+
|
| 1048 |
+
def isfile(self, path):
|
| 1049 |
+
"""
|
| 1050 |
+
Check if a path is a file.
|
| 1051 |
+
|
| 1052 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isfile).
|
| 1053 |
+
|
| 1054 |
+
Args:
|
| 1055 |
+
path (`str`):
|
| 1056 |
+
Path to check.
|
| 1057 |
+
|
| 1058 |
+
Returns:
|
| 1059 |
+
`bool`: True if path is a file, False otherwise.
|
| 1060 |
+
"""
|
| 1061 |
+
try:
|
| 1062 |
+
return self.info(path)["type"] == "file"
|
| 1063 |
+
except OSError:
|
| 1064 |
+
return False
|
| 1065 |
+
|
| 1066 |
+
def url(self, path: str) -> str:
|
| 1067 |
+
"""
|
| 1068 |
+
Get the HTTP URL of the given path.
|
| 1069 |
+
|
| 1070 |
+
Args:
|
| 1071 |
+
path (`str`):
|
| 1072 |
+
Path to get URL for.
|
| 1073 |
+
|
| 1074 |
+
Returns:
|
| 1075 |
+
`str`: HTTP URL to access the file or directory on the Hub.
|
| 1076 |
+
"""
|
| 1077 |
+
resolved_path = self.resolve_path(path)
|
| 1078 |
+
if isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 1079 |
+
url = f"{self.endpoint}/buckets/{resolved_path.bucket_id}/resolve/{quote(resolved_path.path)}"
|
| 1080 |
+
else:
|
| 1081 |
+
url = hf_hub_url(
|
| 1082 |
+
resolved_path.repo_id,
|
| 1083 |
+
resolved_path.path_in_repo,
|
| 1084 |
+
repo_type=resolved_path.repo_type,
|
| 1085 |
+
revision=resolved_path.revision,
|
| 1086 |
+
endpoint=self.endpoint,
|
| 1087 |
+
)
|
| 1088 |
+
if self.isdir(path):
|
| 1089 |
+
url = url.replace("/resolve/", "/tree/", 1)
|
| 1090 |
+
return url
|
| 1091 |
+
|
| 1092 |
+
def get_file(self, rpath, lpath, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None:
|
| 1093 |
+
"""
|
| 1094 |
+
Copy single remote file to local.
|
| 1095 |
+
|
| 1096 |
+
> [!WARNING]
|
| 1097 |
+
> Note: When possible, use `HfApi.hf_hub_download()` or `HfApi.download_bucket_files` for better performance.
|
| 1098 |
+
|
| 1099 |
+
Args:
|
| 1100 |
+
rpath (`str`):
|
| 1101 |
+
Remote path to download from.
|
| 1102 |
+
lpath (`str`):
|
| 1103 |
+
Local path to download to.
|
| 1104 |
+
callback (`Callback`, *optional*):
|
| 1105 |
+
Optional callback to track download progress. Defaults to no callback.
|
| 1106 |
+
outfile (`IO`, *optional*):
|
| 1107 |
+
Optional file-like object to write to. If provided, `lpath` is ignored.
|
| 1108 |
+
|
| 1109 |
+
"""
|
| 1110 |
+
revision = kwargs.get("revision")
|
| 1111 |
+
unhandled_kwargs = set(kwargs.keys()) - {"revision"}
|
| 1112 |
+
if not isinstance(callback, (NoOpCallback, TqdmCallback)) or len(unhandled_kwargs) > 0:
|
| 1113 |
+
# for now, let's not handle custom callbacks
|
| 1114 |
+
# and let's not handle custom kwargs
|
| 1115 |
+
return super().get_file(rpath, lpath, callback=callback, outfile=outfile, **kwargs)
|
| 1116 |
+
|
| 1117 |
+
# Taken from https://github.com/fsspec/filesystem_spec/blob/47b445ae4c284a82dd15e0287b1ffc410e8fc470/fsspec/spec.py#L883
|
| 1118 |
+
if isfilelike(lpath):
|
| 1119 |
+
outfile = lpath
|
| 1120 |
+
elif self.isdir(rpath):
|
| 1121 |
+
os.makedirs(lpath, exist_ok=True)
|
| 1122 |
+
return None
|
| 1123 |
+
|
| 1124 |
+
if isinstance(lpath, (str, Path)): # otherwise, let's assume it's a file-like object
|
| 1125 |
+
os.makedirs(os.path.dirname(lpath), exist_ok=True)
|
| 1126 |
+
|
| 1127 |
+
# Open file if not already open
|
| 1128 |
+
close_file = False
|
| 1129 |
+
if outfile is None:
|
| 1130 |
+
outfile = open(lpath, "wb")
|
| 1131 |
+
close_file = True
|
| 1132 |
+
initial_pos = outfile.tell()
|
| 1133 |
+
|
| 1134 |
+
# Custom implementation of `get_file` to use `http_get`.
|
| 1135 |
+
resolve_remote_path = self.resolve_path(rpath, revision=revision)
|
| 1136 |
+
expected_size = self.info(rpath, revision=revision)["size"]
|
| 1137 |
+
callback.set_size(expected_size)
|
| 1138 |
+
try:
|
| 1139 |
+
http_get(
|
| 1140 |
+
url=self.url(resolve_remote_path.unresolve()),
|
| 1141 |
+
temp_file=outfile, # type: ignore
|
| 1142 |
+
displayed_filename=rpath,
|
| 1143 |
+
expected_size=expected_size,
|
| 1144 |
+
resume_size=0,
|
| 1145 |
+
headers=self._api._build_hf_headers(),
|
| 1146 |
+
_tqdm_bar=callback.tqdm if isinstance(callback, TqdmCallback) else None,
|
| 1147 |
+
)
|
| 1148 |
+
outfile.seek(initial_pos)
|
| 1149 |
+
finally:
|
| 1150 |
+
# Close file only if we opened it ourselves
|
| 1151 |
+
if close_file:
|
| 1152 |
+
outfile.close()
|
| 1153 |
+
|
| 1154 |
+
@property
|
| 1155 |
+
def transaction(self):
|
| 1156 |
+
"""A context within which files are committed together upon exit
|
| 1157 |
+
|
| 1158 |
+
Requires the file class to implement `.commit()` and `.discard()`
|
| 1159 |
+
for the normal and exception cases.
|
| 1160 |
+
"""
|
| 1161 |
+
# Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L231
|
| 1162 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1733
|
| 1163 |
+
raise NotImplementedError("Transactional commits are not supported.")
|
| 1164 |
+
|
| 1165 |
+
def start_transaction(self):
|
| 1166 |
+
"""Begin write transaction for deferring files, non-context version"""
|
| 1167 |
+
# Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L241
|
| 1168 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1733
|
| 1169 |
+
raise NotImplementedError("Transactional commits are not supported.")
|
| 1170 |
+
|
| 1171 |
+
def __reduce__(self):
|
| 1172 |
+
# re-populate the instance cache at HfFileSystem._cache and re-populate the state of every instance
|
| 1173 |
+
return make_instance, (
|
| 1174 |
+
type(self),
|
| 1175 |
+
self.storage_args,
|
| 1176 |
+
self.storage_options,
|
| 1177 |
+
self._get_instance_state(),
|
| 1178 |
+
)
|
| 1179 |
+
|
| 1180 |
+
def _get_instance_state(self):
|
| 1181 |
+
return {
|
| 1182 |
+
"dircache": deepcopy(self.dircache),
|
| 1183 |
+
"_repo_and_revision_exists_cache": deepcopy(self._repo_and_revision_exists_cache),
|
| 1184 |
+
"_bucket_exists_cache": deepcopy(self._bucket_exists_cache),
|
| 1185 |
+
}
|
| 1186 |
+
|
| 1187 |
+
|
| 1188 |
+
class HfFileSystemFile(fsspec.spec.AbstractBufferedFile):
|
| 1189 |
+
def __init__(self, fs: HfFileSystem, path: str, revision: str | None = None, **kwargs):
|
| 1190 |
+
try:
|
| 1191 |
+
self.resolved_path = fs.resolve_path(path, revision=revision)
|
| 1192 |
+
except FileNotFoundError as e:
|
| 1193 |
+
if "w" in kwargs.get("mode", ""):
|
| 1194 |
+
raise FileNotFoundError(
|
| 1195 |
+
f"{e}.\nMake sure the repository and revision exist before writing data."
|
| 1196 |
+
) from e
|
| 1197 |
+
raise
|
| 1198 |
+
super().__init__(fs, self.resolved_path.unresolve(), **kwargs)
|
| 1199 |
+
self.fs: HfFileSystem
|
| 1200 |
+
|
| 1201 |
+
def __del__(self):
|
| 1202 |
+
if not hasattr(self, "resolved_path"):
|
| 1203 |
+
# Means that the constructor failed. Nothing to do.
|
| 1204 |
+
return
|
| 1205 |
+
return super().__del__()
|
| 1206 |
+
|
| 1207 |
+
def _fetch_range(self, start: int, end: int) -> bytes:
|
| 1208 |
+
headers = {
|
| 1209 |
+
"range": f"bytes={start}-{end - 1}",
|
| 1210 |
+
**self.fs._api._build_hf_headers(),
|
| 1211 |
+
}
|
| 1212 |
+
url = self.url()
|
| 1213 |
+
r = http_backoff("GET", url, headers=headers, timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT)
|
| 1214 |
+
hf_raise_for_status(r)
|
| 1215 |
+
return r.content
|
| 1216 |
+
|
| 1217 |
+
def _initiate_upload(self) -> None:
|
| 1218 |
+
self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False)
|
| 1219 |
+
|
| 1220 |
+
def _upload_chunk(self, final: bool = False) -> None:
|
| 1221 |
+
self.buffer.seek(0)
|
| 1222 |
+
block = self.buffer.read()
|
| 1223 |
+
self.temp_file.write(block)
|
| 1224 |
+
if final:
|
| 1225 |
+
self.temp_file.close()
|
| 1226 |
+
if isinstance(self.resolved_path, HfFileSystemResolvedBucketPath):
|
| 1227 |
+
self.fs._api.batch_bucket_files(
|
| 1228 |
+
self.resolved_path.bucket_id, add=[(self.temp_file.name, self.resolved_path.path)]
|
| 1229 |
+
)
|
| 1230 |
+
else:
|
| 1231 |
+
self.fs._api.upload_file(
|
| 1232 |
+
path_or_fileobj=self.temp_file.name,
|
| 1233 |
+
path_in_repo=self.resolved_path.path_in_repo,
|
| 1234 |
+
repo_id=self.resolved_path.repo_id,
|
| 1235 |
+
token=self.fs.token,
|
| 1236 |
+
repo_type=self.resolved_path.repo_type,
|
| 1237 |
+
revision=self.resolved_path.revision,
|
| 1238 |
+
commit_message=self.kwargs.get("commit_message"),
|
| 1239 |
+
commit_description=self.kwargs.get("commit_description"),
|
| 1240 |
+
)
|
| 1241 |
+
os.remove(self.temp_file.name)
|
| 1242 |
+
self.fs.invalidate_cache(
|
| 1243 |
+
path=self.resolved_path.unresolve(),
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
def read(self, length=-1):
|
| 1247 |
+
"""Read remote file.
|
| 1248 |
+
|
| 1249 |
+
If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems the file is
|
| 1250 |
+
loaded in memory directly. Otherwise, the file is downloaded to a temporary file and read from there.
|
| 1251 |
+
"""
|
| 1252 |
+
if self.mode == "rb" and (length is None or length == -1) and self.loc == 0:
|
| 1253 |
+
with self.fs.open(self.path, "rb", block_size=0) as f: # block_size=0 enables fast streaming
|
| 1254 |
+
out = f.read()
|
| 1255 |
+
self.loc += len(out)
|
| 1256 |
+
return out
|
| 1257 |
+
return super().read(length)
|
| 1258 |
+
|
| 1259 |
+
def url(self) -> str:
|
| 1260 |
+
return self.fs.url(self.path)
|
| 1261 |
+
|
| 1262 |
+
|
| 1263 |
+
class HfFileSystemStreamFile(fsspec.spec.AbstractBufferedFile):
|
| 1264 |
+
def __init__(
|
| 1265 |
+
self,
|
| 1266 |
+
fs: HfFileSystem,
|
| 1267 |
+
path: str,
|
| 1268 |
+
mode: str = "rb",
|
| 1269 |
+
revision: str | None = None,
|
| 1270 |
+
block_size: int = 0,
|
| 1271 |
+
cache_type: str = "none",
|
| 1272 |
+
**kwargs,
|
| 1273 |
+
):
|
| 1274 |
+
if block_size != 0:
|
| 1275 |
+
raise ValueError(f"HfFileSystemStreamFile only supports block_size=0 but got {block_size}")
|
| 1276 |
+
if cache_type != "none":
|
| 1277 |
+
raise ValueError(f"HfFileSystemStreamFile only supports cache_type='none' but got {cache_type}")
|
| 1278 |
+
if "w" in mode:
|
| 1279 |
+
raise ValueError(f"HfFileSystemStreamFile only supports reading but got mode='{mode}'")
|
| 1280 |
+
try:
|
| 1281 |
+
self.resolved_path = fs.resolve_path(path, revision=revision)
|
| 1282 |
+
except FileNotFoundError as e:
|
| 1283 |
+
if "w" in kwargs.get("mode", ""):
|
| 1284 |
+
raise FileNotFoundError(
|
| 1285 |
+
f"{e}.\nMake sure the repository and revision exist before writing data."
|
| 1286 |
+
) from e
|
| 1287 |
+
# avoid an unnecessary .info() call to instantiate .details
|
| 1288 |
+
self.details = {"name": self.resolved_path.unresolve(), "size": None}
|
| 1289 |
+
super().__init__(
|
| 1290 |
+
fs, self.resolved_path.unresolve(), mode=mode, block_size=block_size, cache_type=cache_type, **kwargs
|
| 1291 |
+
)
|
| 1292 |
+
self.response: httpx.Response | None = None
|
| 1293 |
+
self.fs: HfFileSystem
|
| 1294 |
+
self._exit_stack = ExitStack()
|
| 1295 |
+
# streaming state
|
| 1296 |
+
self._stream_iterator: Iterator[bytes] | None = None
|
| 1297 |
+
self._stream_buffer = bytearray()
|
| 1298 |
+
|
| 1299 |
+
def seek(self, loc: int, whence: int = 0):
|
| 1300 |
+
if loc == 0 and whence == 1:
|
| 1301 |
+
return
|
| 1302 |
+
if loc == self.loc and whence == 0:
|
| 1303 |
+
return
|
| 1304 |
+
raise ValueError("Cannot seek streaming HF file")
|
| 1305 |
+
|
| 1306 |
+
def read(self, length: int = -1):
|
| 1307 |
+
"""Read the remote file.
|
| 1308 |
+
|
| 1309 |
+
If the file is already open, we reuse the connection.
|
| 1310 |
+
Otherwise, open a new connection and read from it.
|
| 1311 |
+
|
| 1312 |
+
If reading the stream fails, we retry with a new connection.
|
| 1313 |
+
"""
|
| 1314 |
+
if self.response is None:
|
| 1315 |
+
self._open_connection()
|
| 1316 |
+
|
| 1317 |
+
retried_once = False
|
| 1318 |
+
while True:
|
| 1319 |
+
try:
|
| 1320 |
+
if self.response is None or self._stream_iterator is None:
|
| 1321 |
+
return b"" # Already read the entire file
|
| 1322 |
+
out = self._read_from_stream(self._stream_iterator, length)
|
| 1323 |
+
self.loc += len(out)
|
| 1324 |
+
return out
|
| 1325 |
+
except Exception:
|
| 1326 |
+
if self.response is not None:
|
| 1327 |
+
self.response.close()
|
| 1328 |
+
if retried_once: # Already retried once, give up
|
| 1329 |
+
raise
|
| 1330 |
+
# First failure, retry with range header
|
| 1331 |
+
self._open_connection()
|
| 1332 |
+
retried_once = True
|
| 1333 |
+
|
| 1334 |
+
def _read_from_stream(self, iterator: Iterator[bytes], length: int = -1) -> bytes:
|
| 1335 |
+
"""Read up to `length` bytes from stream buffer and stream.
|
| 1336 |
+
|
| 1337 |
+
If length < 0, read until EOF.
|
| 1338 |
+
|
| 1339 |
+
If EOF is reached before length, fewer bytes may be returned.
|
| 1340 |
+
"""
|
| 1341 |
+
if length == 0:
|
| 1342 |
+
return b""
|
| 1343 |
+
|
| 1344 |
+
if length < 0:
|
| 1345 |
+
buf = bytearray(self._stream_buffer)
|
| 1346 |
+
self._stream_buffer.clear()
|
| 1347 |
+
for chunk in iterator:
|
| 1348 |
+
buf.extend(chunk)
|
| 1349 |
+
return bytes(buf)
|
| 1350 |
+
|
| 1351 |
+
if length <= len(self._stream_buffer):
|
| 1352 |
+
result = bytes(self._stream_buffer[:length])
|
| 1353 |
+
del self._stream_buffer[:length]
|
| 1354 |
+
return result
|
| 1355 |
+
|
| 1356 |
+
buf = bytearray(self._stream_buffer)
|
| 1357 |
+
self._stream_buffer.clear()
|
| 1358 |
+
for chunk in iterator:
|
| 1359 |
+
need = length - len(buf)
|
| 1360 |
+
if need > len(chunk):
|
| 1361 |
+
buf.extend(chunk)
|
| 1362 |
+
else:
|
| 1363 |
+
buf.extend(chunk[:need])
|
| 1364 |
+
self._stream_buffer.extend(chunk[need:])
|
| 1365 |
+
break
|
| 1366 |
+
return bytes(buf)
|
| 1367 |
+
|
| 1368 |
+
def url(self) -> str:
|
| 1369 |
+
return self.fs.url(self.path)
|
| 1370 |
+
|
| 1371 |
+
def __del__(self):
|
| 1372 |
+
if not hasattr(self, "resolved_path"):
|
| 1373 |
+
# Means that the constructor failed. Nothing to do.
|
| 1374 |
+
return
|
| 1375 |
+
self._exit_stack.close()
|
| 1376 |
+
return super().__del__()
|
| 1377 |
+
|
| 1378 |
+
def __reduce__(self):
|
| 1379 |
+
return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name)
|
| 1380 |
+
|
| 1381 |
+
def _open_connection(self):
|
| 1382 |
+
"""Open a connection to the remote file."""
|
| 1383 |
+
# reset streaming state
|
| 1384 |
+
self._stream_buffer.clear()
|
| 1385 |
+
self._stream_iterator = None
|
| 1386 |
+
|
| 1387 |
+
url = self.url()
|
| 1388 |
+
headers = self.fs._api._build_hf_headers()
|
| 1389 |
+
if self.loc > 0:
|
| 1390 |
+
headers["Range"] = f"bytes={self.loc}-"
|
| 1391 |
+
self.response = self._exit_stack.enter_context(
|
| 1392 |
+
http_stream_backoff(
|
| 1393 |
+
"GET",
|
| 1394 |
+
url,
|
| 1395 |
+
headers=headers,
|
| 1396 |
+
timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT,
|
| 1397 |
+
)
|
| 1398 |
+
)
|
| 1399 |
+
|
| 1400 |
+
try:
|
| 1401 |
+
hf_raise_for_status(self.response)
|
| 1402 |
+
except HfHubHTTPError as e:
|
| 1403 |
+
if e.response.status_code == 416:
|
| 1404 |
+
# Range not satisfiable => means that we have already read the entire file
|
| 1405 |
+
self.response = None
|
| 1406 |
+
return
|
| 1407 |
+
raise
|
| 1408 |
+
|
| 1409 |
+
self._stream_iterator = self.response.iter_bytes()
|
| 1410 |
+
|
| 1411 |
+
|
| 1412 |
+
def safe_revision(revision: str) -> str:
|
| 1413 |
+
return revision if SPECIAL_REFS_REVISION_REGEX.match(revision) else safe_quote(revision)
|
| 1414 |
+
|
| 1415 |
+
|
| 1416 |
+
def safe_quote(s: str) -> str:
|
| 1417 |
+
return quote(s, safe="")
|
| 1418 |
+
|
| 1419 |
+
|
| 1420 |
+
def _raise_file_not_found(path: str, err: Exception | None) -> NoReturn:
|
| 1421 |
+
msg = path
|
| 1422 |
+
if isinstance(err, RepositoryNotFoundError):
|
| 1423 |
+
msg = f"{path} (repository not found)"
|
| 1424 |
+
elif isinstance(err, RevisionNotFoundError):
|
| 1425 |
+
msg = f"{path} (revision not found)"
|
| 1426 |
+
elif isinstance(err, HFValidationError):
|
| 1427 |
+
msg = f"{path} (invalid repository id)"
|
| 1428 |
+
raise FileNotFoundError(msg) from err
|
| 1429 |
+
|
| 1430 |
+
|
| 1431 |
+
def reopen(fs: HfFileSystem, path: str, mode: str, block_size: int, cache_type: str):
|
| 1432 |
+
return fs.open(path, mode=mode, block_size=block_size, cache_type=cache_type)
|
| 1433 |
+
|
| 1434 |
+
|
| 1435 |
+
def make_instance(cls, args, kwargs, instance_state):
|
| 1436 |
+
fs = cls(*args, **kwargs)
|
| 1437 |
+
for attr, state_value in instance_state.items():
|
| 1438 |
+
setattr(fs, attr, state_value)
|
| 1439 |
+
return fs
|
| 1440 |
+
|
| 1441 |
+
|
| 1442 |
+
hffs = HfFileSystem()
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/hub_mixin.py
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from dataclasses import Field, asdict, dataclass, is_dataclass
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, ClassVar, Protocol, TypeVar
|
| 8 |
+
|
| 9 |
+
import packaging.version
|
| 10 |
+
|
| 11 |
+
from . import constants
|
| 12 |
+
from .errors import EntryNotFoundError, HfHubHTTPError
|
| 13 |
+
from .file_download import hf_hub_download
|
| 14 |
+
from .hf_api import HfApi
|
| 15 |
+
from .repocard import ModelCard, ModelCardData
|
| 16 |
+
from .utils import (
|
| 17 |
+
SoftTemporaryDirectory,
|
| 18 |
+
is_jsonable,
|
| 19 |
+
is_safetensors_available,
|
| 20 |
+
is_simple_optional_type,
|
| 21 |
+
is_torch_available,
|
| 22 |
+
logging,
|
| 23 |
+
unwrap_simple_optional_type,
|
| 24 |
+
validate_hf_hub_args,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch # type: ignore
|
| 30 |
+
|
| 31 |
+
if is_safetensors_available():
|
| 32 |
+
import safetensors
|
| 33 |
+
from safetensors.torch import load_model as load_model_as_safetensor
|
| 34 |
+
from safetensors.torch import save_model as save_model_as_safetensor
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# Type alias for dataclass instances, copied from https://github.com/python/typeshed/blob/9f28171658b9ca6c32a7cb93fbb99fc92b17858b/stdlib/_typeshed/__init__.pyi#L349
|
| 41 |
+
class DataclassInstance(Protocol):
|
| 42 |
+
__dataclass_fields__: ClassVar[dict[str, Field]]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Generic variable that is either ModelHubMixin or a subclass thereof
|
| 46 |
+
T = TypeVar("T", bound="ModelHubMixin")
|
| 47 |
+
# Generic variable to represent an args type
|
| 48 |
+
ARGS_T = TypeVar("ARGS_T")
|
| 49 |
+
ENCODER_T = Callable[[ARGS_T], Any]
|
| 50 |
+
DECODER_T = Callable[[Any], ARGS_T]
|
| 51 |
+
CODER_T = tuple[ENCODER_T, DECODER_T]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
DEFAULT_MODEL_CARD = """
|
| 55 |
+
---
|
| 56 |
+
# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
|
| 57 |
+
# Doc / guide: https://huggingface.co/docs/hub/model-cards
|
| 58 |
+
{{ card_data }}
|
| 59 |
+
---
|
| 60 |
+
|
| 61 |
+
This model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration:
|
| 62 |
+
- Code: {{ repo_url | default("[More Information Needed]", true) }}
|
| 63 |
+
- Paper: {{ paper_url | default("[More Information Needed]", true) }}
|
| 64 |
+
- Docs: {{ docs_url | default("[More Information Needed]", true) }}
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass
|
| 69 |
+
class MixinInfo:
|
| 70 |
+
model_card_template: str
|
| 71 |
+
model_card_data: ModelCardData
|
| 72 |
+
docs_url: str | None = None
|
| 73 |
+
paper_url: str | None = None
|
| 74 |
+
repo_url: str | None = None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class ModelHubMixin:
|
| 78 |
+
"""
|
| 79 |
+
A generic mixin to integrate ANY machine learning framework with the Hub.
|
| 80 |
+
|
| 81 |
+
To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models
|
| 82 |
+
have to be overwritten in [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelHubMixin`] is a good example
|
| 83 |
+
of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions.
|
| 84 |
+
|
| 85 |
+
When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to
|
| 86 |
+
`__init__` but to the class definition itself. This is useful to define metadata about the library integrating
|
| 87 |
+
[`ModelHubMixin`].
|
| 88 |
+
|
| 89 |
+
For more details on how to integrate the mixin with your library, checkout the [integration guide](../guides/integrations).
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
repo_url (`str`, *optional*):
|
| 93 |
+
URL of the library repository. Used to generate model card.
|
| 94 |
+
paper_url (`str`, *optional*):
|
| 95 |
+
URL of the library paper. Used to generate model card.
|
| 96 |
+
docs_url (`str`, *optional*):
|
| 97 |
+
URL of the library documentation. Used to generate model card.
|
| 98 |
+
model_card_template (`str`, *optional*):
|
| 99 |
+
Template of the model card. Used to generate model card. Defaults to a generic template.
|
| 100 |
+
language (`str` or `list[str]`, *optional*):
|
| 101 |
+
Language supported by the library. Used to generate model card.
|
| 102 |
+
library_name (`str`, *optional*):
|
| 103 |
+
Name of the library integrating ModelHubMixin. Used to generate model card.
|
| 104 |
+
license (`str`, *optional*):
|
| 105 |
+
License of the library integrating ModelHubMixin. Used to generate model card.
|
| 106 |
+
E.g: "apache-2.0"
|
| 107 |
+
license_name (`str`, *optional*):
|
| 108 |
+
Name of the library integrating ModelHubMixin. Used to generate model card.
|
| 109 |
+
Only used if `license` is set to `other`.
|
| 110 |
+
E.g: "coqui-public-model-license".
|
| 111 |
+
license_link (`str`, *optional*):
|
| 112 |
+
URL to the license of the library integrating ModelHubMixin. Used to generate model card.
|
| 113 |
+
Only used if `license` is set to `other` and `license_name` is set.
|
| 114 |
+
E.g: "https://coqui.ai/cpml".
|
| 115 |
+
pipeline_tag (`str`, *optional*):
|
| 116 |
+
Tag of the pipeline. Used to generate model card. E.g. "text-classification".
|
| 117 |
+
tags (`list[str]`, *optional*):
|
| 118 |
+
Tags to be added to the model card. Used to generate model card. E.g. ["computer-vision"]
|
| 119 |
+
coders (`dict[Type, tuple[Callable, Callable]]`, *optional*):
|
| 120 |
+
Dictionary of custom types and their encoders/decoders. Used to encode/decode arguments that are not
|
| 121 |
+
jsonable by default. E.g. dataclasses, argparse.Namespace, OmegaConf, etc.
|
| 122 |
+
|
| 123 |
+
Example:
|
| 124 |
+
|
| 125 |
+
```python
|
| 126 |
+
>>> from huggingface_hub import ModelHubMixin
|
| 127 |
+
|
| 128 |
+
# Inherit from ModelHubMixin
|
| 129 |
+
>>> class MyCustomModel(
|
| 130 |
+
... ModelHubMixin,
|
| 131 |
+
... library_name="my-library",
|
| 132 |
+
... tags=["computer-vision"],
|
| 133 |
+
... repo_url="https://github.com/huggingface/my-cool-library",
|
| 134 |
+
... paper_url="https://arxiv.org/abs/2304.12244",
|
| 135 |
+
... docs_url="https://huggingface.co/docs/my-cool-library",
|
| 136 |
+
... # ^ optional metadata to generate model card
|
| 137 |
+
... ):
|
| 138 |
+
... def __init__(self, size: int = 512, device: str = "cpu"):
|
| 139 |
+
... # define how to initialize your model
|
| 140 |
+
... super().__init__()
|
| 141 |
+
... ...
|
| 142 |
+
...
|
| 143 |
+
... def _save_pretrained(self, save_directory: Path) -> None:
|
| 144 |
+
... # define how to serialize your model
|
| 145 |
+
... ...
|
| 146 |
+
...
|
| 147 |
+
... @classmethod
|
| 148 |
+
... def from_pretrained(
|
| 149 |
+
... cls: type[T],
|
| 150 |
+
... pretrained_model_name_or_path: Union[str, Path],
|
| 151 |
+
... *,
|
| 152 |
+
... force_download: bool = False,
|
| 153 |
+
... token: Optional[Union[str, bool]] = None,
|
| 154 |
+
... cache_dir: Optional[Union[str, Path]] = None,
|
| 155 |
+
... local_files_only: bool = False,
|
| 156 |
+
... revision: Optional[str] = None,
|
| 157 |
+
... **model_kwargs,
|
| 158 |
+
... ) -> T:
|
| 159 |
+
... # define how to deserialize your model
|
| 160 |
+
... ...
|
| 161 |
+
|
| 162 |
+
>>> model = MyCustomModel(size=256, device="gpu")
|
| 163 |
+
|
| 164 |
+
# Save model weights to local directory
|
| 165 |
+
>>> model.save_pretrained("my-awesome-model")
|
| 166 |
+
|
| 167 |
+
# Push model weights to the Hub
|
| 168 |
+
>>> model.push_to_hub("my-awesome-model")
|
| 169 |
+
|
| 170 |
+
# Download and initialize weights from the Hub
|
| 171 |
+
>>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model")
|
| 172 |
+
>>> reloaded_model.size
|
| 173 |
+
256
|
| 174 |
+
|
| 175 |
+
# Model card has been correctly populated
|
| 176 |
+
>>> from huggingface_hub import ModelCard
|
| 177 |
+
>>> card = ModelCard.load("username/my-awesome-model")
|
| 178 |
+
>>> card.data.tags
|
| 179 |
+
["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"]
|
| 180 |
+
>>> card.data.library_name
|
| 181 |
+
"my-library"
|
| 182 |
+
```
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
_hub_mixin_config: dict | DataclassInstance | None = None
|
| 186 |
+
# ^ optional config attribute automatically set in `from_pretrained`
|
| 187 |
+
_hub_mixin_info: MixinInfo
|
| 188 |
+
# ^ information about the library integrating ModelHubMixin (used to generate model card)
|
| 189 |
+
_hub_mixin_inject_config: bool # whether `_from_pretrained` expects `config` or not
|
| 190 |
+
_hub_mixin_init_parameters: dict[str, inspect.Parameter] # __init__ parameters
|
| 191 |
+
_hub_mixin_jsonable_default_values: dict[str, Any] # default values for __init__ parameters
|
| 192 |
+
_hub_mixin_jsonable_custom_types: tuple[type, ...] # custom types that can be encoded/decoded
|
| 193 |
+
_hub_mixin_coders: dict[type, CODER_T] # encoders/decoders for custom types
|
| 194 |
+
# ^ internal values to handle config
|
| 195 |
+
|
| 196 |
+
def __init_subclass__(
|
| 197 |
+
cls,
|
| 198 |
+
*,
|
| 199 |
+
# Generic info for model card
|
| 200 |
+
repo_url: str | None = None,
|
| 201 |
+
paper_url: str | None = None,
|
| 202 |
+
docs_url: str | None = None,
|
| 203 |
+
# Model card template
|
| 204 |
+
model_card_template: str = DEFAULT_MODEL_CARD,
|
| 205 |
+
# Model card metadata
|
| 206 |
+
language: list[str] | None = None,
|
| 207 |
+
library_name: str | None = None,
|
| 208 |
+
license: str | None = None,
|
| 209 |
+
license_name: str | None = None,
|
| 210 |
+
license_link: str | None = None,
|
| 211 |
+
pipeline_tag: str | None = None,
|
| 212 |
+
tags: list[str] | None = None,
|
| 213 |
+
# How to encode/decode arguments with custom type into a JSON config?
|
| 214 |
+
coders: None
|
| 215 |
+
| (
|
| 216 |
+
dict[type, CODER_T]
|
| 217 |
+
# Key is a type.
|
| 218 |
+
# Value is a tuple (encoder, decoder).
|
| 219 |
+
# Example: {MyCustomType: (lambda x: x.value, lambda data: MyCustomType(data))}
|
| 220 |
+
) = None,
|
| 221 |
+
) -> None:
|
| 222 |
+
"""Inspect __init__ signature only once when subclassing + handle modelcard."""
|
| 223 |
+
super().__init_subclass__()
|
| 224 |
+
|
| 225 |
+
# Will be reused when creating modelcard
|
| 226 |
+
tags = tags or []
|
| 227 |
+
tags.append("model_hub_mixin")
|
| 228 |
+
|
| 229 |
+
# Initialize MixinInfo if not existent
|
| 230 |
+
info = MixinInfo(model_card_template=model_card_template, model_card_data=ModelCardData())
|
| 231 |
+
|
| 232 |
+
# If parent class has a MixinInfo, inherit from it as a copy
|
| 233 |
+
if hasattr(cls, "_hub_mixin_info"):
|
| 234 |
+
# Inherit model card template from parent class if not explicitly set
|
| 235 |
+
if model_card_template == DEFAULT_MODEL_CARD:
|
| 236 |
+
info.model_card_template = cls._hub_mixin_info.model_card_template
|
| 237 |
+
|
| 238 |
+
# Inherit from parent model card data
|
| 239 |
+
info.model_card_data = ModelCardData(**cls._hub_mixin_info.model_card_data.to_dict())
|
| 240 |
+
|
| 241 |
+
# Inherit other info
|
| 242 |
+
info.docs_url = cls._hub_mixin_info.docs_url
|
| 243 |
+
info.paper_url = cls._hub_mixin_info.paper_url
|
| 244 |
+
info.repo_url = cls._hub_mixin_info.repo_url
|
| 245 |
+
cls._hub_mixin_info = info
|
| 246 |
+
|
| 247 |
+
# Update MixinInfo with metadata
|
| 248 |
+
if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD:
|
| 249 |
+
info.model_card_template = model_card_template
|
| 250 |
+
if repo_url is not None:
|
| 251 |
+
info.repo_url = repo_url
|
| 252 |
+
if paper_url is not None:
|
| 253 |
+
info.paper_url = paper_url
|
| 254 |
+
if docs_url is not None:
|
| 255 |
+
info.docs_url = docs_url
|
| 256 |
+
if language is not None:
|
| 257 |
+
info.model_card_data.language = language
|
| 258 |
+
if library_name is not None:
|
| 259 |
+
info.model_card_data.library_name = library_name
|
| 260 |
+
if license is not None:
|
| 261 |
+
info.model_card_data.license = license
|
| 262 |
+
if license_name is not None:
|
| 263 |
+
info.model_card_data.license_name = license_name
|
| 264 |
+
if license_link is not None:
|
| 265 |
+
info.model_card_data.license_link = license_link
|
| 266 |
+
if pipeline_tag is not None:
|
| 267 |
+
info.model_card_data.pipeline_tag = pipeline_tag
|
| 268 |
+
if tags is not None:
|
| 269 |
+
normalized_tags = list(tags)
|
| 270 |
+
if info.model_card_data.tags is not None:
|
| 271 |
+
info.model_card_data.tags.extend(normalized_tags)
|
| 272 |
+
else:
|
| 273 |
+
info.model_card_data.tags = normalized_tags
|
| 274 |
+
|
| 275 |
+
if info.model_card_data.tags is not None:
|
| 276 |
+
info.model_card_data.tags = sorted(set(info.model_card_data.tags))
|
| 277 |
+
|
| 278 |
+
# Handle encoders/decoders for args
|
| 279 |
+
cls._hub_mixin_coders = coders or {}
|
| 280 |
+
cls._hub_mixin_jsonable_custom_types = tuple(cls._hub_mixin_coders.keys())
|
| 281 |
+
|
| 282 |
+
# Inspect __init__ signature to handle config
|
| 283 |
+
cls._hub_mixin_init_parameters = dict(inspect.signature(cls.__init__).parameters)
|
| 284 |
+
cls._hub_mixin_jsonable_default_values = {
|
| 285 |
+
param.name: cls._encode_arg(param.default)
|
| 286 |
+
for param in cls._hub_mixin_init_parameters.values()
|
| 287 |
+
if param.default is not inspect.Parameter.empty and cls._is_jsonable(param.default)
|
| 288 |
+
}
|
| 289 |
+
cls._hub_mixin_inject_config = "config" in inspect.signature(cls._from_pretrained).parameters
|
| 290 |
+
|
| 291 |
+
def __new__(cls: type[T], *args, **kwargs) -> T:
|
| 292 |
+
"""Create a new instance of the class and handle config.
|
| 293 |
+
|
| 294 |
+
3 cases:
|
| 295 |
+
- If `self._hub_mixin_config` is already set, do nothing.
|
| 296 |
+
- If `config` is passed as a dataclass, set it as `self._hub_mixin_config`.
|
| 297 |
+
- Otherwise, build `self._hub_mixin_config` from default values and passed values.
|
| 298 |
+
"""
|
| 299 |
+
instance = super().__new__(cls)
|
| 300 |
+
|
| 301 |
+
# If `config` is already set, return early
|
| 302 |
+
if instance._hub_mixin_config is not None:
|
| 303 |
+
return instance
|
| 304 |
+
|
| 305 |
+
# Infer passed values
|
| 306 |
+
passed_values = {
|
| 307 |
+
**{
|
| 308 |
+
key: value
|
| 309 |
+
for key, value in zip(
|
| 310 |
+
# [1:] to skip `self` parameter
|
| 311 |
+
list(cls._hub_mixin_init_parameters)[1:],
|
| 312 |
+
args,
|
| 313 |
+
)
|
| 314 |
+
},
|
| 315 |
+
**kwargs,
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
# If config passed as dataclass => set it and return early
|
| 319 |
+
if is_dataclass(passed_values.get("config")):
|
| 320 |
+
instance._hub_mixin_config = passed_values["config"]
|
| 321 |
+
return instance
|
| 322 |
+
|
| 323 |
+
# Otherwise, build config from default + passed values
|
| 324 |
+
init_config = {
|
| 325 |
+
# default values
|
| 326 |
+
**cls._hub_mixin_jsonable_default_values,
|
| 327 |
+
# passed values
|
| 328 |
+
**{
|
| 329 |
+
key: cls._encode_arg(value) # Encode custom types as jsonable value
|
| 330 |
+
for key, value in passed_values.items()
|
| 331 |
+
if instance._is_jsonable(value) # Only if jsonable or we have a custom encoder
|
| 332 |
+
},
|
| 333 |
+
}
|
| 334 |
+
passed_config = init_config.pop("config", {})
|
| 335 |
+
|
| 336 |
+
# Populate `init_config` with provided config
|
| 337 |
+
if isinstance(passed_config, dict):
|
| 338 |
+
init_config.update(passed_config)
|
| 339 |
+
|
| 340 |
+
# Set `config` attribute and return
|
| 341 |
+
if init_config != {}:
|
| 342 |
+
instance._hub_mixin_config = init_config
|
| 343 |
+
return instance
|
| 344 |
+
|
| 345 |
+
@classmethod
|
| 346 |
+
def _is_jsonable(cls, value: Any) -> bool:
|
| 347 |
+
"""Check if a value is JSON serializable."""
|
| 348 |
+
if is_dataclass(value):
|
| 349 |
+
return True
|
| 350 |
+
if isinstance(value, cls._hub_mixin_jsonable_custom_types):
|
| 351 |
+
return True
|
| 352 |
+
return is_jsonable(value)
|
| 353 |
+
|
| 354 |
+
@classmethod
|
| 355 |
+
def _encode_arg(cls, arg: Any) -> Any:
|
| 356 |
+
"""Encode an argument into a JSON serializable format."""
|
| 357 |
+
if is_dataclass(arg):
|
| 358 |
+
return asdict(arg) # type: ignore[arg-type]
|
| 359 |
+
for type_, (encoder, _) in cls._hub_mixin_coders.items():
|
| 360 |
+
if isinstance(arg, type_):
|
| 361 |
+
if arg is None:
|
| 362 |
+
return None
|
| 363 |
+
return encoder(arg)
|
| 364 |
+
return arg
|
| 365 |
+
|
| 366 |
+
@classmethod
|
| 367 |
+
def _decode_arg(cls, expected_type: type[ARGS_T], value: Any) -> ARGS_T | None:
|
| 368 |
+
"""Decode a JSON serializable value into an argument."""
|
| 369 |
+
if is_simple_optional_type(expected_type):
|
| 370 |
+
if value is None:
|
| 371 |
+
return None
|
| 372 |
+
expected_type = unwrap_simple_optional_type(expected_type) # type: ignore
|
| 373 |
+
# Dataclass => handle it
|
| 374 |
+
if is_dataclass(expected_type):
|
| 375 |
+
return _load_dataclass(expected_type, value) # type: ignore
|
| 376 |
+
# Otherwise => check custom decoders
|
| 377 |
+
for type_, (_, decoder) in cls._hub_mixin_coders.items():
|
| 378 |
+
if inspect.isclass(expected_type) and issubclass(expected_type, type_):
|
| 379 |
+
return decoder(value)
|
| 380 |
+
# Otherwise => don't decode
|
| 381 |
+
return value
|
| 382 |
+
|
| 383 |
+
def save_pretrained(
|
| 384 |
+
self,
|
| 385 |
+
save_directory: str | Path,
|
| 386 |
+
*,
|
| 387 |
+
config: dict | DataclassInstance | None = None,
|
| 388 |
+
repo_id: str | None = None,
|
| 389 |
+
push_to_hub: bool = False,
|
| 390 |
+
model_card_kwargs: dict[str, Any] | None = None,
|
| 391 |
+
**push_to_hub_kwargs,
|
| 392 |
+
) -> str | None:
|
| 393 |
+
"""
|
| 394 |
+
Save weights in local directory.
|
| 395 |
+
|
| 396 |
+
Args:
|
| 397 |
+
save_directory (`str` or `Path`):
|
| 398 |
+
Path to directory in which the model weights and configuration will be saved.
|
| 399 |
+
config (`dict` or `DataclassInstance`, *optional*):
|
| 400 |
+
Model configuration specified as a key/value dictionary or a dataclass instance.
|
| 401 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 402 |
+
Whether or not to push your model to the Huggingface Hub after saving it.
|
| 403 |
+
repo_id (`str`, *optional*):
|
| 404 |
+
ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
|
| 405 |
+
not provided.
|
| 406 |
+
model_card_kwargs (`dict[str, Any]`, *optional*):
|
| 407 |
+
Additional arguments passed to the model card template to customize the model card.
|
| 408 |
+
push_to_hub_kwargs:
|
| 409 |
+
Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method.
|
| 410 |
+
Returns:
|
| 411 |
+
`str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
|
| 412 |
+
"""
|
| 413 |
+
save_directory = Path(save_directory)
|
| 414 |
+
save_directory.mkdir(parents=True, exist_ok=True)
|
| 415 |
+
|
| 416 |
+
# Remove config.json if already exists. After `_save_pretrained` we don't want to overwrite config.json
|
| 417 |
+
# as it might have been saved by the custom `_save_pretrained` already. However we do want to overwrite
|
| 418 |
+
# an existing config.json if it was not saved by `_save_pretrained`.
|
| 419 |
+
config_path = save_directory / constants.CONFIG_NAME
|
| 420 |
+
config_path.unlink(missing_ok=True)
|
| 421 |
+
|
| 422 |
+
# save model weights/files (framework-specific)
|
| 423 |
+
self._save_pretrained(save_directory)
|
| 424 |
+
|
| 425 |
+
# save config (if provided and if not serialized yet in `_save_pretrained`)
|
| 426 |
+
if config is None:
|
| 427 |
+
config = self._hub_mixin_config
|
| 428 |
+
if config is not None:
|
| 429 |
+
if is_dataclass(config):
|
| 430 |
+
config = asdict(config) # type: ignore[arg-type]
|
| 431 |
+
if not config_path.exists():
|
| 432 |
+
config_str = json.dumps(config, sort_keys=True, indent=2)
|
| 433 |
+
config_path.write_text(config_str)
|
| 434 |
+
|
| 435 |
+
# save model card
|
| 436 |
+
model_card_path = save_directory / "README.md"
|
| 437 |
+
model_card_kwargs = model_card_kwargs if model_card_kwargs is not None else {}
|
| 438 |
+
if not model_card_path.exists(): # do not overwrite if already exists
|
| 439 |
+
self.generate_model_card(**model_card_kwargs).save(save_directory / "README.md")
|
| 440 |
+
|
| 441 |
+
# push to the Hub if required
|
| 442 |
+
if push_to_hub:
|
| 443 |
+
kwargs = push_to_hub_kwargs.copy() # soft-copy to avoid mutating input
|
| 444 |
+
if config is not None: # kwarg for `push_to_hub`
|
| 445 |
+
kwargs["config"] = config
|
| 446 |
+
if repo_id is None:
|
| 447 |
+
repo_id = save_directory.name # Defaults to `save_directory` name
|
| 448 |
+
return self.push_to_hub(repo_id=repo_id, model_card_kwargs=model_card_kwargs, **kwargs)
|
| 449 |
+
return None
|
| 450 |
+
|
| 451 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
| 452 |
+
"""
|
| 453 |
+
Overwrite this method in subclass to define how to save your model.
|
| 454 |
+
Check out our [integration guide](../guides/integrations) for instructions.
|
| 455 |
+
|
| 456 |
+
Args:
|
| 457 |
+
save_directory (`str` or `Path`):
|
| 458 |
+
Path to directory in which the model weights and configuration will be saved.
|
| 459 |
+
"""
|
| 460 |
+
raise NotImplementedError
|
| 461 |
+
|
| 462 |
+
@classmethod
|
| 463 |
+
@validate_hf_hub_args
|
| 464 |
+
def from_pretrained(
|
| 465 |
+
cls: type[T],
|
| 466 |
+
pretrained_model_name_or_path: str | Path,
|
| 467 |
+
*,
|
| 468 |
+
force_download: bool = False,
|
| 469 |
+
token: str | bool | None = None,
|
| 470 |
+
cache_dir: str | Path | None = None,
|
| 471 |
+
local_files_only: bool = False,
|
| 472 |
+
revision: str | None = None,
|
| 473 |
+
**model_kwargs,
|
| 474 |
+
) -> T:
|
| 475 |
+
"""
|
| 476 |
+
Download a model from the Huggingface Hub and instantiate it.
|
| 477 |
+
|
| 478 |
+
Args:
|
| 479 |
+
pretrained_model_name_or_path (`str`, `Path`):
|
| 480 |
+
- Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`.
|
| 481 |
+
- Or a path to a `directory` containing model weights saved using
|
| 482 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `../path/to/my_model_directory/`.
|
| 483 |
+
revision (`str`, *optional*):
|
| 484 |
+
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id.
|
| 485 |
+
Defaults to the latest commit on `main` branch.
|
| 486 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 487 |
+
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
|
| 488 |
+
the existing cache.
|
| 489 |
+
token (`str` or `bool`, *optional*):
|
| 490 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
| 491 |
+
cached when running `hf auth login`.
|
| 492 |
+
cache_dir (`str`, `Path`, *optional*):
|
| 493 |
+
Path to the folder where cached files are stored.
|
| 494 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 495 |
+
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
|
| 496 |
+
model_kwargs (`dict`, *optional*):
|
| 497 |
+
Additional kwargs to pass to the model during initialization.
|
| 498 |
+
"""
|
| 499 |
+
model_id = str(pretrained_model_name_or_path)
|
| 500 |
+
config_file: str | None = None
|
| 501 |
+
if os.path.isdir(model_id):
|
| 502 |
+
if constants.CONFIG_NAME in os.listdir(model_id):
|
| 503 |
+
config_file = os.path.join(model_id, constants.CONFIG_NAME)
|
| 504 |
+
else:
|
| 505 |
+
logger.warning(f"{constants.CONFIG_NAME} not found in {Path(model_id).resolve()}")
|
| 506 |
+
else:
|
| 507 |
+
try:
|
| 508 |
+
config_file = hf_hub_download(
|
| 509 |
+
repo_id=model_id,
|
| 510 |
+
filename=constants.CONFIG_NAME,
|
| 511 |
+
revision=revision,
|
| 512 |
+
cache_dir=cache_dir,
|
| 513 |
+
force_download=force_download,
|
| 514 |
+
token=token,
|
| 515 |
+
local_files_only=local_files_only,
|
| 516 |
+
)
|
| 517 |
+
except HfHubHTTPError as e:
|
| 518 |
+
logger.info(f"{constants.CONFIG_NAME} not found on the HuggingFace Hub: {str(e)}")
|
| 519 |
+
|
| 520 |
+
# Read config
|
| 521 |
+
config = None
|
| 522 |
+
if config_file is not None:
|
| 523 |
+
with open(config_file, encoding="utf-8") as f:
|
| 524 |
+
config = json.load(f)
|
| 525 |
+
|
| 526 |
+
# Decode custom types in config
|
| 527 |
+
for key, value in config.items():
|
| 528 |
+
if key in cls._hub_mixin_init_parameters:
|
| 529 |
+
expected_type = cls._hub_mixin_init_parameters[key].annotation
|
| 530 |
+
if expected_type is not inspect.Parameter.empty:
|
| 531 |
+
config[key] = cls._decode_arg(expected_type, value)
|
| 532 |
+
|
| 533 |
+
# Populate model_kwargs from config
|
| 534 |
+
for param in cls._hub_mixin_init_parameters.values():
|
| 535 |
+
if param.name not in model_kwargs and param.name in config:
|
| 536 |
+
model_kwargs[param.name] = config[param.name]
|
| 537 |
+
|
| 538 |
+
# Check if `config` argument was passed at init
|
| 539 |
+
if "config" in cls._hub_mixin_init_parameters and "config" not in model_kwargs:
|
| 540 |
+
# Decode `config` argument if it was passed
|
| 541 |
+
config_annotation = cls._hub_mixin_init_parameters["config"].annotation
|
| 542 |
+
config = cls._decode_arg(config_annotation, config)
|
| 543 |
+
|
| 544 |
+
# Forward config to model initialization
|
| 545 |
+
model_kwargs["config"] = config
|
| 546 |
+
|
| 547 |
+
# Inject config if `**kwargs` are expected
|
| 548 |
+
if is_dataclass(cls):
|
| 549 |
+
for key in cls.__dataclass_fields__:
|
| 550 |
+
if key not in model_kwargs and key in config:
|
| 551 |
+
model_kwargs[key] = config[key]
|
| 552 |
+
elif any(param.kind == inspect.Parameter.VAR_KEYWORD for param in cls._hub_mixin_init_parameters.values()):
|
| 553 |
+
for key, value in config.items(): # type: ignore[union-attr]
|
| 554 |
+
if key not in model_kwargs:
|
| 555 |
+
model_kwargs[key] = value
|
| 556 |
+
|
| 557 |
+
# Finally, also inject if `_from_pretrained` expects it
|
| 558 |
+
if cls._hub_mixin_inject_config and "config" not in model_kwargs:
|
| 559 |
+
model_kwargs["config"] = config
|
| 560 |
+
|
| 561 |
+
instance = cls._from_pretrained(
|
| 562 |
+
model_id=str(model_id),
|
| 563 |
+
revision=revision,
|
| 564 |
+
cache_dir=cache_dir,
|
| 565 |
+
force_download=force_download,
|
| 566 |
+
local_files_only=local_files_only,
|
| 567 |
+
token=token,
|
| 568 |
+
**model_kwargs,
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
# Implicitly set the config as instance attribute if not already set by the class
|
| 572 |
+
# This way `config` will be available when calling `save_pretrained` or `push_to_hub`.
|
| 573 |
+
if config is not None and (getattr(instance, "_hub_mixin_config", None) in (None, {})):
|
| 574 |
+
instance._hub_mixin_config = config
|
| 575 |
+
|
| 576 |
+
return instance
|
| 577 |
+
|
| 578 |
+
@classmethod
|
| 579 |
+
def _from_pretrained(
|
| 580 |
+
cls: type[T],
|
| 581 |
+
*,
|
| 582 |
+
model_id: str,
|
| 583 |
+
revision: str | None,
|
| 584 |
+
cache_dir: str | Path | None,
|
| 585 |
+
force_download: bool,
|
| 586 |
+
local_files_only: bool,
|
| 587 |
+
token: str | bool | None,
|
| 588 |
+
**model_kwargs,
|
| 589 |
+
) -> T:
|
| 590 |
+
"""Overwrite this method in subclass to define how to load your model from pretrained.
|
| 591 |
+
|
| 592 |
+
Use [`hf_hub_download`] or [`snapshot_download`] to download files from the Hub before loading them. Most
|
| 593 |
+
args taken as input can be directly passed to those 2 methods. If needed, you can add more arguments to this
|
| 594 |
+
method using "model_kwargs". For example [`PyTorchModelHubMixin._from_pretrained`] takes as input a `map_location`
|
| 595 |
+
parameter to set on which device the model should be loaded.
|
| 596 |
+
|
| 597 |
+
Check out our [integration guide](../guides/integrations) for more instructions.
|
| 598 |
+
|
| 599 |
+
Args:
|
| 600 |
+
model_id (`str`):
|
| 601 |
+
ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
|
| 602 |
+
revision (`str`, *optional*):
|
| 603 |
+
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
|
| 604 |
+
latest commit on `main` branch.
|
| 605 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 606 |
+
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
|
| 607 |
+
the existing cache.
|
| 608 |
+
token (`str` or `bool`, *optional*):
|
| 609 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
| 610 |
+
cached when running `hf auth login`.
|
| 611 |
+
cache_dir (`str`, `Path`, *optional*):
|
| 612 |
+
Path to the folder where cached files are stored.
|
| 613 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 614 |
+
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
|
| 615 |
+
model_kwargs:
|
| 616 |
+
Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
|
| 617 |
+
"""
|
| 618 |
+
raise NotImplementedError
|
| 619 |
+
|
| 620 |
+
@validate_hf_hub_args
|
| 621 |
+
def push_to_hub(
|
| 622 |
+
self,
|
| 623 |
+
repo_id: str,
|
| 624 |
+
*,
|
| 625 |
+
config: dict | DataclassInstance | None = None,
|
| 626 |
+
commit_message: str = "Push model using huggingface_hub.",
|
| 627 |
+
private: bool | None = None,
|
| 628 |
+
token: str | None = None,
|
| 629 |
+
branch: str | None = None,
|
| 630 |
+
create_pr: bool | None = None,
|
| 631 |
+
allow_patterns: list[str] | str | None = None,
|
| 632 |
+
ignore_patterns: list[str] | str | None = None,
|
| 633 |
+
delete_patterns: list[str] | str | None = None,
|
| 634 |
+
model_card_kwargs: dict[str, Any] | None = None,
|
| 635 |
+
) -> str:
|
| 636 |
+
"""
|
| 637 |
+
Upload model checkpoint to the Hub.
|
| 638 |
+
|
| 639 |
+
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
|
| 640 |
+
`delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
|
| 641 |
+
details.
|
| 642 |
+
|
| 643 |
+
Args:
|
| 644 |
+
repo_id (`str`):
|
| 645 |
+
ID of the repository to push to (example: `"username/my-model"`).
|
| 646 |
+
config (`dict` or `DataclassInstance`, *optional*):
|
| 647 |
+
Model configuration specified as a key/value dictionary or a dataclass instance.
|
| 648 |
+
commit_message (`str`, *optional*):
|
| 649 |
+
Message to commit while pushing.
|
| 650 |
+
private (`bool`, *optional*):
|
| 651 |
+
Whether the repository created should be private.
|
| 652 |
+
If `None` (default), the repo will be public unless the organization's default is private.
|
| 653 |
+
token (`str`, *optional*):
|
| 654 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
| 655 |
+
cached when running `hf auth login`.
|
| 656 |
+
branch (`str`, *optional*):
|
| 657 |
+
The git branch on which to push the model. This defaults to `"main"`.
|
| 658 |
+
create_pr (`boolean`, *optional*):
|
| 659 |
+
Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`.
|
| 660 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 661 |
+
If provided, only files matching at least one pattern are pushed.
|
| 662 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 663 |
+
If provided, files matching any of the patterns are not pushed.
|
| 664 |
+
delete_patterns (`list[str]` or `str`, *optional*):
|
| 665 |
+
If provided, remote files matching any of the patterns will be deleted from the repo.
|
| 666 |
+
model_card_kwargs (`dict[str, Any]`, *optional*):
|
| 667 |
+
Additional arguments passed to the model card template to customize the model card.
|
| 668 |
+
|
| 669 |
+
Returns:
|
| 670 |
+
The url of the commit of your model in the given repository.
|
| 671 |
+
"""
|
| 672 |
+
api = HfApi(token=token)
|
| 673 |
+
repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id
|
| 674 |
+
|
| 675 |
+
# Push the files to the repo in a single commit
|
| 676 |
+
with SoftTemporaryDirectory() as tmp:
|
| 677 |
+
saved_path = Path(tmp) / repo_id
|
| 678 |
+
self.save_pretrained(saved_path, config=config, model_card_kwargs=model_card_kwargs)
|
| 679 |
+
return api.upload_folder(
|
| 680 |
+
repo_id=repo_id,
|
| 681 |
+
repo_type="model",
|
| 682 |
+
folder_path=saved_path,
|
| 683 |
+
commit_message=commit_message,
|
| 684 |
+
revision=branch,
|
| 685 |
+
create_pr=create_pr,
|
| 686 |
+
allow_patterns=allow_patterns,
|
| 687 |
+
ignore_patterns=ignore_patterns,
|
| 688 |
+
delete_patterns=delete_patterns,
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
def generate_model_card(self, *args, **kwargs) -> ModelCard:
|
| 692 |
+
card = ModelCard.from_template(
|
| 693 |
+
card_data=self._hub_mixin_info.model_card_data,
|
| 694 |
+
template_str=self._hub_mixin_info.model_card_template,
|
| 695 |
+
repo_url=self._hub_mixin_info.repo_url,
|
| 696 |
+
paper_url=self._hub_mixin_info.paper_url,
|
| 697 |
+
docs_url=self._hub_mixin_info.docs_url,
|
| 698 |
+
**kwargs,
|
| 699 |
+
)
|
| 700 |
+
return card
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class PyTorchModelHubMixin(ModelHubMixin):
|
| 704 |
+
"""
|
| 705 |
+
Implementation of [`ModelHubMixin`] to provide model Hub upload/download capabilities to PyTorch models. The model
|
| 706 |
+
is set in evaluation mode by default using `model.eval()` (dropout modules are deactivated). To train the model,
|
| 707 |
+
you should first set it back in training mode with `model.train()`.
|
| 708 |
+
|
| 709 |
+
See [`ModelHubMixin`] for more details on how to use the mixin.
|
| 710 |
+
|
| 711 |
+
Example:
|
| 712 |
+
|
| 713 |
+
```python
|
| 714 |
+
>>> import torch
|
| 715 |
+
>>> import torch.nn as nn
|
| 716 |
+
>>> from huggingface_hub import PyTorchModelHubMixin
|
| 717 |
+
|
| 718 |
+
>>> class MyModel(
|
| 719 |
+
... nn.Module,
|
| 720 |
+
... PyTorchModelHubMixin,
|
| 721 |
+
... library_name="keras-nlp",
|
| 722 |
+
... repo_url="https://github.com/keras-team/keras-nlp",
|
| 723 |
+
... paper_url="https://arxiv.org/abs/2304.12244",
|
| 724 |
+
... docs_url="https://keras.io/keras_nlp/",
|
| 725 |
+
... # ^ optional metadata to generate model card
|
| 726 |
+
... ):
|
| 727 |
+
... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
|
| 728 |
+
... super().__init__()
|
| 729 |
+
... self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
|
| 730 |
+
... self.linear = nn.Linear(output_size, vocab_size)
|
| 731 |
+
|
| 732 |
+
... def forward(self, x):
|
| 733 |
+
... return self.linear(x + self.param)
|
| 734 |
+
>>> model = MyModel(hidden_size=256)
|
| 735 |
+
|
| 736 |
+
# Save model weights to local directory
|
| 737 |
+
>>> model.save_pretrained("my-awesome-model")
|
| 738 |
+
|
| 739 |
+
# Push model weights to the Hub
|
| 740 |
+
>>> model.push_to_hub("my-awesome-model")
|
| 741 |
+
|
| 742 |
+
# Download and initialize weights from the Hub
|
| 743 |
+
>>> model = MyModel.from_pretrained("username/my-awesome-model")
|
| 744 |
+
>>> model.hidden_size
|
| 745 |
+
256
|
| 746 |
+
```
|
| 747 |
+
"""
|
| 748 |
+
|
| 749 |
+
def __init_subclass__(cls, *args, tags: list[str] | None = None, **kwargs) -> None:
|
| 750 |
+
tags = tags or []
|
| 751 |
+
tags.append("pytorch_model_hub_mixin")
|
| 752 |
+
kwargs["tags"] = tags
|
| 753 |
+
return super().__init_subclass__(*args, **kwargs)
|
| 754 |
+
|
| 755 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
| 756 |
+
"""Save weights from a Pytorch model to a local directory."""
|
| 757 |
+
model_to_save = self.module if hasattr(self, "module") else self # type: ignore
|
| 758 |
+
save_model_as_safetensor(model_to_save, str(save_directory / constants.SAFETENSORS_SINGLE_FILE)) # type: ignore [arg-type]
|
| 759 |
+
|
| 760 |
+
@classmethod
|
| 761 |
+
def _from_pretrained(
|
| 762 |
+
cls,
|
| 763 |
+
*,
|
| 764 |
+
model_id: str,
|
| 765 |
+
revision: str | None,
|
| 766 |
+
cache_dir: str | Path | None,
|
| 767 |
+
force_download: bool,
|
| 768 |
+
local_files_only: bool,
|
| 769 |
+
token: str | bool | None,
|
| 770 |
+
map_location: str = "cpu",
|
| 771 |
+
strict: bool = False,
|
| 772 |
+
**model_kwargs,
|
| 773 |
+
):
|
| 774 |
+
"""Load Pytorch pretrained weights and return the loaded model."""
|
| 775 |
+
model = cls(**model_kwargs)
|
| 776 |
+
if os.path.isdir(model_id):
|
| 777 |
+
print("Loading weights from local directory")
|
| 778 |
+
model_file = os.path.join(model_id, constants.SAFETENSORS_SINGLE_FILE)
|
| 779 |
+
return cls._load_as_safetensor(model, model_file, map_location, strict)
|
| 780 |
+
else:
|
| 781 |
+
try:
|
| 782 |
+
model_file = hf_hub_download(
|
| 783 |
+
repo_id=model_id,
|
| 784 |
+
filename=constants.SAFETENSORS_SINGLE_FILE,
|
| 785 |
+
revision=revision,
|
| 786 |
+
cache_dir=cache_dir,
|
| 787 |
+
force_download=force_download,
|
| 788 |
+
token=token,
|
| 789 |
+
local_files_only=local_files_only,
|
| 790 |
+
)
|
| 791 |
+
return cls._load_as_safetensor(model, model_file, map_location, strict)
|
| 792 |
+
except EntryNotFoundError:
|
| 793 |
+
model_file = hf_hub_download(
|
| 794 |
+
repo_id=model_id,
|
| 795 |
+
filename=constants.PYTORCH_WEIGHTS_NAME,
|
| 796 |
+
revision=revision,
|
| 797 |
+
cache_dir=cache_dir,
|
| 798 |
+
force_download=force_download,
|
| 799 |
+
token=token,
|
| 800 |
+
local_files_only=local_files_only,
|
| 801 |
+
)
|
| 802 |
+
return cls._load_as_pickle(model, model_file, map_location, strict)
|
| 803 |
+
|
| 804 |
+
@classmethod
|
| 805 |
+
def _load_as_pickle(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
|
| 806 |
+
state_dict = torch.load(model_file, map_location=torch.device(map_location), weights_only=True)
|
| 807 |
+
model.load_state_dict(state_dict, strict=strict) # type: ignore
|
| 808 |
+
model.eval() # type: ignore
|
| 809 |
+
return model
|
| 810 |
+
|
| 811 |
+
@classmethod
|
| 812 |
+
def _load_as_safetensor(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
|
| 813 |
+
if packaging.version.parse(safetensors.__version__) < packaging.version.parse("0.4.3"): # type: ignore [attr-defined]
|
| 814 |
+
load_model_as_safetensor(model, model_file, strict=strict) # type: ignore [arg-type]
|
| 815 |
+
if map_location != "cpu":
|
| 816 |
+
logger.warning(
|
| 817 |
+
"Loading model weights on other devices than 'cpu' is not supported natively in your version of safetensors."
|
| 818 |
+
" This means that the model is loaded on 'cpu' first and then copied to the device."
|
| 819 |
+
" This leads to a slower loading time."
|
| 820 |
+
" Please update safetensors to version 0.4.3 or above for improved performance."
|
| 821 |
+
)
|
| 822 |
+
model.to(map_location) # type: ignore [attr-defined]
|
| 823 |
+
else:
|
| 824 |
+
safetensors.torch.load_model(model, model_file, strict=strict, device=map_location) # type: ignore [arg-type]
|
| 825 |
+
model.eval() # type: ignore
|
| 826 |
+
return model
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def _load_dataclass(datacls: type[DataclassInstance], data: dict) -> DataclassInstance:
|
| 830 |
+
"""Load a dataclass instance from a dictionary.
|
| 831 |
+
|
| 832 |
+
Fields not expected by the dataclass are ignored.
|
| 833 |
+
"""
|
| 834 |
+
return datacls(**{k: v for k, v in data.items() if k in datacls.__dataclass_fields__})
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/lfs.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Git LFS related type definitions and utilities"""
|
| 15 |
+
|
| 16 |
+
import io
|
| 17 |
+
import re
|
| 18 |
+
from collections.abc import Iterable
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from math import ceil
|
| 21 |
+
from os.path import getsize
|
| 22 |
+
from typing import TYPE_CHECKING, BinaryIO, TypedDict
|
| 23 |
+
from urllib.parse import unquote
|
| 24 |
+
|
| 25 |
+
from huggingface_hub import constants
|
| 26 |
+
|
| 27 |
+
from .utils import (
|
| 28 |
+
build_hf_headers,
|
| 29 |
+
fix_hf_endpoint_in_url,
|
| 30 |
+
hf_raise_for_status,
|
| 31 |
+
http_backoff,
|
| 32 |
+
logging,
|
| 33 |
+
validate_hf_hub_args,
|
| 34 |
+
)
|
| 35 |
+
from .utils._lfs import SliceFileObj
|
| 36 |
+
from .utils.sha import sha256, sha_fileobj
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
from ._commit_api import CommitOperationAdd
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
OID_REGEX = re.compile(r"^[0-9a-f]{40}$")
|
| 45 |
+
|
| 46 |
+
LFS_MULTIPART_UPLOAD_COMMAND = "lfs-multipart-upload"
|
| 47 |
+
|
| 48 |
+
LFS_HEADERS = {
|
| 49 |
+
"Accept": "application/vnd.git-lfs+json",
|
| 50 |
+
"Content-Type": "application/vnd.git-lfs+json",
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass
|
| 55 |
+
class UploadInfo:
|
| 56 |
+
"""
|
| 57 |
+
Dataclass holding required information to determine whether a blob
|
| 58 |
+
should be uploaded to the hub using the LFS protocol or the regular protocol
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
sha256 (`bytes`):
|
| 62 |
+
SHA256 hash of the blob
|
| 63 |
+
size (`int`):
|
| 64 |
+
Size in bytes of the blob
|
| 65 |
+
sample (`bytes`):
|
| 66 |
+
First 512 bytes of the blob
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
sha256: bytes
|
| 70 |
+
size: int
|
| 71 |
+
sample: bytes
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def from_path(cls, path: str):
|
| 75 |
+
size = getsize(path)
|
| 76 |
+
with open(path, "rb") as file:
|
| 77 |
+
sample = file.peek(512)[:512]
|
| 78 |
+
sha = sha_fileobj(file)
|
| 79 |
+
return cls(size=size, sha256=sha, sample=sample)
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def from_bytes(cls, data: bytes):
|
| 83 |
+
sha = sha256(data).digest()
|
| 84 |
+
return cls(size=len(data), sample=data[:512], sha256=sha)
|
| 85 |
+
|
| 86 |
+
@classmethod
|
| 87 |
+
def from_fileobj(cls, fileobj: BinaryIO):
|
| 88 |
+
sample = fileobj.read(512)
|
| 89 |
+
fileobj.seek(0, io.SEEK_SET)
|
| 90 |
+
sha = sha_fileobj(fileobj)
|
| 91 |
+
size = fileobj.tell()
|
| 92 |
+
fileobj.seek(0, io.SEEK_SET)
|
| 93 |
+
return cls(size=size, sha256=sha, sample=sample)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@validate_hf_hub_args
|
| 97 |
+
def post_lfs_batch_info(
|
| 98 |
+
upload_infos: Iterable[UploadInfo],
|
| 99 |
+
token: str | None,
|
| 100 |
+
repo_type: str,
|
| 101 |
+
repo_id: str,
|
| 102 |
+
revision: str | None = None,
|
| 103 |
+
endpoint: str | None = None,
|
| 104 |
+
headers: dict[str, str] | None = None,
|
| 105 |
+
transfers: list[str] | None = None,
|
| 106 |
+
) -> tuple[list[dict], list[dict], str | None]:
|
| 107 |
+
"""
|
| 108 |
+
Requests the LFS batch endpoint to retrieve upload instructions
|
| 109 |
+
|
| 110 |
+
Learn more: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
upload_infos (`Iterable` of `UploadInfo`):
|
| 114 |
+
`UploadInfo` for the files that are being uploaded, typically obtained
|
| 115 |
+
from `CommitOperationAdd.upload_info`
|
| 116 |
+
repo_type (`str`):
|
| 117 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 118 |
+
repo_id (`str`):
|
| 119 |
+
A namespace (user or an organization) and a repo name separated
|
| 120 |
+
by a `/`.
|
| 121 |
+
revision (`str`, *optional*):
|
| 122 |
+
The git revision to upload to.
|
| 123 |
+
headers (`dict`, *optional*):
|
| 124 |
+
Additional headers to include in the request
|
| 125 |
+
transfers (`list`, *optional*):
|
| 126 |
+
List of transfer methods to use. Defaults to ["basic", "multipart"].
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
`LfsBatchInfo`: 3-tuple:
|
| 130 |
+
- First element is the list of upload instructions from the server
|
| 131 |
+
- Second element is a list of errors, if any
|
| 132 |
+
- Third element is the chosen transfer adapter if provided by the server (e.g. "basic", "multipart", "xet")
|
| 133 |
+
|
| 134 |
+
Raises:
|
| 135 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 136 |
+
If an argument is invalid or the server response is malformed.
|
| 137 |
+
[`HfHubHTTPError`]
|
| 138 |
+
If the server returned an error.
|
| 139 |
+
"""
|
| 140 |
+
endpoint = endpoint if endpoint is not None else constants.ENDPOINT
|
| 141 |
+
url_prefix = ""
|
| 142 |
+
if repo_type in constants.REPO_TYPES_URL_PREFIXES:
|
| 143 |
+
url_prefix = constants.REPO_TYPES_URL_PREFIXES[repo_type]
|
| 144 |
+
batch_url = f"{endpoint}/{url_prefix}{repo_id}.git/info/lfs/objects/batch"
|
| 145 |
+
payload: dict = {
|
| 146 |
+
"operation": "upload",
|
| 147 |
+
"transfers": transfers if transfers is not None else ["basic", "multipart"],
|
| 148 |
+
"objects": [
|
| 149 |
+
{
|
| 150 |
+
"oid": upload.sha256.hex(),
|
| 151 |
+
"size": upload.size,
|
| 152 |
+
}
|
| 153 |
+
for upload in upload_infos
|
| 154 |
+
],
|
| 155 |
+
"hash_algo": "sha256",
|
| 156 |
+
}
|
| 157 |
+
if revision is not None:
|
| 158 |
+
payload["ref"] = {"name": unquote(revision)} # revision has been previously 'quoted'
|
| 159 |
+
|
| 160 |
+
headers = {
|
| 161 |
+
**LFS_HEADERS,
|
| 162 |
+
**build_hf_headers(token=token),
|
| 163 |
+
**(headers or {}),
|
| 164 |
+
}
|
| 165 |
+
resp = http_backoff("POST", batch_url, headers=headers, json=payload)
|
| 166 |
+
hf_raise_for_status(resp)
|
| 167 |
+
batch_info = resp.json()
|
| 168 |
+
|
| 169 |
+
objects = batch_info.get("objects", None)
|
| 170 |
+
if not isinstance(objects, list):
|
| 171 |
+
raise ValueError("Malformed response from server")
|
| 172 |
+
|
| 173 |
+
chosen_transfer = batch_info.get("transfer")
|
| 174 |
+
chosen_transfer = chosen_transfer if isinstance(chosen_transfer, str) else None
|
| 175 |
+
|
| 176 |
+
return (
|
| 177 |
+
[_validate_batch_actions(obj) for obj in objects if "error" not in obj],
|
| 178 |
+
[_validate_batch_error(obj) for obj in objects if "error" in obj],
|
| 179 |
+
chosen_transfer,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class PayloadPartT(TypedDict):
|
| 184 |
+
partNumber: int
|
| 185 |
+
etag: str
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class CompletionPayloadT(TypedDict):
|
| 189 |
+
"""Payload that will be sent to the Hub when uploading multi-part."""
|
| 190 |
+
|
| 191 |
+
oid: str
|
| 192 |
+
parts: list[PayloadPartT]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def lfs_upload(
|
| 196 |
+
operation: "CommitOperationAdd",
|
| 197 |
+
lfs_batch_action: dict,
|
| 198 |
+
token: str | None = None,
|
| 199 |
+
headers: dict[str, str] | None = None,
|
| 200 |
+
endpoint: str | None = None,
|
| 201 |
+
) -> None:
|
| 202 |
+
"""
|
| 203 |
+
Handles uploading a given object to the Hub with the LFS protocol.
|
| 204 |
+
|
| 205 |
+
Can be a No-op if the content of the file is already present on the hub large file storage.
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
operation (`CommitOperationAdd`):
|
| 209 |
+
The add operation triggering this upload.
|
| 210 |
+
lfs_batch_action (`dict`):
|
| 211 |
+
Upload instructions from the LFS batch endpoint for this object. See [`~utils.lfs.post_lfs_batch_info`] for
|
| 212 |
+
more details.
|
| 213 |
+
headers (`dict`, *optional*):
|
| 214 |
+
Headers to include in the request, including authentication and user agent headers.
|
| 215 |
+
|
| 216 |
+
Raises:
|
| 217 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 218 |
+
If `lfs_batch_action` is improperly formatted
|
| 219 |
+
[`HfHubHTTPError`]
|
| 220 |
+
If the upload resulted in an error
|
| 221 |
+
"""
|
| 222 |
+
# 0. If LFS file is already present, skip upload
|
| 223 |
+
_validate_batch_actions(lfs_batch_action)
|
| 224 |
+
actions = lfs_batch_action.get("actions")
|
| 225 |
+
if actions is None:
|
| 226 |
+
# The file was already uploaded
|
| 227 |
+
logger.debug(f"Content of file {operation.path_in_repo} is already present upstream - skipping upload")
|
| 228 |
+
return
|
| 229 |
+
|
| 230 |
+
# 1. Validate server response (check required keys in dict)
|
| 231 |
+
upload_action = lfs_batch_action["actions"]["upload"]
|
| 232 |
+
_validate_lfs_action(upload_action)
|
| 233 |
+
verify_action = lfs_batch_action["actions"].get("verify")
|
| 234 |
+
if verify_action is not None:
|
| 235 |
+
_validate_lfs_action(verify_action)
|
| 236 |
+
|
| 237 |
+
# 2. Upload file (either single part or multi-part)
|
| 238 |
+
header = upload_action.get("header", {})
|
| 239 |
+
chunk_size = header.get("chunk_size")
|
| 240 |
+
upload_url = fix_hf_endpoint_in_url(upload_action["href"], endpoint=endpoint)
|
| 241 |
+
if chunk_size is not None:
|
| 242 |
+
try:
|
| 243 |
+
chunk_size = int(chunk_size)
|
| 244 |
+
except (ValueError, TypeError):
|
| 245 |
+
raise ValueError(
|
| 246 |
+
f"Malformed response from LFS batch endpoint: `chunk_size` should be an integer. Got '{chunk_size}'."
|
| 247 |
+
)
|
| 248 |
+
_upload_multi_part(operation=operation, header=header, chunk_size=chunk_size, upload_url=upload_url)
|
| 249 |
+
else:
|
| 250 |
+
_upload_single_part(operation=operation, upload_url=upload_url)
|
| 251 |
+
|
| 252 |
+
# 3. Verify upload went well
|
| 253 |
+
if verify_action is not None:
|
| 254 |
+
_validate_lfs_action(verify_action)
|
| 255 |
+
verify_url = fix_hf_endpoint_in_url(verify_action["href"], endpoint)
|
| 256 |
+
verify_resp = http_backoff(
|
| 257 |
+
"POST",
|
| 258 |
+
verify_url,
|
| 259 |
+
headers=build_hf_headers(token=token, headers=headers),
|
| 260 |
+
json={"oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size},
|
| 261 |
+
)
|
| 262 |
+
hf_raise_for_status(verify_resp)
|
| 263 |
+
logger.debug(f"{operation.path_in_repo}: Upload successful")
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _validate_lfs_action(lfs_action: dict):
|
| 267 |
+
"""validates response from the LFS batch endpoint"""
|
| 268 |
+
if not (
|
| 269 |
+
isinstance(lfs_action.get("href"), str)
|
| 270 |
+
and (lfs_action.get("header") is None or isinstance(lfs_action.get("header"), dict))
|
| 271 |
+
):
|
| 272 |
+
raise ValueError("lfs_action is improperly formatted")
|
| 273 |
+
return lfs_action
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _validate_batch_actions(lfs_batch_actions: dict):
|
| 277 |
+
"""validates response from the LFS batch endpoint"""
|
| 278 |
+
if not (isinstance(lfs_batch_actions.get("oid"), str) and isinstance(lfs_batch_actions.get("size"), int)):
|
| 279 |
+
raise ValueError("lfs_batch_actions is improperly formatted")
|
| 280 |
+
|
| 281 |
+
upload_action = lfs_batch_actions.get("actions", {}).get("upload")
|
| 282 |
+
verify_action = lfs_batch_actions.get("actions", {}).get("verify")
|
| 283 |
+
if upload_action is not None:
|
| 284 |
+
_validate_lfs_action(upload_action)
|
| 285 |
+
if verify_action is not None:
|
| 286 |
+
_validate_lfs_action(verify_action)
|
| 287 |
+
return lfs_batch_actions
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _validate_batch_error(lfs_batch_error: dict):
|
| 291 |
+
"""validates response from the LFS batch endpoint"""
|
| 292 |
+
if not (isinstance(lfs_batch_error.get("oid"), str) and isinstance(lfs_batch_error.get("size"), int)):
|
| 293 |
+
raise ValueError("lfs_batch_error is improperly formatted")
|
| 294 |
+
error_info = lfs_batch_error.get("error")
|
| 295 |
+
if not (
|
| 296 |
+
isinstance(error_info, dict)
|
| 297 |
+
and isinstance(error_info.get("message"), str)
|
| 298 |
+
and isinstance(error_info.get("code"), int)
|
| 299 |
+
):
|
| 300 |
+
raise ValueError("lfs_batch_error is improperly formatted")
|
| 301 |
+
return lfs_batch_error
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _upload_single_part(operation: "CommitOperationAdd", upload_url: str) -> None:
|
| 305 |
+
"""
|
| 306 |
+
Uploads `fileobj` as a single PUT HTTP request (basic LFS transfer protocol)
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
upload_url (`str`):
|
| 310 |
+
The URL to PUT the file to.
|
| 311 |
+
fileobj:
|
| 312 |
+
The file-like object holding the data to upload.
|
| 313 |
+
|
| 314 |
+
Raises:
|
| 315 |
+
[`HfHubHTTPError`]
|
| 316 |
+
If the upload resulted in an error.
|
| 317 |
+
"""
|
| 318 |
+
with operation.as_file(with_tqdm=True) as fileobj:
|
| 319 |
+
# S3 might raise a transient 500 error -> let's retry if that happens
|
| 320 |
+
response = http_backoff("PUT", upload_url, data=fileobj)
|
| 321 |
+
hf_raise_for_status(response)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _upload_multi_part(operation: "CommitOperationAdd", header: dict, chunk_size: int, upload_url: str) -> None:
|
| 325 |
+
"""
|
| 326 |
+
Uploads file using HF multipart LFS transfer protocol.
|
| 327 |
+
"""
|
| 328 |
+
# 1. Get upload URLs for each part
|
| 329 |
+
sorted_parts_urls = _get_sorted_parts_urls(header=header, upload_info=operation.upload_info, chunk_size=chunk_size)
|
| 330 |
+
|
| 331 |
+
# 2. Upload parts (pure Python)
|
| 332 |
+
response_headers = _upload_parts_iteratively(
|
| 333 |
+
operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# 3. Send completion request
|
| 337 |
+
# NOTE: `upload_url` is the Hub completion endpoint (not the S3 upload URLs).
|
| 338 |
+
completion_res = http_backoff(
|
| 339 |
+
"POST",
|
| 340 |
+
upload_url,
|
| 341 |
+
json=_get_completion_payload(response_headers, operation.upload_info.sha256.hex()),
|
| 342 |
+
headers=LFS_HEADERS,
|
| 343 |
+
)
|
| 344 |
+
hf_raise_for_status(completion_res)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def _get_sorted_parts_urls(header: dict, upload_info: UploadInfo, chunk_size: int) -> list[str]:
|
| 348 |
+
sorted_part_upload_urls = [
|
| 349 |
+
upload_url
|
| 350 |
+
for _, upload_url in sorted(
|
| 351 |
+
[
|
| 352 |
+
(int(part_num, 10), upload_url)
|
| 353 |
+
for part_num, upload_url in header.items()
|
| 354 |
+
if part_num.isdigit() and len(part_num) > 0
|
| 355 |
+
],
|
| 356 |
+
key=lambda t: t[0],
|
| 357 |
+
)
|
| 358 |
+
]
|
| 359 |
+
num_parts = len(sorted_part_upload_urls)
|
| 360 |
+
if num_parts != ceil(upload_info.size / chunk_size):
|
| 361 |
+
raise ValueError("Invalid server response to upload large LFS file")
|
| 362 |
+
return sorted_part_upload_urls
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def _get_completion_payload(response_headers: list[dict], oid: str) -> CompletionPayloadT:
|
| 366 |
+
parts: list[PayloadPartT] = []
|
| 367 |
+
for part_number, header in enumerate(response_headers):
|
| 368 |
+
etag = header.get("etag")
|
| 369 |
+
if etag is None or etag == "":
|
| 370 |
+
raise ValueError(f"Invalid etag (`{etag}`) returned for part {part_number + 1}")
|
| 371 |
+
parts.append(
|
| 372 |
+
{
|
| 373 |
+
"partNumber": part_number + 1,
|
| 374 |
+
"etag": etag,
|
| 375 |
+
}
|
| 376 |
+
)
|
| 377 |
+
return {"oid": oid, "parts": parts}
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _upload_parts_iteratively(
|
| 381 |
+
operation: "CommitOperationAdd", sorted_parts_urls: list[str], chunk_size: int
|
| 382 |
+
) -> list[dict]:
|
| 383 |
+
headers = []
|
| 384 |
+
with operation.as_file(with_tqdm=True) as fileobj:
|
| 385 |
+
for part_idx, part_upload_url in enumerate(sorted_parts_urls):
|
| 386 |
+
with SliceFileObj(
|
| 387 |
+
fileobj,
|
| 388 |
+
seek_from=chunk_size * part_idx,
|
| 389 |
+
read_limit=chunk_size,
|
| 390 |
+
) as fileobj_slice:
|
| 391 |
+
# S3 might raise a transient 500 error -> let's retry if that happens
|
| 392 |
+
part_upload_res = http_backoff("PUT", part_upload_url, data=fileobj_slice)
|
| 393 |
+
hf_raise_for_status(part_upload_res)
|
| 394 |
+
headers.append(part_upload_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|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any, Literal
|
| 5 |
+
|
| 6 |
+
import yaml
|
| 7 |
+
|
| 8 |
+
from huggingface_hub.file_download import hf_hub_download
|
| 9 |
+
from huggingface_hub.hf_api import upload_file
|
| 10 |
+
from huggingface_hub.repocard_data import (
|
| 11 |
+
CardData,
|
| 12 |
+
DatasetCardData,
|
| 13 |
+
EvalResult,
|
| 14 |
+
ModelCardData,
|
| 15 |
+
SpaceCardData,
|
| 16 |
+
eval_results_to_model_index,
|
| 17 |
+
model_index_to_eval_results,
|
| 18 |
+
)
|
| 19 |
+
from huggingface_hub.utils import HfHubHTTPError, get_session, hf_raise_for_status, is_jinja_available, yaml_dump
|
| 20 |
+
|
| 21 |
+
from . import constants
|
| 22 |
+
from .errors import EntryNotFoundError
|
| 23 |
+
from .utils import SoftTemporaryDirectory, logging, validate_hf_hub_args
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
TEMPLATE_MODELCARD_PATH = Path(__file__).parent / "templates" / "modelcard_template.md"
|
| 30 |
+
TEMPLATE_DATASETCARD_PATH = Path(__file__).parent / "templates" / "datasetcard_template.md"
|
| 31 |
+
|
| 32 |
+
# exact same regex as in the Hub server. Please keep in sync.
|
| 33 |
+
# See https://github.com/huggingface/moon-landing/blob/main/server/lib/ViewMarkdown.ts#L18
|
| 34 |
+
REGEX_YAML_BLOCK = re.compile(r"^(\s*---[\r\n]+)([\S\s]*?)([\r\n]+---(\r\n|\n|$))")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class RepoCard:
|
| 38 |
+
card_data_class = CardData
|
| 39 |
+
default_template_path = TEMPLATE_MODELCARD_PATH
|
| 40 |
+
repo_type = "model"
|
| 41 |
+
|
| 42 |
+
def __init__(self, content: str, ignore_metadata_errors: bool = False):
|
| 43 |
+
"""Initialize a RepoCard from string content. The content should be a
|
| 44 |
+
Markdown file with a YAML block at the beginning and a Markdown body.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
content (`str`): The content of the Markdown file.
|
| 48 |
+
|
| 49 |
+
Example:
|
| 50 |
+
```python
|
| 51 |
+
>>> from huggingface_hub.repocard import RepoCard
|
| 52 |
+
>>> text = '''
|
| 53 |
+
... ---
|
| 54 |
+
... language: en
|
| 55 |
+
... license: mit
|
| 56 |
+
... ---
|
| 57 |
+
...
|
| 58 |
+
... # My repo
|
| 59 |
+
... '''
|
| 60 |
+
>>> card = RepoCard(text)
|
| 61 |
+
>>> card.data.to_dict()
|
| 62 |
+
{'language': 'en', 'license': 'mit'}
|
| 63 |
+
>>> card.text
|
| 64 |
+
'\\n# My repo\\n'
|
| 65 |
+
|
| 66 |
+
```
|
| 67 |
+
> [!TIP]
|
| 68 |
+
> Raises the following error:
|
| 69 |
+
>
|
| 70 |
+
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 71 |
+
> when the content of the repo card metadata is not a dictionary.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
# Set the content of the RepoCard, as well as underlying .data and .text attributes.
|
| 75 |
+
# See the `content` property setter for more details.
|
| 76 |
+
self.ignore_metadata_errors = ignore_metadata_errors
|
| 77 |
+
self.content = content
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def content(self):
|
| 81 |
+
"""The content of the RepoCard, including the YAML block and the Markdown body."""
|
| 82 |
+
line_break = _detect_line_ending(self._content) or "\n"
|
| 83 |
+
return f"---{line_break}{self.data.to_yaml(line_break=line_break, original_order=self._original_order)}{line_break}---{line_break}{self.text}"
|
| 84 |
+
|
| 85 |
+
@content.setter
|
| 86 |
+
def content(self, content: str):
|
| 87 |
+
"""Set the content of the RepoCard."""
|
| 88 |
+
self._content = content
|
| 89 |
+
|
| 90 |
+
match = REGEX_YAML_BLOCK.search(content)
|
| 91 |
+
if match:
|
| 92 |
+
# Metadata found in the YAML block
|
| 93 |
+
yaml_block = match.group(2)
|
| 94 |
+
self.text = content[match.end() :]
|
| 95 |
+
data_dict = yaml.safe_load(yaml_block)
|
| 96 |
+
|
| 97 |
+
if data_dict is None:
|
| 98 |
+
data_dict = {}
|
| 99 |
+
|
| 100 |
+
# The YAML block's data should be a dictionary
|
| 101 |
+
if not isinstance(data_dict, dict):
|
| 102 |
+
raise ValueError("repo card metadata block should be a dict")
|
| 103 |
+
else:
|
| 104 |
+
# Model card without metadata... create empty metadata
|
| 105 |
+
logger.warning("Repo card metadata block was not found. Setting CardData to empty.")
|
| 106 |
+
data_dict = {}
|
| 107 |
+
self.text = content
|
| 108 |
+
|
| 109 |
+
self.data = self.card_data_class(**data_dict, ignore_metadata_errors=self.ignore_metadata_errors)
|
| 110 |
+
self._original_order = list(data_dict.keys())
|
| 111 |
+
|
| 112 |
+
def __str__(self):
|
| 113 |
+
return self.content
|
| 114 |
+
|
| 115 |
+
def save(self, filepath: Path | str):
|
| 116 |
+
r"""Save a RepoCard to a file.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
filepath (`Union[Path, str]`): Filepath to the markdown file to save.
|
| 120 |
+
|
| 121 |
+
Example:
|
| 122 |
+
```python
|
| 123 |
+
>>> from huggingface_hub.repocard import RepoCard
|
| 124 |
+
>>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
|
| 125 |
+
>>> card.save("/tmp/test.md")
|
| 126 |
+
|
| 127 |
+
```
|
| 128 |
+
"""
|
| 129 |
+
filepath = Path(filepath)
|
| 130 |
+
filepath.parent.mkdir(parents=True, exist_ok=True)
|
| 131 |
+
# Preserve newlines as in the existing file.
|
| 132 |
+
with open(filepath, mode="w", newline="", encoding="utf-8") as f:
|
| 133 |
+
f.write(str(self))
|
| 134 |
+
|
| 135 |
+
@classmethod
|
| 136 |
+
def load(
|
| 137 |
+
cls,
|
| 138 |
+
repo_id_or_path: str | Path,
|
| 139 |
+
repo_type: str | None = None,
|
| 140 |
+
token: str | None = None,
|
| 141 |
+
ignore_metadata_errors: bool = False,
|
| 142 |
+
):
|
| 143 |
+
"""Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
repo_id_or_path (`Union[str, Path]`):
|
| 147 |
+
The repo ID associated with a Hugging Face Hub repo or a local filepath.
|
| 148 |
+
repo_type (`str`, *optional*):
|
| 149 |
+
The type of Hugging Face repo to push to. Defaults to None, which will use "model". Other options
|
| 150 |
+
are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child
|
| 151 |
+
class, the default value will be the child class's `repo_type`.
|
| 152 |
+
token (`str`, *optional*):
|
| 153 |
+
Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
|
| 154 |
+
ignore_metadata_errors (`str`):
|
| 155 |
+
If True, errors while parsing the metadata section will be ignored. Some information might be lost during
|
| 156 |
+
the process. Use it at your own risk.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
[`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's
|
| 160 |
+
README.md file or filepath.
|
| 161 |
+
|
| 162 |
+
Example:
|
| 163 |
+
```python
|
| 164 |
+
>>> from huggingface_hub.repocard import RepoCard
|
| 165 |
+
>>> card = RepoCard.load("nateraw/food")
|
| 166 |
+
>>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]
|
| 167 |
+
|
| 168 |
+
```
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
if Path(repo_id_or_path).is_file():
|
| 172 |
+
card_path = Path(repo_id_or_path)
|
| 173 |
+
elif isinstance(repo_id_or_path, str):
|
| 174 |
+
card_path = Path(
|
| 175 |
+
hf_hub_download(
|
| 176 |
+
repo_id_or_path,
|
| 177 |
+
constants.REPOCARD_NAME,
|
| 178 |
+
repo_type=repo_type or cls.repo_type,
|
| 179 |
+
token=token,
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
raise ValueError(f"Cannot load RepoCard: path not found on disk ({repo_id_or_path}).")
|
| 184 |
+
|
| 185 |
+
# Preserve newlines in the existing file.
|
| 186 |
+
with card_path.open(mode="r", newline="", encoding="utf-8") as f:
|
| 187 |
+
return cls(f.read(), ignore_metadata_errors=ignore_metadata_errors)
|
| 188 |
+
|
| 189 |
+
def validate(self, repo_type: str | None = None):
|
| 190 |
+
"""Validates card against Hugging Face Hub's card validation logic.
|
| 191 |
+
Using this function requires access to the internet, so it is only called
|
| 192 |
+
internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`].
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
repo_type (`str`, *optional*, defaults to "model"):
|
| 196 |
+
The type of Hugging Face repo to push to. Options are "model", "dataset", and "space".
|
| 197 |
+
If this function is called from a child class, the default will be the child class's `repo_type`.
|
| 198 |
+
|
| 199 |
+
> [!TIP]
|
| 200 |
+
> Raises the following errors:
|
| 201 |
+
>
|
| 202 |
+
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 203 |
+
> if the card fails validation checks.
|
| 204 |
+
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
|
| 205 |
+
> if the request to the Hub API fails for any other reason.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
# If repo type is provided, otherwise, use the repo type of the card.
|
| 209 |
+
repo_type = repo_type or self.repo_type
|
| 210 |
+
|
| 211 |
+
body = {
|
| 212 |
+
"repoType": repo_type,
|
| 213 |
+
"content": str(self),
|
| 214 |
+
}
|
| 215 |
+
headers = {"Accept": "text/plain"}
|
| 216 |
+
|
| 217 |
+
try:
|
| 218 |
+
response = get_session().post("https://huggingface.co/api/validate-yaml", json=body, headers=headers)
|
| 219 |
+
hf_raise_for_status(response)
|
| 220 |
+
except HfHubHTTPError as exc:
|
| 221 |
+
if response.status_code == 400:
|
| 222 |
+
raise ValueError(response.text)
|
| 223 |
+
else:
|
| 224 |
+
raise exc
|
| 225 |
+
|
| 226 |
+
def push_to_hub(
|
| 227 |
+
self,
|
| 228 |
+
repo_id: str,
|
| 229 |
+
token: str | None = None,
|
| 230 |
+
repo_type: str | None = None,
|
| 231 |
+
commit_message: str | None = None,
|
| 232 |
+
commit_description: str | None = None,
|
| 233 |
+
revision: str | None = None,
|
| 234 |
+
create_pr: bool | None = None,
|
| 235 |
+
parent_commit: str | None = None,
|
| 236 |
+
):
|
| 237 |
+
"""Push a RepoCard to a Hugging Face Hub repo.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
repo_id (`str`):
|
| 241 |
+
The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food".
|
| 242 |
+
token (`str`, *optional*):
|
| 243 |
+
Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to
|
| 244 |
+
the stored token.
|
| 245 |
+
repo_type (`str`, *optional*, defaults to "model"):
|
| 246 |
+
The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this
|
| 247 |
+
function is called by a child class, it will default to the child class's `repo_type`.
|
| 248 |
+
commit_message (`str`, *optional*):
|
| 249 |
+
The summary / title / first line of the generated commit.
|
| 250 |
+
commit_description (`str`, *optional*)
|
| 251 |
+
The description of the generated commit.
|
| 252 |
+
revision (`str`, *optional*):
|
| 253 |
+
The git revision to commit from. Defaults to the head of the `"main"` branch.
|
| 254 |
+
create_pr (`bool`, *optional*):
|
| 255 |
+
Whether or not to create a Pull Request with this commit. Defaults to `False`.
|
| 256 |
+
parent_commit (`str`, *optional*):
|
| 257 |
+
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
|
| 258 |
+
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
|
| 259 |
+
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
|
| 260 |
+
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
|
| 261 |
+
especially useful if the repo is updated / committed too concurrently.
|
| 262 |
+
Returns:
|
| 263 |
+
`str`: URL of the commit which updated the card metadata.
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
# If repo type is provided, otherwise, use the repo type of the card.
|
| 267 |
+
repo_type = repo_type or self.repo_type
|
| 268 |
+
|
| 269 |
+
# Validate card before pushing to hub
|
| 270 |
+
self.validate(repo_type=repo_type)
|
| 271 |
+
|
| 272 |
+
with SoftTemporaryDirectory() as tmpdir:
|
| 273 |
+
tmp_path = Path(tmpdir) / constants.REPOCARD_NAME
|
| 274 |
+
tmp_path.write_text(str(self), encoding="utf-8")
|
| 275 |
+
url = upload_file(
|
| 276 |
+
path_or_fileobj=str(tmp_path),
|
| 277 |
+
path_in_repo=constants.REPOCARD_NAME,
|
| 278 |
+
repo_id=repo_id,
|
| 279 |
+
token=token,
|
| 280 |
+
repo_type=repo_type,
|
| 281 |
+
commit_message=commit_message,
|
| 282 |
+
commit_description=commit_description,
|
| 283 |
+
create_pr=create_pr,
|
| 284 |
+
revision=revision,
|
| 285 |
+
parent_commit=parent_commit,
|
| 286 |
+
)
|
| 287 |
+
return url
|
| 288 |
+
|
| 289 |
+
@classmethod
|
| 290 |
+
def from_template(
|
| 291 |
+
cls,
|
| 292 |
+
card_data: CardData,
|
| 293 |
+
template_path: str | None = None,
|
| 294 |
+
template_str: str | None = None,
|
| 295 |
+
**template_kwargs,
|
| 296 |
+
):
|
| 297 |
+
"""Initialize a RepoCard from a template. By default, it uses the default template.
|
| 298 |
+
|
| 299 |
+
Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
card_data (`huggingface_hub.CardData`):
|
| 303 |
+
A huggingface_hub.CardData instance containing the metadata you want to include in the YAML
|
| 304 |
+
header of the repo card on the Hugging Face Hub.
|
| 305 |
+
template_path (`str`, *optional*):
|
| 306 |
+
A path to a markdown file with optional Jinja template variables that can be filled
|
| 307 |
+
in with `template_kwargs`. Defaults to the default template.
|
| 308 |
+
|
| 309 |
+
Returns:
|
| 310 |
+
[`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the
|
| 311 |
+
template.
|
| 312 |
+
"""
|
| 313 |
+
if is_jinja_available():
|
| 314 |
+
import jinja2
|
| 315 |
+
else:
|
| 316 |
+
raise ImportError(
|
| 317 |
+
"Using RepoCard.from_template requires Jinja2 to be installed. Please"
|
| 318 |
+
" install it with `pip install Jinja2`."
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
kwargs = card_data.to_dict().copy()
|
| 322 |
+
kwargs.update(template_kwargs) # Template_kwargs have priority
|
| 323 |
+
|
| 324 |
+
if template_path is not None:
|
| 325 |
+
template_str = Path(template_path).read_text()
|
| 326 |
+
if template_str is None:
|
| 327 |
+
template_str = Path(cls.default_template_path).read_text()
|
| 328 |
+
template = jinja2.Template(template_str)
|
| 329 |
+
content = template.render(card_data=card_data.to_yaml(), **kwargs)
|
| 330 |
+
return cls(content)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class ModelCard(RepoCard):
|
| 334 |
+
card_data_class = ModelCardData # type: ignore[assignment]
|
| 335 |
+
default_template_path = TEMPLATE_MODELCARD_PATH
|
| 336 |
+
repo_type = "model"
|
| 337 |
+
|
| 338 |
+
@classmethod
|
| 339 |
+
def from_template( # type: ignore # violates Liskov property but easier to use
|
| 340 |
+
cls,
|
| 341 |
+
card_data: ModelCardData,
|
| 342 |
+
template_path: str | None = None,
|
| 343 |
+
template_str: str | None = None,
|
| 344 |
+
**template_kwargs,
|
| 345 |
+
):
|
| 346 |
+
"""Initialize a ModelCard from a template. By default, it uses the default template, which can be found here:
|
| 347 |
+
https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md
|
| 348 |
+
|
| 349 |
+
Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| 350 |
+
|
| 351 |
+
Args:
|
| 352 |
+
card_data (`huggingface_hub.ModelCardData`):
|
| 353 |
+
A huggingface_hub.ModelCardData instance containing the metadata you want to include in the YAML
|
| 354 |
+
header of the model card on the Hugging Face Hub.
|
| 355 |
+
template_path (`str`, *optional*):
|
| 356 |
+
A path to a markdown file with optional Jinja template variables that can be filled
|
| 357 |
+
in with `template_kwargs`. Defaults to the default template.
|
| 358 |
+
|
| 359 |
+
Returns:
|
| 360 |
+
[`huggingface_hub.ModelCard`]: A ModelCard instance with the specified card data and content from the
|
| 361 |
+
template.
|
| 362 |
+
|
| 363 |
+
Example:
|
| 364 |
+
```python
|
| 365 |
+
>>> from huggingface_hub import ModelCard, ModelCardData, EvalResult
|
| 366 |
+
|
| 367 |
+
>>> # Using the Default Template
|
| 368 |
+
>>> card_data = ModelCardData(
|
| 369 |
+
... language='en',
|
| 370 |
+
... license='mit',
|
| 371 |
+
... library_name='timm',
|
| 372 |
+
... tags=['image-classification', 'resnet'],
|
| 373 |
+
... datasets=['beans'],
|
| 374 |
+
... metrics=['accuracy'],
|
| 375 |
+
... )
|
| 376 |
+
>>> card = ModelCard.from_template(
|
| 377 |
+
... card_data,
|
| 378 |
+
... model_description='This model does x + y...'
|
| 379 |
+
... )
|
| 380 |
+
|
| 381 |
+
>>> # Including Evaluation Results
|
| 382 |
+
>>> card_data = ModelCardData(
|
| 383 |
+
... language='en',
|
| 384 |
+
... tags=['image-classification', 'resnet'],
|
| 385 |
+
... eval_results=[
|
| 386 |
+
... EvalResult(
|
| 387 |
+
... task_type='image-classification',
|
| 388 |
+
... dataset_type='beans',
|
| 389 |
+
... dataset_name='Beans',
|
| 390 |
+
... metric_type='accuracy',
|
| 391 |
+
... metric_value=0.9,
|
| 392 |
+
... ),
|
| 393 |
+
... ],
|
| 394 |
+
... model_name='my-cool-model',
|
| 395 |
+
... )
|
| 396 |
+
>>> card = ModelCard.from_template(card_data)
|
| 397 |
+
|
| 398 |
+
>>> # Using a Custom Template
|
| 399 |
+
>>> card_data = ModelCardData(
|
| 400 |
+
... language='en',
|
| 401 |
+
... tags=['image-classification', 'resnet']
|
| 402 |
+
... )
|
| 403 |
+
>>> card = ModelCard.from_template(
|
| 404 |
+
... card_data=card_data,
|
| 405 |
+
... template_path='./src/huggingface_hub/templates/modelcard_template.md',
|
| 406 |
+
... custom_template_var='custom value', # will be replaced in template if it exists
|
| 407 |
+
... )
|
| 408 |
+
|
| 409 |
+
```
|
| 410 |
+
"""
|
| 411 |
+
return super().from_template(card_data, template_path, template_str, **template_kwargs)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class DatasetCard(RepoCard):
|
| 415 |
+
card_data_class = DatasetCardData # type: ignore[assignment]
|
| 416 |
+
default_template_path = TEMPLATE_DATASETCARD_PATH
|
| 417 |
+
repo_type = "dataset"
|
| 418 |
+
|
| 419 |
+
@classmethod
|
| 420 |
+
def from_template( # type: ignore # violates Liskov property but easier to use
|
| 421 |
+
cls,
|
| 422 |
+
card_data: DatasetCardData,
|
| 423 |
+
template_path: str | None = None,
|
| 424 |
+
template_str: str | None = None,
|
| 425 |
+
**template_kwargs,
|
| 426 |
+
):
|
| 427 |
+
"""Initialize a DatasetCard from a template. By default, it uses the default template, which can be found here:
|
| 428 |
+
https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md
|
| 429 |
+
|
| 430 |
+
Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| 431 |
+
|
| 432 |
+
Args:
|
| 433 |
+
card_data (`huggingface_hub.DatasetCardData`):
|
| 434 |
+
A huggingface_hub.DatasetCardData instance containing the metadata you want to include in the YAML
|
| 435 |
+
header of the dataset card on the Hugging Face Hub.
|
| 436 |
+
template_path (`str`, *optional*):
|
| 437 |
+
A path to a markdown file with optional Jinja template variables that can be filled
|
| 438 |
+
in with `template_kwargs`. Defaults to the default template.
|
| 439 |
+
|
| 440 |
+
Returns:
|
| 441 |
+
[`huggingface_hub.DatasetCard`]: A DatasetCard instance with the specified card data and content from the
|
| 442 |
+
template.
|
| 443 |
+
|
| 444 |
+
Example:
|
| 445 |
+
```python
|
| 446 |
+
>>> from huggingface_hub import DatasetCard, DatasetCardData
|
| 447 |
+
|
| 448 |
+
>>> # Using the Default Template
|
| 449 |
+
>>> card_data = DatasetCardData(
|
| 450 |
+
... language='en',
|
| 451 |
+
... license='mit',
|
| 452 |
+
... annotations_creators='crowdsourced',
|
| 453 |
+
... task_categories=['text-classification'],
|
| 454 |
+
... task_ids=['sentiment-classification', 'text-scoring'],
|
| 455 |
+
... multilinguality='monolingual',
|
| 456 |
+
... pretty_name='My Text Classification Dataset',
|
| 457 |
+
... )
|
| 458 |
+
>>> card = DatasetCard.from_template(
|
| 459 |
+
... card_data,
|
| 460 |
+
... pretty_name=card_data.pretty_name,
|
| 461 |
+
... )
|
| 462 |
+
|
| 463 |
+
>>> # Using a Custom Template
|
| 464 |
+
>>> card_data = DatasetCardData(
|
| 465 |
+
... language='en',
|
| 466 |
+
... license='mit',
|
| 467 |
+
... )
|
| 468 |
+
>>> card = DatasetCard.from_template(
|
| 469 |
+
... card_data=card_data,
|
| 470 |
+
... template_path='./src/huggingface_hub/templates/datasetcard_template.md',
|
| 471 |
+
... custom_template_var='custom value', # will be replaced in template if it exists
|
| 472 |
+
... )
|
| 473 |
+
|
| 474 |
+
```
|
| 475 |
+
"""
|
| 476 |
+
return super().from_template(card_data, template_path, template_str, **template_kwargs)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
class SpaceCard(RepoCard):
|
| 480 |
+
card_data_class = SpaceCardData # type: ignore[assignment]
|
| 481 |
+
default_template_path = TEMPLATE_MODELCARD_PATH
|
| 482 |
+
repo_type = "space"
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _detect_line_ending(content: str) -> Literal["\r", "\n", "\r\n", None]: # noqa: F722
|
| 486 |
+
"""Detect the line ending of a string. Used by RepoCard to avoid making huge diff on newlines.
|
| 487 |
+
|
| 488 |
+
Uses same implementation as in Hub server, keep it in sync.
|
| 489 |
+
|
| 490 |
+
Returns:
|
| 491 |
+
str: The detected line ending of the string.
|
| 492 |
+
"""
|
| 493 |
+
cr = content.count("\r")
|
| 494 |
+
lf = content.count("\n")
|
| 495 |
+
crlf = content.count("\r\n")
|
| 496 |
+
if cr + lf == 0:
|
| 497 |
+
return None
|
| 498 |
+
if crlf == cr and crlf == lf:
|
| 499 |
+
return "\r\n"
|
| 500 |
+
if cr > lf:
|
| 501 |
+
return "\r"
|
| 502 |
+
else:
|
| 503 |
+
return "\n"
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def metadata_load(local_path: str | Path) -> dict | None:
|
| 507 |
+
content = Path(local_path).read_text()
|
| 508 |
+
match = REGEX_YAML_BLOCK.search(content)
|
| 509 |
+
if match:
|
| 510 |
+
yaml_block = match.group(2)
|
| 511 |
+
data = yaml.safe_load(yaml_block)
|
| 512 |
+
if data is None or isinstance(data, dict):
|
| 513 |
+
return data
|
| 514 |
+
raise ValueError("repo card metadata block should be a dict")
|
| 515 |
+
else:
|
| 516 |
+
return None
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def metadata_save(local_path: str | Path, data: dict) -> None:
|
| 520 |
+
"""
|
| 521 |
+
Save the metadata dict in the upper YAML part Trying to preserve newlines as
|
| 522 |
+
in the existing file. Docs about open() with newline="" parameter:
|
| 523 |
+
https://docs.python.org/3/library/functions.html?highlight=open#open Does
|
| 524 |
+
not work with "^M" linebreaks, which are replaced by \n
|
| 525 |
+
"""
|
| 526 |
+
line_break = "\n"
|
| 527 |
+
content = ""
|
| 528 |
+
# try to detect existing newline character
|
| 529 |
+
if os.path.exists(local_path):
|
| 530 |
+
with open(local_path, newline="", encoding="utf8") as readme:
|
| 531 |
+
content = readme.read()
|
| 532 |
+
if isinstance(readme.newlines, tuple):
|
| 533 |
+
line_break = readme.newlines[0]
|
| 534 |
+
elif isinstance(readme.newlines, str):
|
| 535 |
+
line_break = readme.newlines
|
| 536 |
+
|
| 537 |
+
# creates a new file if it not
|
| 538 |
+
with open(local_path, "w", newline="", encoding="utf8") as readme:
|
| 539 |
+
data_yaml = yaml_dump(data, sort_keys=False, line_break=line_break)
|
| 540 |
+
# sort_keys: keep dict order
|
| 541 |
+
match = REGEX_YAML_BLOCK.search(content)
|
| 542 |
+
if match:
|
| 543 |
+
output = content[: match.start()] + f"---{line_break}{data_yaml}---{line_break}" + content[match.end() :]
|
| 544 |
+
else:
|
| 545 |
+
output = f"---{line_break}{data_yaml}---{line_break}{content}"
|
| 546 |
+
|
| 547 |
+
readme.write(output)
|
| 548 |
+
readme.close()
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def metadata_eval_result(
|
| 552 |
+
*,
|
| 553 |
+
model_pretty_name: str,
|
| 554 |
+
task_pretty_name: str,
|
| 555 |
+
task_id: str,
|
| 556 |
+
metrics_pretty_name: str,
|
| 557 |
+
metrics_id: str,
|
| 558 |
+
metrics_value: Any,
|
| 559 |
+
dataset_pretty_name: str,
|
| 560 |
+
dataset_id: str,
|
| 561 |
+
metrics_config: str | None = None,
|
| 562 |
+
metrics_verified: bool = False,
|
| 563 |
+
dataset_config: str | None = None,
|
| 564 |
+
dataset_split: str | None = None,
|
| 565 |
+
dataset_revision: str | None = None,
|
| 566 |
+
metrics_verification_token: str | None = None,
|
| 567 |
+
) -> dict:
|
| 568 |
+
"""
|
| 569 |
+
Creates a metadata dict with the result from a model evaluated on a dataset.
|
| 570 |
+
|
| 571 |
+
Args:
|
| 572 |
+
model_pretty_name (`str`):
|
| 573 |
+
The name of the model in natural language.
|
| 574 |
+
task_pretty_name (`str`):
|
| 575 |
+
The name of a task in natural language.
|
| 576 |
+
task_id (`str`):
|
| 577 |
+
Example: automatic-speech-recognition. A task id.
|
| 578 |
+
metrics_pretty_name (`str`):
|
| 579 |
+
A name for the metric in natural language. Example: Test WER.
|
| 580 |
+
metrics_id (`str`):
|
| 581 |
+
Example: wer. A metric id from https://hf.co/metrics.
|
| 582 |
+
metrics_value (`Any`):
|
| 583 |
+
The value from the metric. Example: 20.0 or "20.0 ± 1.2".
|
| 584 |
+
dataset_pretty_name (`str`):
|
| 585 |
+
The name of the dataset in natural language.
|
| 586 |
+
dataset_id (`str`):
|
| 587 |
+
Example: common_voice. A dataset id from https://hf.co/datasets.
|
| 588 |
+
metrics_config (`str`, *optional*):
|
| 589 |
+
The name of the metric configuration used in `load_metric()`.
|
| 590 |
+
Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
|
| 591 |
+
metrics_verified (`bool`, *optional*, defaults to `False`):
|
| 592 |
+
Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
|
| 593 |
+
dataset_config (`str`, *optional*):
|
| 594 |
+
Example: fr. The name of the dataset configuration used in `load_dataset()`.
|
| 595 |
+
dataset_split (`str`, *optional*):
|
| 596 |
+
Example: test. The name of the dataset split used in `load_dataset()`.
|
| 597 |
+
dataset_revision (`str`, *optional*):
|
| 598 |
+
Example: 5503434ddd753f426f4b38109466949a1217c2bb. The name of the dataset dataset revision
|
| 599 |
+
used in `load_dataset()`.
|
| 600 |
+
metrics_verification_token (`bool`, *optional*):
|
| 601 |
+
A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
|
| 602 |
+
|
| 603 |
+
Returns:
|
| 604 |
+
`dict`: a metadata dict with the result from a model evaluated on a dataset.
|
| 605 |
+
|
| 606 |
+
Example:
|
| 607 |
+
```python
|
| 608 |
+
>>> from huggingface_hub import metadata_eval_result
|
| 609 |
+
>>> results = metadata_eval_result(
|
| 610 |
+
... model_pretty_name="RoBERTa fine-tuned on ReactionGIF",
|
| 611 |
+
... task_pretty_name="Text Classification",
|
| 612 |
+
... task_id="text-classification",
|
| 613 |
+
... metrics_pretty_name="Accuracy",
|
| 614 |
+
... metrics_id="accuracy",
|
| 615 |
+
... metrics_value=0.2662102282047272,
|
| 616 |
+
... dataset_pretty_name="ReactionJPEG",
|
| 617 |
+
... dataset_id="julien-c/reactionjpeg",
|
| 618 |
+
... dataset_config="default",
|
| 619 |
+
... dataset_split="test",
|
| 620 |
+
... )
|
| 621 |
+
>>> results == {
|
| 622 |
+
... 'model-index': [
|
| 623 |
+
... {
|
| 624 |
+
... 'name': 'RoBERTa fine-tuned on ReactionGIF',
|
| 625 |
+
... 'results': [
|
| 626 |
+
... {
|
| 627 |
+
... 'task': {
|
| 628 |
+
... 'type': 'text-classification',
|
| 629 |
+
... 'name': 'Text Classification'
|
| 630 |
+
... },
|
| 631 |
+
... 'dataset': {
|
| 632 |
+
... 'name': 'ReactionJPEG',
|
| 633 |
+
... 'type': 'julien-c/reactionjpeg',
|
| 634 |
+
... 'config': 'default',
|
| 635 |
+
... 'split': 'test'
|
| 636 |
+
... },
|
| 637 |
+
... 'metrics': [
|
| 638 |
+
... {
|
| 639 |
+
... 'type': 'accuracy',
|
| 640 |
+
... 'value': 0.2662102282047272,
|
| 641 |
+
... 'name': 'Accuracy',
|
| 642 |
+
... 'verified': False
|
| 643 |
+
... }
|
| 644 |
+
... ]
|
| 645 |
+
... }
|
| 646 |
+
... ]
|
| 647 |
+
... }
|
| 648 |
+
... ]
|
| 649 |
+
... }
|
| 650 |
+
True
|
| 651 |
+
|
| 652 |
+
```
|
| 653 |
+
"""
|
| 654 |
+
|
| 655 |
+
return {
|
| 656 |
+
"model-index": eval_results_to_model_index(
|
| 657 |
+
model_name=model_pretty_name,
|
| 658 |
+
eval_results=[
|
| 659 |
+
EvalResult(
|
| 660 |
+
task_name=task_pretty_name,
|
| 661 |
+
task_type=task_id,
|
| 662 |
+
metric_name=metrics_pretty_name,
|
| 663 |
+
metric_type=metrics_id,
|
| 664 |
+
metric_value=metrics_value,
|
| 665 |
+
dataset_name=dataset_pretty_name,
|
| 666 |
+
dataset_type=dataset_id,
|
| 667 |
+
metric_config=metrics_config,
|
| 668 |
+
verified=metrics_verified,
|
| 669 |
+
verify_token=metrics_verification_token,
|
| 670 |
+
dataset_config=dataset_config,
|
| 671 |
+
dataset_split=dataset_split,
|
| 672 |
+
dataset_revision=dataset_revision,
|
| 673 |
+
)
|
| 674 |
+
],
|
| 675 |
+
)
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
@validate_hf_hub_args
|
| 680 |
+
def metadata_update(
|
| 681 |
+
repo_id: str,
|
| 682 |
+
metadata: dict,
|
| 683 |
+
*,
|
| 684 |
+
repo_type: str | None = None,
|
| 685 |
+
overwrite: bool = False,
|
| 686 |
+
token: str | None = None,
|
| 687 |
+
commit_message: str | None = None,
|
| 688 |
+
commit_description: str | None = None,
|
| 689 |
+
revision: str | None = None,
|
| 690 |
+
create_pr: bool = False,
|
| 691 |
+
parent_commit: str | None = None,
|
| 692 |
+
) -> str:
|
| 693 |
+
"""
|
| 694 |
+
Updates the metadata in the README.md of a repository on the Hugging Face Hub.
|
| 695 |
+
If the README.md file doesn't exist yet, a new one is created with metadata and
|
| 696 |
+
the default ModelCard or DatasetCard template. For `space` repo, an error is thrown
|
| 697 |
+
as a Space cannot exist without a `README.md` file.
|
| 698 |
+
|
| 699 |
+
Args:
|
| 700 |
+
repo_id (`str`):
|
| 701 |
+
The name of the repository.
|
| 702 |
+
metadata (`dict`):
|
| 703 |
+
A dictionary containing the metadata to be updated.
|
| 704 |
+
repo_type (`str`, *optional*):
|
| 705 |
+
Set to `"dataset"` or `"space"` if updating to a dataset or space,
|
| 706 |
+
`None` or `"model"` if updating to a model. Default is `None`.
|
| 707 |
+
overwrite (`bool`, *optional*, defaults to `False`):
|
| 708 |
+
If set to `True` an existing field can be overwritten, otherwise
|
| 709 |
+
attempting to overwrite an existing field will cause an error.
|
| 710 |
+
token (`str`, *optional*):
|
| 711 |
+
The Hugging Face authentication token.
|
| 712 |
+
commit_message (`str`, *optional*):
|
| 713 |
+
The summary / title / first line of the generated commit. Defaults to
|
| 714 |
+
`f"Update metadata with huggingface_hub"`
|
| 715 |
+
commit_description (`str` *optional*)
|
| 716 |
+
The description of the generated commit
|
| 717 |
+
revision (`str`, *optional*):
|
| 718 |
+
The git revision to commit from. Defaults to the head of the
|
| 719 |
+
`"main"` branch.
|
| 720 |
+
create_pr (`boolean`, *optional*):
|
| 721 |
+
Whether or not to create a Pull Request from `revision` with that commit.
|
| 722 |
+
Defaults to `False`.
|
| 723 |
+
parent_commit (`str`, *optional*):
|
| 724 |
+
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
|
| 725 |
+
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
|
| 726 |
+
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
|
| 727 |
+
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
|
| 728 |
+
especially useful if the repo is updated / committed too concurrently.
|
| 729 |
+
Returns:
|
| 730 |
+
`str`: URL of the commit which updated the card metadata.
|
| 731 |
+
|
| 732 |
+
Example:
|
| 733 |
+
```python
|
| 734 |
+
>>> from huggingface_hub import metadata_update
|
| 735 |
+
>>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF',
|
| 736 |
+
... 'results': [{'dataset': {'name': 'ReactionGIF',
|
| 737 |
+
... 'type': 'julien-c/reactiongif'},
|
| 738 |
+
... 'metrics': [{'name': 'Recall',
|
| 739 |
+
... 'type': 'recall',
|
| 740 |
+
... 'value': 0.7762102282047272}],
|
| 741 |
+
... 'task': {'name': 'Text Classification',
|
| 742 |
+
... 'type': 'text-classification'}}]}]}
|
| 743 |
+
>>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata)
|
| 744 |
+
|
| 745 |
+
```
|
| 746 |
+
"""
|
| 747 |
+
commit_message = commit_message if commit_message is not None else "Update metadata with huggingface_hub"
|
| 748 |
+
|
| 749 |
+
# Card class given repo_type
|
| 750 |
+
card_class: type[RepoCard]
|
| 751 |
+
if repo_type is None or repo_type == "model":
|
| 752 |
+
card_class = ModelCard
|
| 753 |
+
elif repo_type == "dataset":
|
| 754 |
+
card_class = DatasetCard
|
| 755 |
+
elif repo_type == "space":
|
| 756 |
+
card_class = RepoCard
|
| 757 |
+
else:
|
| 758 |
+
raise ValueError(f"Unknown repo_type: {repo_type}")
|
| 759 |
+
|
| 760 |
+
# Either load repo_card from the Hub or create an empty one.
|
| 761 |
+
# NOTE: Will not create the repo if it doesn't exist.
|
| 762 |
+
try:
|
| 763 |
+
card = card_class.load(repo_id, token=token, repo_type=repo_type)
|
| 764 |
+
except EntryNotFoundError:
|
| 765 |
+
if repo_type == "space":
|
| 766 |
+
raise ValueError("Cannot update metadata on a Space that doesn't contain a `README.md` file.")
|
| 767 |
+
|
| 768 |
+
# Initialize a ModelCard or DatasetCard from default template and no data.
|
| 769 |
+
# Cast to the concrete expected card type to satisfy type checkers.
|
| 770 |
+
card = card_class.from_template(CardData()) # type: ignore
|
| 771 |
+
|
| 772 |
+
for key, value in metadata.items():
|
| 773 |
+
if key == "model-index":
|
| 774 |
+
# if the new metadata doesn't include a name, either use existing one or repo name
|
| 775 |
+
if "name" not in value[0]:
|
| 776 |
+
value[0]["name"] = getattr(card, "model_name", repo_id)
|
| 777 |
+
model_name, new_results = model_index_to_eval_results(value)
|
| 778 |
+
if card.data.eval_results is None:
|
| 779 |
+
card.data.eval_results = new_results
|
| 780 |
+
card.data.model_name = model_name
|
| 781 |
+
else:
|
| 782 |
+
existing_results = card.data.eval_results
|
| 783 |
+
|
| 784 |
+
# Iterate over new results
|
| 785 |
+
# Iterate over existing results
|
| 786 |
+
# If both results describe the same metric but value is different:
|
| 787 |
+
# If overwrite=True: overwrite the metric value
|
| 788 |
+
# Else: raise ValueError
|
| 789 |
+
# Else: append new result to existing ones.
|
| 790 |
+
for new_result in new_results:
|
| 791 |
+
result_found = False
|
| 792 |
+
for existing_result in existing_results:
|
| 793 |
+
if new_result.is_equal_except_value(existing_result):
|
| 794 |
+
if new_result != existing_result and not overwrite:
|
| 795 |
+
raise ValueError(
|
| 796 |
+
"You passed a new value for the existing metric"
|
| 797 |
+
f" 'name: {new_result.metric_name}, type: "
|
| 798 |
+
f"{new_result.metric_type}'. Set `overwrite=True`"
|
| 799 |
+
" to overwrite existing metrics."
|
| 800 |
+
)
|
| 801 |
+
result_found = True
|
| 802 |
+
existing_result.metric_value = new_result.metric_value
|
| 803 |
+
if existing_result.verified is True:
|
| 804 |
+
existing_result.verify_token = new_result.verify_token
|
| 805 |
+
if not result_found:
|
| 806 |
+
card.data.eval_results.append(new_result)
|
| 807 |
+
else:
|
| 808 |
+
# Any metadata that is not a result metric
|
| 809 |
+
if card.data.get(key) is not None and not overwrite and card.data.get(key) != value:
|
| 810 |
+
raise ValueError(
|
| 811 |
+
f"You passed a new value for the existing meta data field '{key}'."
|
| 812 |
+
" Set `overwrite=True` to overwrite existing metadata."
|
| 813 |
+
)
|
| 814 |
+
else:
|
| 815 |
+
card.data[key] = value
|
| 816 |
+
|
| 817 |
+
return card.push_to_hub(
|
| 818 |
+
repo_id,
|
| 819 |
+
token=token,
|
| 820 |
+
repo_type=repo_type,
|
| 821 |
+
commit_message=commit_message,
|
| 822 |
+
commit_description=commit_description,
|
| 823 |
+
create_pr=create_pr,
|
| 824 |
+
revision=revision,
|
| 825 |
+
parent_commit=parent_commit,
|
| 826 |
+
)
|
.cache/uv/archive-v0/P-PwjYKODLBSqbgWC3J1N/huggingface_hub/repocard_data.py
ADDED
|
@@ -0,0 +1,770 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from huggingface_hub.utils import logging, yaml_dump
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
logger = logging.get_logger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass
|
| 13 |
+
class EvalResult:
|
| 14 |
+
"""
|
| 15 |
+
Flattened representation of individual evaluation results found in model-index of Model Cards.
|
| 16 |
+
|
| 17 |
+
For more information on the model-index spec, see https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
task_type (`str`):
|
| 21 |
+
The task identifier. Example: "image-classification".
|
| 22 |
+
dataset_type (`str`):
|
| 23 |
+
The dataset identifier. Example: "common_voice". Use dataset id from https://hf.co/datasets.
|
| 24 |
+
dataset_name (`str`):
|
| 25 |
+
A pretty name for the dataset. Example: "Common Voice (French)".
|
| 26 |
+
metric_type (`str`):
|
| 27 |
+
The metric identifier. Example: "wer". Use metric id from https://hf.co/metrics.
|
| 28 |
+
metric_value (`Any`):
|
| 29 |
+
The metric value. Example: 0.9 or "20.0 ± 1.2".
|
| 30 |
+
task_name (`str`, *optional*):
|
| 31 |
+
A pretty name for the task. Example: "Speech Recognition".
|
| 32 |
+
dataset_config (`str`, *optional*):
|
| 33 |
+
The name of the dataset configuration used in `load_dataset()`.
|
| 34 |
+
Example: fr in `load_dataset("common_voice", "fr")`. See the `datasets` docs for more info:
|
| 35 |
+
https://hf.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name
|
| 36 |
+
dataset_split (`str`, *optional*):
|
| 37 |
+
The split used in `load_dataset()`. Example: "test".
|
| 38 |
+
dataset_revision (`str`, *optional*):
|
| 39 |
+
The revision (AKA Git Sha) of the dataset used in `load_dataset()`.
|
| 40 |
+
Example: 5503434ddd753f426f4b38109466949a1217c2bb
|
| 41 |
+
dataset_args (`dict[str, Any]`, *optional*):
|
| 42 |
+
The arguments passed during `Metric.compute()`. Example for `bleu`: `{"max_order": 4}`
|
| 43 |
+
metric_name (`str`, *optional*):
|
| 44 |
+
A pretty name for the metric. Example: "Test WER".
|
| 45 |
+
metric_config (`str`, *optional*):
|
| 46 |
+
The name of the metric configuration used in `load_metric()`.
|
| 47 |
+
Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
|
| 48 |
+
See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations
|
| 49 |
+
metric_args (`dict[str, Any]`, *optional*):
|
| 50 |
+
The arguments passed during `Metric.compute()`. Example for `bleu`: max_order: 4
|
| 51 |
+
verified (`bool`, *optional*):
|
| 52 |
+
Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
|
| 53 |
+
verify_token (`str`, *optional*):
|
| 54 |
+
A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
|
| 55 |
+
source_name (`str`, *optional*):
|
| 56 |
+
The name of the source of the evaluation result. Example: "Open LLM Leaderboard".
|
| 57 |
+
source_url (`str`, *optional*):
|
| 58 |
+
The URL of the source of the evaluation result. Example: "https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard".
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
# Required
|
| 62 |
+
|
| 63 |
+
# The task identifier
|
| 64 |
+
# Example: automatic-speech-recognition
|
| 65 |
+
task_type: str
|
| 66 |
+
|
| 67 |
+
# The dataset identifier
|
| 68 |
+
# Example: common_voice. Use dataset id from https://hf.co/datasets
|
| 69 |
+
dataset_type: str
|
| 70 |
+
|
| 71 |
+
# A pretty name for the dataset.
|
| 72 |
+
# Example: Common Voice (French)
|
| 73 |
+
dataset_name: str
|
| 74 |
+
|
| 75 |
+
# The metric identifier
|
| 76 |
+
# Example: wer. Use metric id from https://hf.co/metrics
|
| 77 |
+
metric_type: str
|
| 78 |
+
|
| 79 |
+
# Value of the metric.
|
| 80 |
+
# Example: 20.0 or "20.0 ± 1.2"
|
| 81 |
+
metric_value: Any
|
| 82 |
+
|
| 83 |
+
# Optional
|
| 84 |
+
|
| 85 |
+
# A pretty name for the task.
|
| 86 |
+
# Example: Speech Recognition
|
| 87 |
+
task_name: str | None = None
|
| 88 |
+
|
| 89 |
+
# The name of the dataset configuration used in `load_dataset()`.
|
| 90 |
+
# Example: fr in `load_dataset("common_voice", "fr")`.
|
| 91 |
+
# See the `datasets` docs for more info:
|
| 92 |
+
# https://huggingface.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name
|
| 93 |
+
dataset_config: str | None = None
|
| 94 |
+
|
| 95 |
+
# The split used in `load_dataset()`.
|
| 96 |
+
# Example: test
|
| 97 |
+
dataset_split: str | None = None
|
| 98 |
+
|
| 99 |
+
# The revision (AKA Git Sha) of the dataset used in `load_dataset()`.
|
| 100 |
+
# Example: 5503434ddd753f426f4b38109466949a1217c2bb
|
| 101 |
+
dataset_revision: str | None = None
|
| 102 |
+
|
| 103 |
+
# The arguments passed during `Metric.compute()`.
|
| 104 |
+
# Example for `bleu`: max_order: 4
|
| 105 |
+
dataset_args: dict[str, Any] | None = None
|
| 106 |
+
|
| 107 |
+
# A pretty name for the metric.
|
| 108 |
+
# Example: Test WER
|
| 109 |
+
metric_name: str | None = None
|
| 110 |
+
|
| 111 |
+
# The name of the metric configuration used in `load_metric()`.
|
| 112 |
+
# Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
|
| 113 |
+
# See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations
|
| 114 |
+
metric_config: str | None = None
|
| 115 |
+
|
| 116 |
+
# The arguments passed during `Metric.compute()`.
|
| 117 |
+
# Example for `bleu`: max_order: 4
|
| 118 |
+
metric_args: dict[str, Any] | None = None
|
| 119 |
+
|
| 120 |
+
# Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
|
| 121 |
+
verified: bool | None = None
|
| 122 |
+
|
| 123 |
+
# A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
|
| 124 |
+
verify_token: str | None = None
|
| 125 |
+
|
| 126 |
+
# The name of the source of the evaluation result.
|
| 127 |
+
# Example: Open LLM Leaderboard
|
| 128 |
+
source_name: str | None = None
|
| 129 |
+
|
| 130 |
+
# The URL of the source of the evaluation result.
|
| 131 |
+
# Example: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard
|
| 132 |
+
source_url: str | None = None
|
| 133 |
+
|
| 134 |
+
@property
|
| 135 |
+
def unique_identifier(self) -> tuple:
|
| 136 |
+
"""Returns a tuple that uniquely identifies this evaluation."""
|
| 137 |
+
return (
|
| 138 |
+
self.task_type,
|
| 139 |
+
self.dataset_type,
|
| 140 |
+
self.dataset_config,
|
| 141 |
+
self.dataset_split,
|
| 142 |
+
self.dataset_revision,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def is_equal_except_value(self, other: "EvalResult") -> bool:
|
| 146 |
+
"""
|
| 147 |
+
Return True if `self` and `other` describe exactly the same metric but with a
|
| 148 |
+
different value.
|
| 149 |
+
"""
|
| 150 |
+
for key, _ in self.__dict__.items():
|
| 151 |
+
if key == "metric_value":
|
| 152 |
+
continue
|
| 153 |
+
# For metrics computed by Hugging Face's evaluation service, `verify_token` is derived from `metric_value`,
|
| 154 |
+
# so we exclude it here in the comparison.
|
| 155 |
+
if key != "verify_token" and getattr(self, key) != getattr(other, key):
|
| 156 |
+
return False
|
| 157 |
+
return True
|
| 158 |
+
|
| 159 |
+
def __post_init__(self) -> None:
|
| 160 |
+
if self.source_name is not None and self.source_url is None:
|
| 161 |
+
raise ValueError("If `source_name` is provided, `source_url` must also be provided.")
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@dataclass
|
| 165 |
+
class CardData:
|
| 166 |
+
"""Structure containing metadata from a RepoCard.
|
| 167 |
+
|
| 168 |
+
[`CardData`] is the parent class of [`ModelCardData`] and [`DatasetCardData`].
|
| 169 |
+
|
| 170 |
+
Metadata can be exported as a dictionary or YAML. Export can be customized to alter the representation of the data
|
| 171 |
+
(example: flatten evaluation results). `CardData` behaves as a dictionary (can get, pop, set values) but do not
|
| 172 |
+
inherit from `dict` to allow this export step.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
def __init__(self, ignore_metadata_errors: bool = False, **kwargs):
|
| 176 |
+
self.__dict__.update(kwargs)
|
| 177 |
+
|
| 178 |
+
def to_dict(self):
|
| 179 |
+
"""Converts CardData to a dict.
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
`dict`: CardData represented as a dictionary ready to be dumped to a YAML
|
| 183 |
+
block for inclusion in a README.md file.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
data_dict = copy.deepcopy(self.__dict__)
|
| 187 |
+
self._to_dict(data_dict)
|
| 188 |
+
return {key: value for key, value in data_dict.items() if value is not None}
|
| 189 |
+
|
| 190 |
+
def _to_dict(self, data_dict):
|
| 191 |
+
"""Use this method in child classes to alter the dict representation of the data. Alter the dict in-place.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
data_dict (`dict`): The raw dict representation of the card data.
|
| 195 |
+
"""
|
| 196 |
+
pass
|
| 197 |
+
|
| 198 |
+
def to_yaml(self, line_break=None, original_order: list[str] | None = None) -> str:
|
| 199 |
+
"""Dumps CardData to a YAML block for inclusion in a README.md file.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
line_break (str, *optional*):
|
| 203 |
+
The line break to use when dumping to yaml.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
`str`: CardData represented as a YAML block.
|
| 207 |
+
"""
|
| 208 |
+
if original_order:
|
| 209 |
+
self.__dict__ = {
|
| 210 |
+
k: self.__dict__[k]
|
| 211 |
+
for k in original_order + list(set(self.__dict__.keys()) - set(original_order))
|
| 212 |
+
if k in self.__dict__
|
| 213 |
+
}
|
| 214 |
+
return yaml_dump(self.to_dict(), sort_keys=False, line_break=line_break).strip()
|
| 215 |
+
|
| 216 |
+
def __repr__(self):
|
| 217 |
+
return repr(self.__dict__)
|
| 218 |
+
|
| 219 |
+
def __str__(self):
|
| 220 |
+
return self.to_yaml()
|
| 221 |
+
|
| 222 |
+
def get(self, key: str, default: Any = None) -> Any:
|
| 223 |
+
"""Get value for a given metadata key."""
|
| 224 |
+
value = self.__dict__.get(key)
|
| 225 |
+
return default if value is None else value
|
| 226 |
+
|
| 227 |
+
def pop(self, key: str, default: Any = None) -> Any:
|
| 228 |
+
"""Pop value for a given metadata key."""
|
| 229 |
+
return self.__dict__.pop(key, default)
|
| 230 |
+
|
| 231 |
+
def __getitem__(self, key: str) -> Any:
|
| 232 |
+
"""Get value for a given metadata key."""
|
| 233 |
+
return self.__dict__[key]
|
| 234 |
+
|
| 235 |
+
def __setitem__(self, key: str, value: Any) -> None:
|
| 236 |
+
"""Set value for a given metadata key."""
|
| 237 |
+
self.__dict__[key] = value
|
| 238 |
+
|
| 239 |
+
def __contains__(self, key: str) -> bool:
|
| 240 |
+
"""Check if a given metadata key is set."""
|
| 241 |
+
return key in self.__dict__
|
| 242 |
+
|
| 243 |
+
def __len__(self) -> int:
|
| 244 |
+
"""Return the number of metadata keys set."""
|
| 245 |
+
return len(self.__dict__)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _validate_eval_results(
|
| 249 |
+
eval_results: EvalResult | list[EvalResult] | None,
|
| 250 |
+
model_name: str | None,
|
| 251 |
+
) -> list[EvalResult]:
|
| 252 |
+
if eval_results is None:
|
| 253 |
+
return []
|
| 254 |
+
if isinstance(eval_results, EvalResult):
|
| 255 |
+
eval_results = [eval_results]
|
| 256 |
+
if not isinstance(eval_results, list) or not all(isinstance(r, EvalResult) for r in eval_results):
|
| 257 |
+
raise ValueError(
|
| 258 |
+
f"`eval_results` should be of type `EvalResult` or a list of `EvalResult`, got {type(eval_results)}."
|
| 259 |
+
)
|
| 260 |
+
if model_name is None:
|
| 261 |
+
raise ValueError("Passing `eval_results` requires `model_name` to be set.")
|
| 262 |
+
return eval_results
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class ModelCardData(CardData):
|
| 266 |
+
"""Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
base_model (`str` or `list[str]`, *optional*):
|
| 270 |
+
The identifier of the base model from which the model derives. This is applicable for example if your model is a
|
| 271 |
+
fine-tune or adapter of an existing model. The value must be the ID of a model on the Hub (or a list of IDs
|
| 272 |
+
if your model derives from multiple models). Defaults to None.
|
| 273 |
+
datasets (`Union[str, list[str]]`, *optional*):
|
| 274 |
+
Dataset or list of datasets that were used to train this model. Should be a dataset ID
|
| 275 |
+
found on https://hf.co/datasets. Defaults to None.
|
| 276 |
+
eval_results (`Union[list[EvalResult], EvalResult]`, *optional*):
|
| 277 |
+
List of `huggingface_hub.EvalResult` that define evaluation results of the model. If provided,
|
| 278 |
+
`model_name` is used to as a name on PapersWithCode's leaderboards. Defaults to `None`.
|
| 279 |
+
language (`Union[str, list[str]]`, *optional*):
|
| 280 |
+
Language of model's training data or metadata. It must be an ISO 639-1, 639-2 or
|
| 281 |
+
639-3 code (two/three letters), or a special value like "code", "multilingual". Defaults to `None`.
|
| 282 |
+
library_name (`str`, *optional*):
|
| 283 |
+
Name of library used by this model. Example: keras or any library from
|
| 284 |
+
https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts.
|
| 285 |
+
Defaults to None.
|
| 286 |
+
license (`str`, *optional*):
|
| 287 |
+
License of this model. Example: apache-2.0 or any license from
|
| 288 |
+
https://huggingface.co/docs/hub/repositories-licenses. Defaults to None.
|
| 289 |
+
license_name (`str`, *optional*):
|
| 290 |
+
Name of the license of this model. Defaults to None. To be used in conjunction with `license_link`.
|
| 291 |
+
Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a name. In that case, use `license` instead.
|
| 292 |
+
license_link (`str`, *optional*):
|
| 293 |
+
Link to the license of this model. Defaults to None. To be used in conjunction with `license_name`.
|
| 294 |
+
Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a link. In that case, use `license` instead.
|
| 295 |
+
metrics (`list[str]`, *optional*):
|
| 296 |
+
List of metrics used to evaluate this model. Should be a metric name that can be found
|
| 297 |
+
at https://hf.co/metrics. Example: 'accuracy'. Defaults to None.
|
| 298 |
+
model_name (`str`, *optional*):
|
| 299 |
+
A name for this model. It is used along with
|
| 300 |
+
`eval_results` to construct the `model-index` within the card's metadata. The name
|
| 301 |
+
you supply here is what will be used on PapersWithCode's leaderboards. If None is provided
|
| 302 |
+
then the repo name is used as a default. Defaults to None.
|
| 303 |
+
pipeline_tag (`str`, *optional*):
|
| 304 |
+
The pipeline tag associated with the model. Example: "text-classification".
|
| 305 |
+
tags (`list[str]`, *optional*):
|
| 306 |
+
List of tags to add to your model that can be used when filtering on the Hugging
|
| 307 |
+
Face Hub. Defaults to None.
|
| 308 |
+
ignore_metadata_errors (`str`):
|
| 309 |
+
If True, errors while parsing the metadata section will be ignored. Some information might be lost during
|
| 310 |
+
the process. Use it at your own risk.
|
| 311 |
+
kwargs (`dict`, *optional*):
|
| 312 |
+
Additional metadata that will be added to the model card. Defaults to None.
|
| 313 |
+
|
| 314 |
+
Example:
|
| 315 |
+
```python
|
| 316 |
+
>>> from huggingface_hub import ModelCardData
|
| 317 |
+
>>> card_data = ModelCardData(
|
| 318 |
+
... language="en",
|
| 319 |
+
... license="mit",
|
| 320 |
+
... library_name="timm",
|
| 321 |
+
... tags=['image-classification', 'resnet'],
|
| 322 |
+
... )
|
| 323 |
+
>>> card_data.to_dict()
|
| 324 |
+
{'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']}
|
| 325 |
+
|
| 326 |
+
```
|
| 327 |
+
"""
|
| 328 |
+
|
| 329 |
+
def __init__(
|
| 330 |
+
self,
|
| 331 |
+
*,
|
| 332 |
+
base_model: str | list[str] | None = None,
|
| 333 |
+
datasets: str | list[str] | None = None,
|
| 334 |
+
eval_results: list[EvalResult] | None = None,
|
| 335 |
+
language: str | list[str] | None = None,
|
| 336 |
+
library_name: str | None = None,
|
| 337 |
+
license: str | None = None,
|
| 338 |
+
license_name: str | None = None,
|
| 339 |
+
license_link: str | None = None,
|
| 340 |
+
metrics: list[str] | None = None,
|
| 341 |
+
model_name: str | None = None,
|
| 342 |
+
pipeline_tag: str | None = None,
|
| 343 |
+
tags: list[str] | None = None,
|
| 344 |
+
ignore_metadata_errors: bool = False,
|
| 345 |
+
**kwargs,
|
| 346 |
+
):
|
| 347 |
+
self.base_model = base_model
|
| 348 |
+
self.datasets = datasets
|
| 349 |
+
self.eval_results = eval_results
|
| 350 |
+
self.language = language
|
| 351 |
+
self.library_name = library_name
|
| 352 |
+
self.license = license
|
| 353 |
+
self.license_name = license_name
|
| 354 |
+
self.license_link = license_link
|
| 355 |
+
self.metrics = metrics
|
| 356 |
+
self.model_name = model_name
|
| 357 |
+
self.pipeline_tag = pipeline_tag
|
| 358 |
+
self.tags = _to_unique_list(tags)
|
| 359 |
+
|
| 360 |
+
model_index = kwargs.pop("model-index", None)
|
| 361 |
+
if model_index:
|
| 362 |
+
try:
|
| 363 |
+
model_name, eval_results = model_index_to_eval_results(model_index)
|
| 364 |
+
self.model_name = model_name
|
| 365 |
+
self.eval_results = eval_results
|
| 366 |
+
except (KeyError, TypeError) as error:
|
| 367 |
+
if ignore_metadata_errors:
|
| 368 |
+
logger.warning("Invalid model-index. Not loading eval results into CardData.")
|
| 369 |
+
else:
|
| 370 |
+
raise ValueError(
|
| 371 |
+
f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass"
|
| 372 |
+
" `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:"
|
| 373 |
+
" some information will be lost. Use it at your own risk."
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
super().__init__(**kwargs)
|
| 377 |
+
|
| 378 |
+
if self.eval_results:
|
| 379 |
+
try:
|
| 380 |
+
self.eval_results = _validate_eval_results(self.eval_results, self.model_name)
|
| 381 |
+
except Exception as e:
|
| 382 |
+
if ignore_metadata_errors:
|
| 383 |
+
logger.warning(f"Failed to validate eval_results: {e}. Not loading eval results into CardData.")
|
| 384 |
+
else:
|
| 385 |
+
raise ValueError(f"Failed to validate eval_results: {e}") from e
|
| 386 |
+
|
| 387 |
+
def _to_dict(self, data_dict):
|
| 388 |
+
"""Format the internal data dict. In this case, we convert eval results to a valid model index"""
|
| 389 |
+
if self.eval_results is not None:
|
| 390 |
+
data_dict["model-index"] = eval_results_to_model_index(self.model_name, self.eval_results) # type: ignore
|
| 391 |
+
del data_dict["eval_results"], data_dict["model_name"]
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class DatasetCardData(CardData):
|
| 395 |
+
"""Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 396 |
+
|
| 397 |
+
Args:
|
| 398 |
+
language (`list[str]`, *optional*):
|
| 399 |
+
Language of dataset's data or metadata. It must be an ISO 639-1, 639-2 or
|
| 400 |
+
639-3 code (two/three letters), or a special value like "code", "multilingual".
|
| 401 |
+
license (`Union[str, list[str]]`, *optional*):
|
| 402 |
+
License(s) of this dataset. Example: apache-2.0 or any license from
|
| 403 |
+
https://huggingface.co/docs/hub/repositories-licenses.
|
| 404 |
+
annotations_creators (`Union[str, list[str]]`, *optional*):
|
| 405 |
+
How the annotations for the dataset were created.
|
| 406 |
+
Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'no-annotation', 'other'.
|
| 407 |
+
language_creators (`Union[str, list[str]]`, *optional*):
|
| 408 |
+
How the text-based data in the dataset was created.
|
| 409 |
+
Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'other'
|
| 410 |
+
multilinguality (`Union[str, list[str]]`, *optional*):
|
| 411 |
+
Whether the dataset is multilingual.
|
| 412 |
+
Options are: 'monolingual', 'multilingual', 'translation', 'other'.
|
| 413 |
+
size_categories (`Union[str, list[str]]`, *optional*):
|
| 414 |
+
The number of examples in the dataset. Options are: 'n<1K', '1K<n<10K', '10K<n<100K',
|
| 415 |
+
'100K<n<1M', '1M<n<10M', '10M<n<100M', '100M<n<1B', '1B<n<10B', '10B<n<100B', '100B<n<1T', 'n>1T', and 'other'.
|
| 416 |
+
source_datasets (`list[str]]`, *optional*):
|
| 417 |
+
Indicates whether the dataset is an original dataset or extended from another existing dataset.
|
| 418 |
+
Options are: 'original' and 'extended'.
|
| 419 |
+
task_categories (`Union[str, list[str]]`, *optional*):
|
| 420 |
+
What categories of task does the dataset support?
|
| 421 |
+
task_ids (`Union[str, list[str]]`, *optional*):
|
| 422 |
+
What specific tasks does the dataset support?
|
| 423 |
+
paperswithcode_id (`str`, *optional*):
|
| 424 |
+
ID of the dataset on PapersWithCode.
|
| 425 |
+
pretty_name (`str`, *optional*):
|
| 426 |
+
A more human-readable name for the dataset. (ex. "Cats vs. Dogs")
|
| 427 |
+
train_eval_index (`dict`, *optional*):
|
| 428 |
+
A dictionary that describes the necessary spec for doing evaluation on the Hub.
|
| 429 |
+
If not provided, it will be gathered from the 'train-eval-index' key of the kwargs.
|
| 430 |
+
config_names (`Union[str, list[str]]`, *optional*):
|
| 431 |
+
A list of the available dataset configs for the dataset.
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
def __init__(
|
| 435 |
+
self,
|
| 436 |
+
*,
|
| 437 |
+
language: str | list[str] | None = None,
|
| 438 |
+
license: str | list[str] | None = None,
|
| 439 |
+
annotations_creators: str | list[str] | None = None,
|
| 440 |
+
language_creators: str | list[str] | None = None,
|
| 441 |
+
multilinguality: str | list[str] | None = None,
|
| 442 |
+
size_categories: str | list[str] | None = None,
|
| 443 |
+
source_datasets: list[str] | None = None,
|
| 444 |
+
task_categories: str | list[str] | None = None,
|
| 445 |
+
task_ids: str | list[str] | None = None,
|
| 446 |
+
paperswithcode_id: str | None = None,
|
| 447 |
+
pretty_name: str | None = None,
|
| 448 |
+
train_eval_index: dict | None = None,
|
| 449 |
+
config_names: str | list[str] | None = None,
|
| 450 |
+
ignore_metadata_errors: bool = False,
|
| 451 |
+
**kwargs,
|
| 452 |
+
):
|
| 453 |
+
self.annotations_creators = annotations_creators
|
| 454 |
+
self.language_creators = language_creators
|
| 455 |
+
self.language = language
|
| 456 |
+
self.license = license
|
| 457 |
+
self.multilinguality = multilinguality
|
| 458 |
+
self.size_categories = size_categories
|
| 459 |
+
self.source_datasets = source_datasets
|
| 460 |
+
self.task_categories = task_categories
|
| 461 |
+
self.task_ids = task_ids
|
| 462 |
+
self.paperswithcode_id = paperswithcode_id
|
| 463 |
+
self.pretty_name = pretty_name
|
| 464 |
+
self.config_names = config_names
|
| 465 |
+
|
| 466 |
+
# TODO - maybe handle this similarly to EvalResult?
|
| 467 |
+
self.train_eval_index = train_eval_index or kwargs.pop("train-eval-index", None)
|
| 468 |
+
super().__init__(**kwargs)
|
| 469 |
+
|
| 470 |
+
def _to_dict(self, data_dict):
|
| 471 |
+
data_dict["train-eval-index"] = data_dict.pop("train_eval_index")
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
class SpaceCardData(CardData):
|
| 475 |
+
"""Space Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 476 |
+
|
| 477 |
+
To get an exhaustive reference of Spaces configuration, please visit https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference.
|
| 478 |
+
|
| 479 |
+
Args:
|
| 480 |
+
title (`str`, *optional*)
|
| 481 |
+
Title of the Space.
|
| 482 |
+
sdk (`str`, *optional*)
|
| 483 |
+
SDK of the Space (one of `gradio`, `streamlit`, `docker`, or `static`).
|
| 484 |
+
sdk_version (`str`, *optional*)
|
| 485 |
+
Version of the used SDK (if Gradio/Streamlit sdk).
|
| 486 |
+
python_version (`str`, *optional*)
|
| 487 |
+
Python version used in the Space (if Gradio/Streamlit sdk).
|
| 488 |
+
app_file (`str`, *optional*)
|
| 489 |
+
Path to your main application file (which contains either gradio or streamlit Python code, or static html code).
|
| 490 |
+
Path is relative to the root of the repository.
|
| 491 |
+
app_port (`str`, *optional*)
|
| 492 |
+
Port on which your application is running. Used only if sdk is `docker`.
|
| 493 |
+
license (`str`, *optional*)
|
| 494 |
+
License of this model. Example: apache-2.0 or any license from
|
| 495 |
+
https://huggingface.co/docs/hub/repositories-licenses.
|
| 496 |
+
duplicated_from (`str`, *optional*)
|
| 497 |
+
ID of the original Space if this is a duplicated Space.
|
| 498 |
+
models (list[`str`], *optional*)
|
| 499 |
+
List of models related to this Space. Should be a dataset ID found on https://hf.co/models.
|
| 500 |
+
datasets (`list[str]`, *optional*)
|
| 501 |
+
List of datasets related to this Space. Should be a dataset ID found on https://hf.co/datasets.
|
| 502 |
+
tags (`list[str]`, *optional*)
|
| 503 |
+
List of tags to add to your Space that can be used when filtering on the Hub.
|
| 504 |
+
ignore_metadata_errors (`str`):
|
| 505 |
+
If True, errors while parsing the metadata section will be ignored. Some information might be lost during
|
| 506 |
+
the process. Use it at your own risk.
|
| 507 |
+
kwargs (`dict`, *optional*):
|
| 508 |
+
Additional metadata that will be added to the space card.
|
| 509 |
+
|
| 510 |
+
Example:
|
| 511 |
+
```python
|
| 512 |
+
>>> from huggingface_hub import SpaceCardData
|
| 513 |
+
>>> card_data = SpaceCardData(
|
| 514 |
+
... title="Dreambooth Training",
|
| 515 |
+
... license="mit",
|
| 516 |
+
... sdk="gradio",
|
| 517 |
+
... duplicated_from="multimodalart/dreambooth-training"
|
| 518 |
+
... )
|
| 519 |
+
>>> card_data.to_dict()
|
| 520 |
+
{'title': 'Dreambooth Training', 'sdk': 'gradio', 'license': 'mit', 'duplicated_from': 'multimodalart/dreambooth-training'}
|
| 521 |
+
```
|
| 522 |
+
"""
|
| 523 |
+
|
| 524 |
+
def __init__(
|
| 525 |
+
self,
|
| 526 |
+
*,
|
| 527 |
+
title: str | None = None,
|
| 528 |
+
sdk: str | None = None,
|
| 529 |
+
sdk_version: str | None = None,
|
| 530 |
+
python_version: str | None = None,
|
| 531 |
+
app_file: str | None = None,
|
| 532 |
+
app_port: int | None = None,
|
| 533 |
+
license: str | None = None,
|
| 534 |
+
duplicated_from: str | None = None,
|
| 535 |
+
models: list[str] | None = None,
|
| 536 |
+
datasets: list[str] | None = None,
|
| 537 |
+
tags: list[str] | None = None,
|
| 538 |
+
ignore_metadata_errors: bool = False,
|
| 539 |
+
**kwargs,
|
| 540 |
+
):
|
| 541 |
+
self.title = title
|
| 542 |
+
self.sdk = sdk
|
| 543 |
+
self.sdk_version = sdk_version
|
| 544 |
+
self.python_version = python_version
|
| 545 |
+
self.app_file = app_file
|
| 546 |
+
self.app_port = app_port
|
| 547 |
+
self.license = license
|
| 548 |
+
self.duplicated_from = duplicated_from
|
| 549 |
+
self.models = models
|
| 550 |
+
self.datasets = datasets
|
| 551 |
+
self.tags = _to_unique_list(tags)
|
| 552 |
+
super().__init__(**kwargs)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def model_index_to_eval_results(model_index: list[dict[str, Any]]) -> tuple[str, list[EvalResult]]:
|
| 556 |
+
"""Takes in a model index and returns the model name and a list of `huggingface_hub.EvalResult` objects.
|
| 557 |
+
|
| 558 |
+
A detailed spec of the model index can be found here:
|
| 559 |
+
https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
|
| 560 |
+
|
| 561 |
+
Args:
|
| 562 |
+
model_index (`list[dict[str, Any]]`):
|
| 563 |
+
A model index data structure, likely coming from a README.md file on the
|
| 564 |
+
Hugging Face Hub.
|
| 565 |
+
|
| 566 |
+
Returns:
|
| 567 |
+
model_name (`str`):
|
| 568 |
+
The name of the model as found in the model index. This is used as the
|
| 569 |
+
identifier for the model on leaderboards like PapersWithCode.
|
| 570 |
+
eval_results (`list[EvalResult]`):
|
| 571 |
+
A list of `huggingface_hub.EvalResult` objects containing the metrics
|
| 572 |
+
reported in the provided model_index.
|
| 573 |
+
|
| 574 |
+
Example:
|
| 575 |
+
```python
|
| 576 |
+
>>> from huggingface_hub.repocard_data import model_index_to_eval_results
|
| 577 |
+
>>> # Define a minimal model index
|
| 578 |
+
>>> model_index = [
|
| 579 |
+
... {
|
| 580 |
+
... "name": "my-cool-model",
|
| 581 |
+
... "results": [
|
| 582 |
+
... {
|
| 583 |
+
... "task": {
|
| 584 |
+
... "type": "image-classification"
|
| 585 |
+
... },
|
| 586 |
+
... "dataset": {
|
| 587 |
+
... "type": "beans",
|
| 588 |
+
... "name": "Beans"
|
| 589 |
+
... },
|
| 590 |
+
... "metrics": [
|
| 591 |
+
... {
|
| 592 |
+
... "type": "accuracy",
|
| 593 |
+
... "value": 0.9
|
| 594 |
+
... }
|
| 595 |
+
... ]
|
| 596 |
+
... }
|
| 597 |
+
... ]
|
| 598 |
+
... }
|
| 599 |
+
... ]
|
| 600 |
+
>>> model_name, eval_results = model_index_to_eval_results(model_index)
|
| 601 |
+
>>> model_name
|
| 602 |
+
'my-cool-model'
|
| 603 |
+
>>> eval_results[0].task_type
|
| 604 |
+
'image-classification'
|
| 605 |
+
>>> eval_results[0].metric_type
|
| 606 |
+
'accuracy'
|
| 607 |
+
|
| 608 |
+
```
|
| 609 |
+
"""
|
| 610 |
+
|
| 611 |
+
eval_results = []
|
| 612 |
+
for elem in model_index:
|
| 613 |
+
name = elem["name"]
|
| 614 |
+
results = elem["results"]
|
| 615 |
+
for result in results:
|
| 616 |
+
task_type = result["task"]["type"]
|
| 617 |
+
task_name = result["task"].get("name")
|
| 618 |
+
dataset_type = result["dataset"]["type"]
|
| 619 |
+
dataset_name = result["dataset"]["name"]
|
| 620 |
+
dataset_config = result["dataset"].get("config")
|
| 621 |
+
dataset_split = result["dataset"].get("split")
|
| 622 |
+
dataset_revision = result["dataset"].get("revision")
|
| 623 |
+
dataset_args = result["dataset"].get("args")
|
| 624 |
+
source_name = result.get("source", {}).get("name")
|
| 625 |
+
source_url = result.get("source", {}).get("url")
|
| 626 |
+
|
| 627 |
+
for metric in result["metrics"]:
|
| 628 |
+
metric_type = metric["type"]
|
| 629 |
+
metric_value = metric["value"]
|
| 630 |
+
metric_name = metric.get("name")
|
| 631 |
+
metric_args = metric.get("args")
|
| 632 |
+
metric_config = metric.get("config")
|
| 633 |
+
verified = metric.get("verified")
|
| 634 |
+
verify_token = metric.get("verifyToken")
|
| 635 |
+
|
| 636 |
+
eval_result = EvalResult(
|
| 637 |
+
task_type=task_type, # Required
|
| 638 |
+
dataset_type=dataset_type, # Required
|
| 639 |
+
dataset_name=dataset_name, # Required
|
| 640 |
+
metric_type=metric_type, # Required
|
| 641 |
+
metric_value=metric_value, # Required
|
| 642 |
+
task_name=task_name,
|
| 643 |
+
dataset_config=dataset_config,
|
| 644 |
+
dataset_split=dataset_split,
|
| 645 |
+
dataset_revision=dataset_revision,
|
| 646 |
+
dataset_args=dataset_args,
|
| 647 |
+
metric_name=metric_name,
|
| 648 |
+
metric_args=metric_args,
|
| 649 |
+
metric_config=metric_config,
|
| 650 |
+
verified=verified,
|
| 651 |
+
verify_token=verify_token,
|
| 652 |
+
source_name=source_name,
|
| 653 |
+
source_url=source_url,
|
| 654 |
+
)
|
| 655 |
+
eval_results.append(eval_result)
|
| 656 |
+
return name, eval_results
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def _remove_none(obj):
|
| 660 |
+
"""
|
| 661 |
+
Recursively remove `None` values from a dict. Borrowed from: https://stackoverflow.com/a/20558778
|
| 662 |
+
"""
|
| 663 |
+
if isinstance(obj, (list, tuple, set)):
|
| 664 |
+
return type(obj)(_remove_none(x) for x in obj if x is not None)
|
| 665 |
+
elif isinstance(obj, dict):
|
| 666 |
+
return type(obj)((_remove_none(k), _remove_none(v)) for k, v in obj.items() if k is not None and v is not None)
|
| 667 |
+
else:
|
| 668 |
+
return obj
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def eval_results_to_model_index(model_name: str, eval_results: list[EvalResult]) -> list[dict[str, Any]]:
|
| 672 |
+
"""Takes in given model name and list of `huggingface_hub.EvalResult` and returns a
|
| 673 |
+
valid model-index that will be compatible with the format expected by the
|
| 674 |
+
Hugging Face Hub.
|
| 675 |
+
|
| 676 |
+
Args:
|
| 677 |
+
model_name (`str`):
|
| 678 |
+
Name of the model (ex. "my-cool-model"). This is used as the identifier
|
| 679 |
+
for the model on leaderboards like PapersWithCode.
|
| 680 |
+
eval_results (`list[EvalResult]`):
|
| 681 |
+
List of `huggingface_hub.EvalResult` objects containing the metrics to be
|
| 682 |
+
reported in the model-index.
|
| 683 |
+
|
| 684 |
+
Returns:
|
| 685 |
+
model_index (`list[dict[str, Any]]`): The eval_results converted to a model-index.
|
| 686 |
+
|
| 687 |
+
Example:
|
| 688 |
+
```python
|
| 689 |
+
>>> from huggingface_hub.repocard_data import eval_results_to_model_index, EvalResult
|
| 690 |
+
>>> # Define minimal eval_results
|
| 691 |
+
>>> eval_results = [
|
| 692 |
+
... EvalResult(
|
| 693 |
+
... task_type="image-classification", # Required
|
| 694 |
+
... dataset_type="beans", # Required
|
| 695 |
+
... dataset_name="Beans", # Required
|
| 696 |
+
... metric_type="accuracy", # Required
|
| 697 |
+
... metric_value=0.9, # Required
|
| 698 |
+
... )
|
| 699 |
+
... ]
|
| 700 |
+
>>> eval_results_to_model_index("my-cool-model", eval_results)
|
| 701 |
+
[{'name': 'my-cool-model', 'results': [{'task': {'type': 'image-classification'}, 'dataset': {'name': 'Beans', 'type': 'beans'}, 'metrics': [{'type': 'accuracy', 'value': 0.9}]}]}]
|
| 702 |
+
|
| 703 |
+
```
|
| 704 |
+
"""
|
| 705 |
+
|
| 706 |
+
# Metrics are reported on a unique task-and-dataset basis.
|
| 707 |
+
# Here, we make a map of those pairs and the associated EvalResults.
|
| 708 |
+
task_and_ds_types_map: dict[Any, list[EvalResult]] = defaultdict(list)
|
| 709 |
+
for eval_result in eval_results:
|
| 710 |
+
task_and_ds_types_map[eval_result.unique_identifier].append(eval_result)
|
| 711 |
+
|
| 712 |
+
# Use the map from above to generate the model index data.
|
| 713 |
+
model_index_data: list[dict[str, Any]] = []
|
| 714 |
+
for results in task_and_ds_types_map.values():
|
| 715 |
+
# All items from `results` share same metadata
|
| 716 |
+
sample_result = results[0]
|
| 717 |
+
data: dict[str, Any] = {
|
| 718 |
+
"task": {
|
| 719 |
+
"type": sample_result.task_type,
|
| 720 |
+
"name": sample_result.task_name,
|
| 721 |
+
},
|
| 722 |
+
"dataset": {
|
| 723 |
+
"name": sample_result.dataset_name,
|
| 724 |
+
"type": sample_result.dataset_type,
|
| 725 |
+
"config": sample_result.dataset_config,
|
| 726 |
+
"split": sample_result.dataset_split,
|
| 727 |
+
"revision": sample_result.dataset_revision,
|
| 728 |
+
"args": sample_result.dataset_args,
|
| 729 |
+
},
|
| 730 |
+
"metrics": [
|
| 731 |
+
{
|
| 732 |
+
"type": result.metric_type,
|
| 733 |
+
"value": result.metric_value,
|
| 734 |
+
"name": result.metric_name,
|
| 735 |
+
"config": result.metric_config,
|
| 736 |
+
"args": result.metric_args,
|
| 737 |
+
"verified": result.verified,
|
| 738 |
+
"verifyToken": result.verify_token,
|
| 739 |
+
}
|
| 740 |
+
for result in results
|
| 741 |
+
],
|
| 742 |
+
}
|
| 743 |
+
if sample_result.source_url is not None:
|
| 744 |
+
source: dict[str, str] = {
|
| 745 |
+
"url": sample_result.source_url,
|
| 746 |
+
}
|
| 747 |
+
if sample_result.source_name is not None:
|
| 748 |
+
source["name"] = sample_result.source_name
|
| 749 |
+
data["source"] = source
|
| 750 |
+
model_index_data.append(data)
|
| 751 |
+
|
| 752 |
+
# TODO - Check if there cases where this list is longer than one?
|
| 753 |
+
# Finally, the model index itself is list of dicts.
|
| 754 |
+
model_index = [
|
| 755 |
+
{
|
| 756 |
+
"name": model_name,
|
| 757 |
+
"results": model_index_data,
|
| 758 |
+
}
|
| 759 |
+
]
|
| 760 |
+
return _remove_none(model_index)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def _to_unique_list(tags: list[str] | None) -> list[str] | None:
|
| 764 |
+
if tags is None:
|
| 765 |
+
return tags
|
| 766 |
+
unique_tags = [] # make tags unique + keep order explicitly
|
| 767 |
+
for tag in tags:
|
| 768 |
+
if tag not in unique_tags:
|
| 769 |
+
unique_tags.append(tag)
|
| 770 |
+
return unique_tags
|
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/filters/__init__.py
ADDED
|
@@ -0,0 +1,942 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 6 |
+
filters.
|
| 7 |
+
|
| 8 |
+
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
|
| 9 |
+
:license: BSD, see LICENSE for details.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
from pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \
|
| 15 |
+
string_to_tokentype
|
| 16 |
+
from pygments.filter import Filter
|
| 17 |
+
from pygments.util import get_list_opt, get_int_opt, get_bool_opt, \
|
| 18 |
+
get_choice_opt, ClassNotFound, OptionError
|
| 19 |
+
from pygments.plugin import find_plugin_filters
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def find_filter_class(filtername):
|
| 23 |
+
"""Lookup a filter by name. Return None if not found."""
|
| 24 |
+
if filtername in FILTERS:
|
| 25 |
+
return FILTERS[filtername]
|
| 26 |
+
for name, cls in find_plugin_filters():
|
| 27 |
+
if name == filtername:
|
| 28 |
+
return cls
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_filter_by_name(filtername, **options):
|
| 33 |
+
"""Return an instantiated filter.
|
| 34 |
+
|
| 35 |
+
Options are passed to the filter initializer if wanted.
|
| 36 |
+
Raise a ClassNotFound if not found.
|
| 37 |
+
"""
|
| 38 |
+
cls = find_filter_class(filtername)
|
| 39 |
+
if cls:
|
| 40 |
+
return cls(**options)
|
| 41 |
+
else:
|
| 42 |
+
raise ClassNotFound(f'filter {filtername!r} not found')
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_all_filters():
|
| 46 |
+
"""Return a generator of all filter names."""
|
| 47 |
+
yield from FILTERS
|
| 48 |
+
for name, _ in find_plugin_filters():
|
| 49 |
+
yield name
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _replace_special(ttype, value, regex, specialttype,
|
| 53 |
+
replacefunc=lambda x: x):
|
| 54 |
+
last = 0
|
| 55 |
+
for match in regex.finditer(value):
|
| 56 |
+
start, end = match.start(), match.end()
|
| 57 |
+
if start != last:
|
| 58 |
+
yield ttype, value[last:start]
|
| 59 |
+
yield specialttype, replacefunc(value[start:end])
|
| 60 |
+
last = end
|
| 61 |
+
if last != len(value):
|
| 62 |
+
yield ttype, value[last:]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class CodeTagFilter(Filter):
|
| 66 |
+
"""Highlight special code tags in comments and docstrings.
|
| 67 |
+
|
| 68 |
+
Options accepted:
|
| 69 |
+
|
| 70 |
+
`codetags` : list of strings
|
| 71 |
+
A list of strings that are flagged as code tags. The default is to
|
| 72 |
+
highlight ``XXX``, ``TODO``, ``FIXME``, ``BUG`` and ``NOTE``.
|
| 73 |
+
|
| 74 |
+
.. versionchanged:: 2.13
|
| 75 |
+
Now recognizes ``FIXME`` by default.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, **options):
|
| 79 |
+
Filter.__init__(self, **options)
|
| 80 |
+
tags = get_list_opt(options, 'codetags',
|
| 81 |
+
['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE'])
|
| 82 |
+
self.tag_re = re.compile(r'\b({})\b'.format('|'.join([
|
| 83 |
+
re.escape(tag) for tag in tags if tag
|
| 84 |
+
])))
|
| 85 |
+
|
| 86 |
+
def filter(self, lexer, stream):
|
| 87 |
+
regex = self.tag_re
|
| 88 |
+
for ttype, value in stream:
|
| 89 |
+
if ttype in String.Doc or \
|
| 90 |
+
ttype in Comment and \
|
| 91 |
+
ttype not in Comment.Preproc:
|
| 92 |
+
yield from _replace_special(ttype, value, regex, Comment.Special)
|
| 93 |
+
else:
|
| 94 |
+
yield ttype, value
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class SymbolFilter(Filter):
|
| 98 |
+
"""Convert mathematical symbols into Unicode characters.
|
| 99 |
+
|
| 100 |
+
Examples are ``\\<longrightarrow>`` in Isabelle or
|
| 101 |
+
``\\longrightarrow`` in LaTeX.
|
| 102 |
+
|
| 103 |
+
This is mostly useful for HTML or console output when you want to
|
| 104 |
+
approximate the source rendering you'd see in an IDE.
|
| 105 |
+
|
| 106 |
+
Options accepted:
|
| 107 |
+
|
| 108 |
+
`lang` : string
|
| 109 |
+
The symbol language. Must be one of ``'isabelle'`` or
|
| 110 |
+
``'latex'``. The default is ``'isabelle'``.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
latex_symbols = {
|
| 114 |
+
'\\alpha' : '\U000003b1',
|
| 115 |
+
'\\beta' : '\U000003b2',
|
| 116 |
+
'\\gamma' : '\U000003b3',
|
| 117 |
+
'\\delta' : '\U000003b4',
|
| 118 |
+
'\\varepsilon' : '\U000003b5',
|
| 119 |
+
'\\zeta' : '\U000003b6',
|
| 120 |
+
'\\eta' : '\U000003b7',
|
| 121 |
+
'\\vartheta' : '\U000003b8',
|
| 122 |
+
'\\iota' : '\U000003b9',
|
| 123 |
+
'\\kappa' : '\U000003ba',
|
| 124 |
+
'\\lambda' : '\U000003bb',
|
| 125 |
+
'\\mu' : '\U000003bc',
|
| 126 |
+
'\\nu' : '\U000003bd',
|
| 127 |
+
'\\xi' : '\U000003be',
|
| 128 |
+
'\\pi' : '\U000003c0',
|
| 129 |
+
'\\varrho' : '\U000003c1',
|
| 130 |
+
'\\sigma' : '\U000003c3',
|
| 131 |
+
'\\tau' : '\U000003c4',
|
| 132 |
+
'\\upsilon' : '\U000003c5',
|
| 133 |
+
'\\varphi' : '\U000003c6',
|
| 134 |
+
'\\chi' : '\U000003c7',
|
| 135 |
+
'\\psi' : '\U000003c8',
|
| 136 |
+
'\\omega' : '\U000003c9',
|
| 137 |
+
'\\Gamma' : '\U00000393',
|
| 138 |
+
'\\Delta' : '\U00000394',
|
| 139 |
+
'\\Theta' : '\U00000398',
|
| 140 |
+
'\\Lambda' : '\U0000039b',
|
| 141 |
+
'\\Xi' : '\U0000039e',
|
| 142 |
+
'\\Pi' : '\U000003a0',
|
| 143 |
+
'\\Sigma' : '\U000003a3',
|
| 144 |
+
'\\Upsilon' : '\U000003a5',
|
| 145 |
+
'\\Phi' : '\U000003a6',
|
| 146 |
+
'\\Psi' : '\U000003a8',
|
| 147 |
+
'\\Omega' : '\U000003a9',
|
| 148 |
+
'\\leftarrow' : '\U00002190',
|
| 149 |
+
'\\longleftarrow' : '\U000027f5',
|
| 150 |
+
'\\rightarrow' : '\U00002192',
|
| 151 |
+
'\\longrightarrow' : '\U000027f6',
|
| 152 |
+
'\\Leftarrow' : '\U000021d0',
|
| 153 |
+
'\\Longleftarrow' : '\U000027f8',
|
| 154 |
+
'\\Rightarrow' : '\U000021d2',
|
| 155 |
+
'\\Longrightarrow' : '\U000027f9',
|
| 156 |
+
'\\leftrightarrow' : '\U00002194',
|
| 157 |
+
'\\longleftrightarrow' : '\U000027f7',
|
| 158 |
+
'\\Leftrightarrow' : '\U000021d4',
|
| 159 |
+
'\\Longleftrightarrow' : '\U000027fa',
|
| 160 |
+
'\\mapsto' : '\U000021a6',
|
| 161 |
+
'\\longmapsto' : '\U000027fc',
|
| 162 |
+
'\\relbar' : '\U00002500',
|
| 163 |
+
'\\Relbar' : '\U00002550',
|
| 164 |
+
'\\hookleftarrow' : '\U000021a9',
|
| 165 |
+
'\\hookrightarrow' : '\U000021aa',
|
| 166 |
+
'\\leftharpoondown' : '\U000021bd',
|
| 167 |
+
'\\rightharpoondown' : '\U000021c1',
|
| 168 |
+
'\\leftharpoonup' : '\U000021bc',
|
| 169 |
+
'\\rightharpoonup' : '\U000021c0',
|
| 170 |
+
'\\rightleftharpoons' : '\U000021cc',
|
| 171 |
+
'\\leadsto' : '\U0000219d',
|
| 172 |
+
'\\downharpoonleft' : '\U000021c3',
|
| 173 |
+
'\\downharpoonright' : '\U000021c2',
|
| 174 |
+
'\\upharpoonleft' : '\U000021bf',
|
| 175 |
+
'\\upharpoonright' : '\U000021be',
|
| 176 |
+
'\\restriction' : '\U000021be',
|
| 177 |
+
'\\uparrow' : '\U00002191',
|
| 178 |
+
'\\Uparrow' : '\U000021d1',
|
| 179 |
+
'\\downarrow' : '\U00002193',
|
| 180 |
+
'\\Downarrow' : '\U000021d3',
|
| 181 |
+
'\\updownarrow' : '\U00002195',
|
| 182 |
+
'\\Updownarrow' : '\U000021d5',
|
| 183 |
+
'\\langle' : '\U000027e8',
|
| 184 |
+
'\\rangle' : '\U000027e9',
|
| 185 |
+
'\\lceil' : '\U00002308',
|
| 186 |
+
'\\rceil' : '\U00002309',
|
| 187 |
+
'\\lfloor' : '\U0000230a',
|
| 188 |
+
'\\rfloor' : '\U0000230b',
|
| 189 |
+
'\\flqq' : '\U000000ab',
|
| 190 |
+
'\\frqq' : '\U000000bb',
|
| 191 |
+
'\\bot' : '\U000022a5',
|
| 192 |
+
'\\top' : '\U000022a4',
|
| 193 |
+
'\\wedge' : '\U00002227',
|
| 194 |
+
'\\bigwedge' : '\U000022c0',
|
| 195 |
+
'\\vee' : '\U00002228',
|
| 196 |
+
'\\bigvee' : '\U000022c1',
|
| 197 |
+
'\\forall' : '\U00002200',
|
| 198 |
+
'\\exists' : '\U00002203',
|
| 199 |
+
'\\nexists' : '\U00002204',
|
| 200 |
+
'\\neg' : '\U000000ac',
|
| 201 |
+
'\\Box' : '\U000025a1',
|
| 202 |
+
'\\Diamond' : '\U000025c7',
|
| 203 |
+
'\\vdash' : '\U000022a2',
|
| 204 |
+
'\\models' : '\U000022a8',
|
| 205 |
+
'\\dashv' : '\U000022a3',
|
| 206 |
+
'\\surd' : '\U0000221a',
|
| 207 |
+
'\\le' : '\U00002264',
|
| 208 |
+
'\\ge' : '\U00002265',
|
| 209 |
+
'\\ll' : '\U0000226a',
|
| 210 |
+
'\\gg' : '\U0000226b',
|
| 211 |
+
'\\lesssim' : '\U00002272',
|
| 212 |
+
'\\gtrsim' : '\U00002273',
|
| 213 |
+
'\\lessapprox' : '\U00002a85',
|
| 214 |
+
'\\gtrapprox' : '\U00002a86',
|
| 215 |
+
'\\in' : '\U00002208',
|
| 216 |
+
'\\notin' : '\U00002209',
|
| 217 |
+
'\\subset' : '\U00002282',
|
| 218 |
+
'\\supset' : '\U00002283',
|
| 219 |
+
'\\subseteq' : '\U00002286',
|
| 220 |
+
'\\supseteq' : '\U00002287',
|
| 221 |
+
'\\sqsubset' : '\U0000228f',
|
| 222 |
+
'\\sqsupset' : '\U00002290',
|
| 223 |
+
'\\sqsubseteq' : '\U00002291',
|
| 224 |
+
'\\sqsupseteq' : '\U00002292',
|
| 225 |
+
'\\cap' : '\U00002229',
|
| 226 |
+
'\\bigcap' : '\U000022c2',
|
| 227 |
+
'\\cup' : '\U0000222a',
|
| 228 |
+
'\\bigcup' : '\U000022c3',
|
| 229 |
+
'\\sqcup' : '\U00002294',
|
| 230 |
+
'\\bigsqcup' : '\U00002a06',
|
| 231 |
+
'\\sqcap' : '\U00002293',
|
| 232 |
+
'\\Bigsqcap' : '\U00002a05',
|
| 233 |
+
'\\setminus' : '\U00002216',
|
| 234 |
+
'\\propto' : '\U0000221d',
|
| 235 |
+
'\\uplus' : '\U0000228e',
|
| 236 |
+
'\\bigplus' : '\U00002a04',
|
| 237 |
+
'\\sim' : '\U0000223c',
|
| 238 |
+
'\\doteq' : '\U00002250',
|
| 239 |
+
'\\simeq' : '\U00002243',
|
| 240 |
+
'\\approx' : '\U00002248',
|
| 241 |
+
'\\asymp' : '\U0000224d',
|
| 242 |
+
'\\cong' : '\U00002245',
|
| 243 |
+
'\\equiv' : '\U00002261',
|
| 244 |
+
'\\Join' : '\U000022c8',
|
| 245 |
+
'\\bowtie' : '\U00002a1d',
|
| 246 |
+
'\\prec' : '\U0000227a',
|
| 247 |
+
'\\succ' : '\U0000227b',
|
| 248 |
+
'\\preceq' : '\U0000227c',
|
| 249 |
+
'\\succeq' : '\U0000227d',
|
| 250 |
+
'\\parallel' : '\U00002225',
|
| 251 |
+
'\\mid' : '\U000000a6',
|
| 252 |
+
'\\pm' : '\U000000b1',
|
| 253 |
+
'\\mp' : '\U00002213',
|
| 254 |
+
'\\times' : '\U000000d7',
|
| 255 |
+
'\\div' : '\U000000f7',
|
| 256 |
+
'\\cdot' : '\U000022c5',
|
| 257 |
+
'\\star' : '\U000022c6',
|
| 258 |
+
'\\circ' : '\U00002218',
|
| 259 |
+
'\\dagger' : '\U00002020',
|
| 260 |
+
'\\ddagger' : '\U00002021',
|
| 261 |
+
'\\lhd' : '\U000022b2',
|
| 262 |
+
'\\rhd' : '\U000022b3',
|
| 263 |
+
'\\unlhd' : '\U000022b4',
|
| 264 |
+
'\\unrhd' : '\U000022b5',
|
| 265 |
+
'\\triangleleft' : '\U000025c3',
|
| 266 |
+
'\\triangleright' : '\U000025b9',
|
| 267 |
+
'\\triangle' : '\U000025b3',
|
| 268 |
+
'\\triangleq' : '\U0000225c',
|
| 269 |
+
'\\oplus' : '\U00002295',
|
| 270 |
+
'\\bigoplus' : '\U00002a01',
|
| 271 |
+
'\\otimes' : '\U00002297',
|
| 272 |
+
'\\bigotimes' : '\U00002a02',
|
| 273 |
+
'\\odot' : '\U00002299',
|
| 274 |
+
'\\bigodot' : '\U00002a00',
|
| 275 |
+
'\\ominus' : '\U00002296',
|
| 276 |
+
'\\oslash' : '\U00002298',
|
| 277 |
+
'\\dots' : '\U00002026',
|
| 278 |
+
'\\cdots' : '\U000022ef',
|
| 279 |
+
'\\sum' : '\U00002211',
|
| 280 |
+
'\\prod' : '\U0000220f',
|
| 281 |
+
'\\coprod' : '\U00002210',
|
| 282 |
+
'\\infty' : '\U0000221e',
|
| 283 |
+
'\\int' : '\U0000222b',
|
| 284 |
+
'\\oint' : '\U0000222e',
|
| 285 |
+
'\\clubsuit' : '\U00002663',
|
| 286 |
+
'\\diamondsuit' : '\U00002662',
|
| 287 |
+
'\\heartsuit' : '\U00002661',
|
| 288 |
+
'\\spadesuit' : '\U00002660',
|
| 289 |
+
'\\aleph' : '\U00002135',
|
| 290 |
+
'\\emptyset' : '\U00002205',
|
| 291 |
+
'\\nabla' : '\U00002207',
|
| 292 |
+
'\\partial' : '\U00002202',
|
| 293 |
+
'\\flat' : '\U0000266d',
|
| 294 |
+
'\\natural' : '\U0000266e',
|
| 295 |
+
'\\sharp' : '\U0000266f',
|
| 296 |
+
'\\angle' : '\U00002220',
|
| 297 |
+
'\\copyright' : '\U000000a9',
|
| 298 |
+
'\\textregistered' : '\U000000ae',
|
| 299 |
+
'\\textonequarter' : '\U000000bc',
|
| 300 |
+
'\\textonehalf' : '\U000000bd',
|
| 301 |
+
'\\textthreequarters' : '\U000000be',
|
| 302 |
+
'\\textordfeminine' : '\U000000aa',
|
| 303 |
+
'\\textordmasculine' : '\U000000ba',
|
| 304 |
+
'\\euro' : '\U000020ac',
|
| 305 |
+
'\\pounds' : '\U000000a3',
|
| 306 |
+
'\\yen' : '\U000000a5',
|
| 307 |
+
'\\textcent' : '\U000000a2',
|
| 308 |
+
'\\textcurrency' : '\U000000a4',
|
| 309 |
+
'\\textdegree' : '\U000000b0',
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
isabelle_symbols = {
|
| 313 |
+
'\\<zero>' : '\U0001d7ec',
|
| 314 |
+
'\\<one>' : '\U0001d7ed',
|
| 315 |
+
'\\<two>' : '\U0001d7ee',
|
| 316 |
+
'\\<three>' : '\U0001d7ef',
|
| 317 |
+
'\\<four>' : '\U0001d7f0',
|
| 318 |
+
'\\<five>' : '\U0001d7f1',
|
| 319 |
+
'\\<six>' : '\U0001d7f2',
|
| 320 |
+
'\\<seven>' : '\U0001d7f3',
|
| 321 |
+
'\\<eight>' : '\U0001d7f4',
|
| 322 |
+
'\\<nine>' : '\U0001d7f5',
|
| 323 |
+
'\\<A>' : '\U0001d49c',
|
| 324 |
+
'\\<B>' : '\U0000212c',
|
| 325 |
+
'\\<C>' : '\U0001d49e',
|
| 326 |
+
'\\<D>' : '\U0001d49f',
|
| 327 |
+
'\\<E>' : '\U00002130',
|
| 328 |
+
'\\<F>' : '\U00002131',
|
| 329 |
+
'\\<G>' : '\U0001d4a2',
|
| 330 |
+
'\\<H>' : '\U0000210b',
|
| 331 |
+
'\\<I>' : '\U00002110',
|
| 332 |
+
'\\<J>' : '\U0001d4a5',
|
| 333 |
+
'\\<K>' : '\U0001d4a6',
|
| 334 |
+
'\\<L>' : '\U00002112',
|
| 335 |
+
'\\<M>' : '\U00002133',
|
| 336 |
+
'\\<N>' : '\U0001d4a9',
|
| 337 |
+
'\\<O>' : '\U0001d4aa',
|
| 338 |
+
'\\<P>' : '\U0001d4ab',
|
| 339 |
+
'\\<Q>' : '\U0001d4ac',
|
| 340 |
+
'\\<R>' : '\U0000211b',
|
| 341 |
+
'\\<S>' : '\U0001d4ae',
|
| 342 |
+
'\\<T>' : '\U0001d4af',
|
| 343 |
+
'\\<U>' : '\U0001d4b0',
|
| 344 |
+
'\\<V>' : '\U0001d4b1',
|
| 345 |
+
'\\<W>' : '\U0001d4b2',
|
| 346 |
+
'\\<X>' : '\U0001d4b3',
|
| 347 |
+
'\\<Y>' : '\U0001d4b4',
|
| 348 |
+
'\\<Z>' : '\U0001d4b5',
|
| 349 |
+
'\\<a>' : '\U0001d5ba',
|
| 350 |
+
'\\<b>' : '\U0001d5bb',
|
| 351 |
+
'\\<c>' : '\U0001d5bc',
|
| 352 |
+
'\\<d>' : '\U0001d5bd',
|
| 353 |
+
'\\<e>' : '\U0001d5be',
|
| 354 |
+
'\\<f>' : '\U0001d5bf',
|
| 355 |
+
'\\<g>' : '\U0001d5c0',
|
| 356 |
+
'\\<h>' : '\U0001d5c1',
|
| 357 |
+
'\\<i>' : '\U0001d5c2',
|
| 358 |
+
'\\<j>' : '\U0001d5c3',
|
| 359 |
+
'\\<k>' : '\U0001d5c4',
|
| 360 |
+
'\\<l>' : '\U0001d5c5',
|
| 361 |
+
'\\<m>' : '\U0001d5c6',
|
| 362 |
+
'\\<n>' : '\U0001d5c7',
|
| 363 |
+
'\\<o>' : '\U0001d5c8',
|
| 364 |
+
'\\<p>' : '\U0001d5c9',
|
| 365 |
+
'\\<q>' : '\U0001d5ca',
|
| 366 |
+
'\\<r>' : '\U0001d5cb',
|
| 367 |
+
'\\<s>' : '\U0001d5cc',
|
| 368 |
+
'\\<t>' : '\U0001d5cd',
|
| 369 |
+
'\\<u>' : '\U0001d5ce',
|
| 370 |
+
'\\<v>' : '\U0001d5cf',
|
| 371 |
+
'\\<w>' : '\U0001d5d0',
|
| 372 |
+
'\\<x>' : '\U0001d5d1',
|
| 373 |
+
'\\<y>' : '\U0001d5d2',
|
| 374 |
+
'\\<z>' : '\U0001d5d3',
|
| 375 |
+
'\\<AA>' : '\U0001d504',
|
| 376 |
+
'\\<BB>' : '\U0001d505',
|
| 377 |
+
'\\<CC>' : '\U0000212d',
|
| 378 |
+
'\\<DD>' : '\U0001d507',
|
| 379 |
+
'\\<EE>' : '\U0001d508',
|
| 380 |
+
'\\<FF>' : '\U0001d509',
|
| 381 |
+
'\\<GG>' : '\U0001d50a',
|
| 382 |
+
'\\<HH>' : '\U0000210c',
|
| 383 |
+
'\\<II>' : '\U00002111',
|
| 384 |
+
'\\<JJ>' : '\U0001d50d',
|
| 385 |
+
'\\<KK>' : '\U0001d50e',
|
| 386 |
+
'\\<LL>' : '\U0001d50f',
|
| 387 |
+
'\\<MM>' : '\U0001d510',
|
| 388 |
+
'\\<NN>' : '\U0001d511',
|
| 389 |
+
'\\<OO>' : '\U0001d512',
|
| 390 |
+
'\\<PP>' : '\U0001d513',
|
| 391 |
+
'\\<QQ>' : '\U0001d514',
|
| 392 |
+
'\\<RR>' : '\U0000211c',
|
| 393 |
+
'\\<SS>' : '\U0001d516',
|
| 394 |
+
'\\<TT>' : '\U0001d517',
|
| 395 |
+
'\\<UU>' : '\U0001d518',
|
| 396 |
+
'\\<VV>' : '\U0001d519',
|
| 397 |
+
'\\<WW>' : '\U0001d51a',
|
| 398 |
+
'\\<XX>' : '\U0001d51b',
|
| 399 |
+
'\\<YY>' : '\U0001d51c',
|
| 400 |
+
'\\<ZZ>' : '\U00002128',
|
| 401 |
+
'\\<aa>' : '\U0001d51e',
|
| 402 |
+
'\\<bb>' : '\U0001d51f',
|
| 403 |
+
'\\<cc>' : '\U0001d520',
|
| 404 |
+
'\\<dd>' : '\U0001d521',
|
| 405 |
+
'\\<ee>' : '\U0001d522',
|
| 406 |
+
'\\<ff>' : '\U0001d523',
|
| 407 |
+
'\\<gg>' : '\U0001d524',
|
| 408 |
+
'\\<hh>' : '\U0001d525',
|
| 409 |
+
'\\<ii>' : '\U0001d526',
|
| 410 |
+
'\\<jj>' : '\U0001d527',
|
| 411 |
+
'\\<kk>' : '\U0001d528',
|
| 412 |
+
'\\<ll>' : '\U0001d529',
|
| 413 |
+
'\\<mm>' : '\U0001d52a',
|
| 414 |
+
'\\<nn>' : '\U0001d52b',
|
| 415 |
+
'\\<oo>' : '\U0001d52c',
|
| 416 |
+
'\\<pp>' : '\U0001d52d',
|
| 417 |
+
'\\<qq>' : '\U0001d52e',
|
| 418 |
+
'\\<rr>' : '\U0001d52f',
|
| 419 |
+
'\\<ss>' : '\U0001d530',
|
| 420 |
+
'\\<tt>' : '\U0001d531',
|
| 421 |
+
'\\<uu>' : '\U0001d532',
|
| 422 |
+
'\\<vv>' : '\U0001d533',
|
| 423 |
+
'\\<ww>' : '\U0001d534',
|
| 424 |
+
'\\<xx>' : '\U0001d535',
|
| 425 |
+
'\\<yy>' : '\U0001d536',
|
| 426 |
+
'\\<zz>' : '\U0001d537',
|
| 427 |
+
'\\<alpha>' : '\U000003b1',
|
| 428 |
+
'\\<beta>' : '\U000003b2',
|
| 429 |
+
'\\<gamma>' : '\U000003b3',
|
| 430 |
+
'\\<delta>' : '\U000003b4',
|
| 431 |
+
'\\<epsilon>' : '\U000003b5',
|
| 432 |
+
'\\<zeta>' : '\U000003b6',
|
| 433 |
+
'\\<eta>' : '\U000003b7',
|
| 434 |
+
'\\<theta>' : '\U000003b8',
|
| 435 |
+
'\\<iota>' : '\U000003b9',
|
| 436 |
+
'\\<kappa>' : '\U000003ba',
|
| 437 |
+
'\\<lambda>' : '\U000003bb',
|
| 438 |
+
'\\<mu>' : '\U000003bc',
|
| 439 |
+
'\\<nu>' : '\U000003bd',
|
| 440 |
+
'\\<xi>' : '\U000003be',
|
| 441 |
+
'\\<pi>' : '\U000003c0',
|
| 442 |
+
'\\<rho>' : '\U000003c1',
|
| 443 |
+
'\\<sigma>' : '\U000003c3',
|
| 444 |
+
'\\<tau>' : '\U000003c4',
|
| 445 |
+
'\\<upsilon>' : '\U000003c5',
|
| 446 |
+
'\\<phi>' : '\U000003c6',
|
| 447 |
+
'\\<chi>' : '\U000003c7',
|
| 448 |
+
'\\<psi>' : '\U000003c8',
|
| 449 |
+
'\\<omega>' : '\U000003c9',
|
| 450 |
+
'\\<Gamma>' : '\U00000393',
|
| 451 |
+
'\\<Delta>' : '\U00000394',
|
| 452 |
+
'\\<Theta>' : '\U00000398',
|
| 453 |
+
'\\<Lambda>' : '\U0000039b',
|
| 454 |
+
'\\<Xi>' : '\U0000039e',
|
| 455 |
+
'\\<Pi>' : '\U000003a0',
|
| 456 |
+
'\\<Sigma>' : '\U000003a3',
|
| 457 |
+
'\\<Upsilon>' : '\U000003a5',
|
| 458 |
+
'\\<Phi>' : '\U000003a6',
|
| 459 |
+
'\\<Psi>' : '\U000003a8',
|
| 460 |
+
'\\<Omega>' : '\U000003a9',
|
| 461 |
+
'\\<bool>' : '\U0001d539',
|
| 462 |
+
'\\<complex>' : '\U00002102',
|
| 463 |
+
'\\<nat>' : '\U00002115',
|
| 464 |
+
'\\<rat>' : '\U0000211a',
|
| 465 |
+
'\\<real>' : '\U0000211d',
|
| 466 |
+
'\\<int>' : '\U00002124',
|
| 467 |
+
'\\<leftarrow>' : '\U00002190',
|
| 468 |
+
'\\<longleftarrow>' : '\U000027f5',
|
| 469 |
+
'\\<rightarrow>' : '\U00002192',
|
| 470 |
+
'\\<longrightarrow>' : '\U000027f6',
|
| 471 |
+
'\\<Leftarrow>' : '\U000021d0',
|
| 472 |
+
'\\<Longleftarrow>' : '\U000027f8',
|
| 473 |
+
'\\<Rightarrow>' : '\U000021d2',
|
| 474 |
+
'\\<Longrightarrow>' : '\U000027f9',
|
| 475 |
+
'\\<leftrightarrow>' : '\U00002194',
|
| 476 |
+
'\\<longleftrightarrow>' : '\U000027f7',
|
| 477 |
+
'\\<Leftrightarrow>' : '\U000021d4',
|
| 478 |
+
'\\<Longleftrightarrow>' : '\U000027fa',
|
| 479 |
+
'\\<mapsto>' : '\U000021a6',
|
| 480 |
+
'\\<longmapsto>' : '\U000027fc',
|
| 481 |
+
'\\<midarrow>' : '\U00002500',
|
| 482 |
+
'\\<Midarrow>' : '\U00002550',
|
| 483 |
+
'\\<hookleftarrow>' : '\U000021a9',
|
| 484 |
+
'\\<hookrightarrow>' : '\U000021aa',
|
| 485 |
+
'\\<leftharpoondown>' : '\U000021bd',
|
| 486 |
+
'\\<rightharpoondown>' : '\U000021c1',
|
| 487 |
+
'\\<leftharpoonup>' : '\U000021bc',
|
| 488 |
+
'\\<rightharpoonup>' : '\U000021c0',
|
| 489 |
+
'\\<rightleftharpoons>' : '\U000021cc',
|
| 490 |
+
'\\<leadsto>' : '\U0000219d',
|
| 491 |
+
'\\<downharpoonleft>' : '\U000021c3',
|
| 492 |
+
'\\<downharpoonright>' : '\U000021c2',
|
| 493 |
+
'\\<upharpoonleft>' : '\U000021bf',
|
| 494 |
+
'\\<upharpoonright>' : '\U000021be',
|
| 495 |
+
'\\<restriction>' : '\U000021be',
|
| 496 |
+
'\\<Colon>' : '\U00002237',
|
| 497 |
+
'\\<up>' : '\U00002191',
|
| 498 |
+
'\\<Up>' : '\U000021d1',
|
| 499 |
+
'\\<down>' : '\U00002193',
|
| 500 |
+
'\\<Down>' : '\U000021d3',
|
| 501 |
+
'\\<updown>' : '\U00002195',
|
| 502 |
+
'\\<Updown>' : '\U000021d5',
|
| 503 |
+
'\\<langle>' : '\U000027e8',
|
| 504 |
+
'\\<rangle>' : '\U000027e9',
|
| 505 |
+
'\\<lceil>' : '\U00002308',
|
| 506 |
+
'\\<rceil>' : '\U00002309',
|
| 507 |
+
'\\<lfloor>' : '\U0000230a',
|
| 508 |
+
'\\<rfloor>' : '\U0000230b',
|
| 509 |
+
'\\<lparr>' : '\U00002987',
|
| 510 |
+
'\\<rparr>' : '\U00002988',
|
| 511 |
+
'\\<lbrakk>' : '\U000027e6',
|
| 512 |
+
'\\<rbrakk>' : '\U000027e7',
|
| 513 |
+
'\\<lbrace>' : '\U00002983',
|
| 514 |
+
'\\<rbrace>' : '\U00002984',
|
| 515 |
+
'\\<guillemotleft>' : '\U000000ab',
|
| 516 |
+
'\\<guillemotright>' : '\U000000bb',
|
| 517 |
+
'\\<bottom>' : '\U000022a5',
|
| 518 |
+
'\\<top>' : '\U000022a4',
|
| 519 |
+
'\\<and>' : '\U00002227',
|
| 520 |
+
'\\<And>' : '\U000022c0',
|
| 521 |
+
'\\<or>' : '\U00002228',
|
| 522 |
+
'\\<Or>' : '\U000022c1',
|
| 523 |
+
'\\<forall>' : '\U00002200',
|
| 524 |
+
'\\<exists>' : '\U00002203',
|
| 525 |
+
'\\<nexists>' : '\U00002204',
|
| 526 |
+
'\\<not>' : '\U000000ac',
|
| 527 |
+
'\\<box>' : '\U000025a1',
|
| 528 |
+
'\\<diamond>' : '\U000025c7',
|
| 529 |
+
'\\<turnstile>' : '\U000022a2',
|
| 530 |
+
'\\<Turnstile>' : '\U000022a8',
|
| 531 |
+
'\\<tturnstile>' : '\U000022a9',
|
| 532 |
+
'\\<TTurnstile>' : '\U000022ab',
|
| 533 |
+
'\\<stileturn>' : '\U000022a3',
|
| 534 |
+
'\\<surd>' : '\U0000221a',
|
| 535 |
+
'\\<le>' : '\U00002264',
|
| 536 |
+
'\\<ge>' : '\U00002265',
|
| 537 |
+
'\\<lless>' : '\U0000226a',
|
| 538 |
+
'\\<ggreater>' : '\U0000226b',
|
| 539 |
+
'\\<lesssim>' : '\U00002272',
|
| 540 |
+
'\\<greatersim>' : '\U00002273',
|
| 541 |
+
'\\<lessapprox>' : '\U00002a85',
|
| 542 |
+
'\\<greaterapprox>' : '\U00002a86',
|
| 543 |
+
'\\<in>' : '\U00002208',
|
| 544 |
+
'\\<notin>' : '\U00002209',
|
| 545 |
+
'\\<subset>' : '\U00002282',
|
| 546 |
+
'\\<supset>' : '\U00002283',
|
| 547 |
+
'\\<subseteq>' : '\U00002286',
|
| 548 |
+
'\\<supseteq>' : '\U00002287',
|
| 549 |
+
'\\<sqsubset>' : '\U0000228f',
|
| 550 |
+
'\\<sqsupset>' : '\U00002290',
|
| 551 |
+
'\\<sqsubseteq>' : '\U00002291',
|
| 552 |
+
'\\<sqsupseteq>' : '\U00002292',
|
| 553 |
+
'\\<inter>' : '\U00002229',
|
| 554 |
+
'\\<Inter>' : '\U000022c2',
|
| 555 |
+
'\\<union>' : '\U0000222a',
|
| 556 |
+
'\\<Union>' : '\U000022c3',
|
| 557 |
+
'\\<squnion>' : '\U00002294',
|
| 558 |
+
'\\<Squnion>' : '\U00002a06',
|
| 559 |
+
'\\<sqinter>' : '\U00002293',
|
| 560 |
+
'\\<Sqinter>' : '\U00002a05',
|
| 561 |
+
'\\<setminus>' : '\U00002216',
|
| 562 |
+
'\\<propto>' : '\U0000221d',
|
| 563 |
+
'\\<uplus>' : '\U0000228e',
|
| 564 |
+
'\\<Uplus>' : '\U00002a04',
|
| 565 |
+
'\\<noteq>' : '\U00002260',
|
| 566 |
+
'\\<sim>' : '\U0000223c',
|
| 567 |
+
'\\<doteq>' : '\U00002250',
|
| 568 |
+
'\\<simeq>' : '\U00002243',
|
| 569 |
+
'\\<approx>' : '\U00002248',
|
| 570 |
+
'\\<asymp>' : '\U0000224d',
|
| 571 |
+
'\\<cong>' : '\U00002245',
|
| 572 |
+
'\\<smile>' : '\U00002323',
|
| 573 |
+
'\\<equiv>' : '\U00002261',
|
| 574 |
+
'\\<frown>' : '\U00002322',
|
| 575 |
+
'\\<Join>' : '\U000022c8',
|
| 576 |
+
'\\<bowtie>' : '\U00002a1d',
|
| 577 |
+
'\\<prec>' : '\U0000227a',
|
| 578 |
+
'\\<succ>' : '\U0000227b',
|
| 579 |
+
'\\<preceq>' : '\U0000227c',
|
| 580 |
+
'\\<succeq>' : '\U0000227d',
|
| 581 |
+
'\\<parallel>' : '\U00002225',
|
| 582 |
+
'\\<bar>' : '\U000000a6',
|
| 583 |
+
'\\<plusminus>' : '\U000000b1',
|
| 584 |
+
'\\<minusplus>' : '\U00002213',
|
| 585 |
+
'\\<times>' : '\U000000d7',
|
| 586 |
+
'\\<div>' : '\U000000f7',
|
| 587 |
+
'\\<cdot>' : '\U000022c5',
|
| 588 |
+
'\\<star>' : '\U000022c6',
|
| 589 |
+
'\\<bullet>' : '\U00002219',
|
| 590 |
+
'\\<circ>' : '\U00002218',
|
| 591 |
+
'\\<dagger>' : '\U00002020',
|
| 592 |
+
'\\<ddagger>' : '\U00002021',
|
| 593 |
+
'\\<lhd>' : '\U000022b2',
|
| 594 |
+
'\\<rhd>' : '\U000022b3',
|
| 595 |
+
'\\<unlhd>' : '\U000022b4',
|
| 596 |
+
'\\<unrhd>' : '\U000022b5',
|
| 597 |
+
'\\<triangleleft>' : '\U000025c3',
|
| 598 |
+
'\\<triangleright>' : '\U000025b9',
|
| 599 |
+
'\\<triangle>' : '\U000025b3',
|
| 600 |
+
'\\<triangleq>' : '\U0000225c',
|
| 601 |
+
'\\<oplus>' : '\U00002295',
|
| 602 |
+
'\\<Oplus>' : '\U00002a01',
|
| 603 |
+
'\\<otimes>' : '\U00002297',
|
| 604 |
+
'\\<Otimes>' : '\U00002a02',
|
| 605 |
+
'\\<odot>' : '\U00002299',
|
| 606 |
+
'\\<Odot>' : '\U00002a00',
|
| 607 |
+
'\\<ominus>' : '\U00002296',
|
| 608 |
+
'\\<oslash>' : '\U00002298',
|
| 609 |
+
'\\<dots>' : '\U00002026',
|
| 610 |
+
'\\<cdots>' : '\U000022ef',
|
| 611 |
+
'\\<Sum>' : '\U00002211',
|
| 612 |
+
'\\<Prod>' : '\U0000220f',
|
| 613 |
+
'\\<Coprod>' : '\U00002210',
|
| 614 |
+
'\\<infinity>' : '\U0000221e',
|
| 615 |
+
'\\<integral>' : '\U0000222b',
|
| 616 |
+
'\\<ointegral>' : '\U0000222e',
|
| 617 |
+
'\\<clubsuit>' : '\U00002663',
|
| 618 |
+
'\\<diamondsuit>' : '\U00002662',
|
| 619 |
+
'\\<heartsuit>' : '\U00002661',
|
| 620 |
+
'\\<spadesuit>' : '\U00002660',
|
| 621 |
+
'\\<aleph>' : '\U00002135',
|
| 622 |
+
'\\<emptyset>' : '\U00002205',
|
| 623 |
+
'\\<nabla>' : '\U00002207',
|
| 624 |
+
'\\<partial>' : '\U00002202',
|
| 625 |
+
'\\<flat>' : '\U0000266d',
|
| 626 |
+
'\\<natural>' : '\U0000266e',
|
| 627 |
+
'\\<sharp>' : '\U0000266f',
|
| 628 |
+
'\\<angle>' : '\U00002220',
|
| 629 |
+
'\\<copyright>' : '\U000000a9',
|
| 630 |
+
'\\<registered>' : '\U000000ae',
|
| 631 |
+
'\\<hyphen>' : '\U000000ad',
|
| 632 |
+
'\\<inverse>' : '\U000000af',
|
| 633 |
+
'\\<onequarter>' : '\U000000bc',
|
| 634 |
+
'\\<onehalf>' : '\U000000bd',
|
| 635 |
+
'\\<threequarters>' : '\U000000be',
|
| 636 |
+
'\\<ordfeminine>' : '\U000000aa',
|
| 637 |
+
'\\<ordmasculine>' : '\U000000ba',
|
| 638 |
+
'\\<section>' : '\U000000a7',
|
| 639 |
+
'\\<paragraph>' : '\U000000b6',
|
| 640 |
+
'\\<exclamdown>' : '\U000000a1',
|
| 641 |
+
'\\<questiondown>' : '\U000000bf',
|
| 642 |
+
'\\<euro>' : '\U000020ac',
|
| 643 |
+
'\\<pounds>' : '\U000000a3',
|
| 644 |
+
'\\<yen>' : '\U000000a5',
|
| 645 |
+
'\\<cent>' : '\U000000a2',
|
| 646 |
+
'\\<currency>' : '\U000000a4',
|
| 647 |
+
'\\<degree>' : '\U000000b0',
|
| 648 |
+
'\\<amalg>' : '\U00002a3f',
|
| 649 |
+
'\\<mho>' : '\U00002127',
|
| 650 |
+
'\\<lozenge>' : '\U000025ca',
|
| 651 |
+
'\\<wp>' : '\U00002118',
|
| 652 |
+
'\\<wrong>' : '\U00002240',
|
| 653 |
+
'\\<struct>' : '\U000022c4',
|
| 654 |
+
'\\<acute>' : '\U000000b4',
|
| 655 |
+
'\\<index>' : '\U00000131',
|
| 656 |
+
'\\<dieresis>' : '\U000000a8',
|
| 657 |
+
'\\<cedilla>' : '\U000000b8',
|
| 658 |
+
'\\<hungarumlaut>' : '\U000002dd',
|
| 659 |
+
'\\<some>' : '\U000003f5',
|
| 660 |
+
'\\<newline>' : '\U000023ce',
|
| 661 |
+
'\\<open>' : '\U00002039',
|
| 662 |
+
'\\<close>' : '\U0000203a',
|
| 663 |
+
'\\<here>' : '\U00002302',
|
| 664 |
+
'\\<^sub>' : '\U000021e9',
|
| 665 |
+
'\\<^sup>' : '\U000021e7',
|
| 666 |
+
'\\<^bold>' : '\U00002759',
|
| 667 |
+
'\\<^bsub>' : '\U000021d8',
|
| 668 |
+
'\\<^esub>' : '\U000021d9',
|
| 669 |
+
'\\<^bsup>' : '\U000021d7',
|
| 670 |
+
'\\<^esup>' : '\U000021d6',
|
| 671 |
+
}
|
| 672 |
+
|
| 673 |
+
lang_map = {'isabelle' : isabelle_symbols, 'latex' : latex_symbols}
|
| 674 |
+
|
| 675 |
+
def __init__(self, **options):
|
| 676 |
+
Filter.__init__(self, **options)
|
| 677 |
+
lang = get_choice_opt(options, 'lang',
|
| 678 |
+
['isabelle', 'latex'], 'isabelle')
|
| 679 |
+
self.symbols = self.lang_map[lang]
|
| 680 |
+
|
| 681 |
+
def filter(self, lexer, stream):
|
| 682 |
+
for ttype, value in stream:
|
| 683 |
+
if value in self.symbols:
|
| 684 |
+
yield ttype, self.symbols[value]
|
| 685 |
+
else:
|
| 686 |
+
yield ttype, value
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
class KeywordCaseFilter(Filter):
|
| 690 |
+
"""Convert keywords to lowercase or uppercase or capitalize them.
|
| 691 |
+
|
| 692 |
+
This means first letter uppercase, rest lowercase.
|
| 693 |
+
|
| 694 |
+
This can be useful e.g. if you highlight Pascal code and want to adapt the
|
| 695 |
+
code to your styleguide.
|
| 696 |
+
|
| 697 |
+
Options accepted:
|
| 698 |
+
|
| 699 |
+
`case` : string
|
| 700 |
+
The casing to convert keywords to. Must be one of ``'lower'``,
|
| 701 |
+
``'upper'`` or ``'capitalize'``. The default is ``'lower'``.
|
| 702 |
+
"""
|
| 703 |
+
|
| 704 |
+
def __init__(self, **options):
|
| 705 |
+
Filter.__init__(self, **options)
|
| 706 |
+
case = get_choice_opt(options, 'case',
|
| 707 |
+
['lower', 'upper', 'capitalize'], 'lower')
|
| 708 |
+
self.convert = getattr(str, case)
|
| 709 |
+
|
| 710 |
+
def filter(self, lexer, stream):
|
| 711 |
+
for ttype, value in stream:
|
| 712 |
+
if ttype in Keyword:
|
| 713 |
+
yield ttype, self.convert(value)
|
| 714 |
+
else:
|
| 715 |
+
yield ttype, value
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
class NameHighlightFilter(Filter):
|
| 719 |
+
"""Highlight a normal Name (and Name.*) token with a different token type.
|
| 720 |
+
|
| 721 |
+
Example::
|
| 722 |
+
|
| 723 |
+
filter = NameHighlightFilter(
|
| 724 |
+
names=['foo', 'bar', 'baz'],
|
| 725 |
+
tokentype=Name.Function,
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
This would highlight the names "foo", "bar" and "baz"
|
| 729 |
+
as functions. `Name.Function` is the default token type.
|
| 730 |
+
|
| 731 |
+
Options accepted:
|
| 732 |
+
|
| 733 |
+
`names` : list of strings
|
| 734 |
+
A list of names that should be given the different token type.
|
| 735 |
+
There is no default.
|
| 736 |
+
`tokentype` : TokenType or string
|
| 737 |
+
A token type or a string containing a token type name that is
|
| 738 |
+
used for highlighting the strings in `names`. The default is
|
| 739 |
+
`Name.Function`.
|
| 740 |
+
"""
|
| 741 |
+
|
| 742 |
+
def __init__(self, **options):
|
| 743 |
+
Filter.__init__(self, **options)
|
| 744 |
+
self.names = set(get_list_opt(options, 'names', []))
|
| 745 |
+
tokentype = options.get('tokentype')
|
| 746 |
+
if tokentype:
|
| 747 |
+
self.tokentype = string_to_tokentype(tokentype)
|
| 748 |
+
else:
|
| 749 |
+
self.tokentype = Name.Function
|
| 750 |
+
|
| 751 |
+
def filter(self, lexer, stream):
|
| 752 |
+
for ttype, value in stream:
|
| 753 |
+
if ttype in Name and value in self.names:
|
| 754 |
+
yield self.tokentype, value
|
| 755 |
+
else:
|
| 756 |
+
yield ttype, value
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
class ErrorToken(Exception):
|
| 760 |
+
pass
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class RaiseOnErrorTokenFilter(Filter):
|
| 764 |
+
"""Raise an exception when the lexer generates an error token.
|
| 765 |
+
|
| 766 |
+
Options accepted:
|
| 767 |
+
|
| 768 |
+
`excclass` : Exception class
|
| 769 |
+
The exception class to raise.
|
| 770 |
+
The default is `pygments.filters.ErrorToken`.
|
| 771 |
+
|
| 772 |
+
.. versionadded:: 0.8
|
| 773 |
+
"""
|
| 774 |
+
|
| 775 |
+
def __init__(self, **options):
|
| 776 |
+
Filter.__init__(self, **options)
|
| 777 |
+
self.exception = options.get('excclass', ErrorToken)
|
| 778 |
+
try:
|
| 779 |
+
# issubclass() will raise TypeError if first argument is not a class
|
| 780 |
+
if not issubclass(self.exception, Exception):
|
| 781 |
+
raise TypeError
|
| 782 |
+
except TypeError:
|
| 783 |
+
raise OptionError('excclass option is not an exception class')
|
| 784 |
+
|
| 785 |
+
def filter(self, lexer, stream):
|
| 786 |
+
for ttype, value in stream:
|
| 787 |
+
if ttype is Error:
|
| 788 |
+
raise self.exception(value)
|
| 789 |
+
yield ttype, value
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
class VisibleWhitespaceFilter(Filter):
|
| 793 |
+
"""Convert tabs, newlines and/or spaces to visible characters.
|
| 794 |
+
|
| 795 |
+
Options accepted:
|
| 796 |
+
|
| 797 |
+
`spaces` : string or bool
|
| 798 |
+
If this is a one-character string, spaces will be replaces by this string.
|
| 799 |
+
If it is another true value, spaces will be replaced by ``·`` (unicode
|
| 800 |
+
MIDDLE DOT). If it is a false value, spaces will not be replaced. The
|
| 801 |
+
default is ``False``.
|
| 802 |
+
`tabs` : string or bool
|
| 803 |
+
The same as for `spaces`, but the default replacement character is ``»``
|
| 804 |
+
(unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value
|
| 805 |
+
is ``False``. Note: this will not work if the `tabsize` option for the
|
| 806 |
+
lexer is nonzero, as tabs will already have been expanded then.
|
| 807 |
+
`tabsize` : int
|
| 808 |
+
If tabs are to be replaced by this filter (see the `tabs` option), this
|
| 809 |
+
is the total number of characters that a tab should be expanded to.
|
| 810 |
+
The default is ``8``.
|
| 811 |
+
`newlines` : string or bool
|
| 812 |
+
The same as for `spaces`, but the default replacement character is ``¶``
|
| 813 |
+
(unicode PILCROW SIGN). The default value is ``False``.
|
| 814 |
+
`wstokentype` : bool
|
| 815 |
+
If true, give whitespace the special `Whitespace` token type. This allows
|
| 816 |
+
styling the visible whitespace differently (e.g. greyed out), but it can
|
| 817 |
+
disrupt background colors. The default is ``True``.
|
| 818 |
+
|
| 819 |
+
.. versionadded:: 0.8
|
| 820 |
+
"""
|
| 821 |
+
|
| 822 |
+
def __init__(self, **options):
|
| 823 |
+
Filter.__init__(self, **options)
|
| 824 |
+
for name, default in [('spaces', '·'),
|
| 825 |
+
('tabs', '»'),
|
| 826 |
+
('newlines', '¶')]:
|
| 827 |
+
opt = options.get(name, False)
|
| 828 |
+
if isinstance(opt, str) and len(opt) == 1:
|
| 829 |
+
setattr(self, name, opt)
|
| 830 |
+
else:
|
| 831 |
+
setattr(self, name, (opt and default or ''))
|
| 832 |
+
tabsize = get_int_opt(options, 'tabsize', 8)
|
| 833 |
+
if self.tabs:
|
| 834 |
+
self.tabs += ' ' * (tabsize - 1)
|
| 835 |
+
if self.newlines:
|
| 836 |
+
self.newlines += '\n'
|
| 837 |
+
self.wstt = get_bool_opt(options, 'wstokentype', True)
|
| 838 |
+
|
| 839 |
+
def filter(self, lexer, stream):
|
| 840 |
+
if self.wstt:
|
| 841 |
+
spaces = self.spaces or ' '
|
| 842 |
+
tabs = self.tabs or '\t'
|
| 843 |
+
newlines = self.newlines or '\n'
|
| 844 |
+
regex = re.compile(r'\s')
|
| 845 |
+
|
| 846 |
+
def replacefunc(wschar):
|
| 847 |
+
if wschar == ' ':
|
| 848 |
+
return spaces
|
| 849 |
+
elif wschar == '\t':
|
| 850 |
+
return tabs
|
| 851 |
+
elif wschar == '\n':
|
| 852 |
+
return newlines
|
| 853 |
+
return wschar
|
| 854 |
+
|
| 855 |
+
for ttype, value in stream:
|
| 856 |
+
yield from _replace_special(ttype, value, regex, Whitespace,
|
| 857 |
+
replacefunc)
|
| 858 |
+
else:
|
| 859 |
+
spaces, tabs, newlines = self.spaces, self.tabs, self.newlines
|
| 860 |
+
# simpler processing
|
| 861 |
+
for ttype, value in stream:
|
| 862 |
+
if spaces:
|
| 863 |
+
value = value.replace(' ', spaces)
|
| 864 |
+
if tabs:
|
| 865 |
+
value = value.replace('\t', tabs)
|
| 866 |
+
if newlines:
|
| 867 |
+
value = value.replace('\n', newlines)
|
| 868 |
+
yield ttype, value
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
class GobbleFilter(Filter):
|
| 872 |
+
"""Gobble source code lines (eats initial characters).
|
| 873 |
+
|
| 874 |
+
This filter drops the first ``n`` characters off every line of code. This
|
| 875 |
+
may be useful when the source code fed to the lexer is indented by a fixed
|
| 876 |
+
amount of space that isn't desired in the output.
|
| 877 |
+
|
| 878 |
+
Options accepted:
|
| 879 |
+
|
| 880 |
+
`n` : int
|
| 881 |
+
The number of characters to gobble.
|
| 882 |
+
|
| 883 |
+
.. versionadded:: 1.2
|
| 884 |
+
"""
|
| 885 |
+
def __init__(self, **options):
|
| 886 |
+
Filter.__init__(self, **options)
|
| 887 |
+
self.n = get_int_opt(options, 'n', 0)
|
| 888 |
+
|
| 889 |
+
def gobble(self, value, left):
|
| 890 |
+
if left < len(value):
|
| 891 |
+
return value[left:], 0
|
| 892 |
+
else:
|
| 893 |
+
return '', left - len(value)
|
| 894 |
+
|
| 895 |
+
def filter(self, lexer, stream):
|
| 896 |
+
n = self.n
|
| 897 |
+
left = n # How many characters left to gobble.
|
| 898 |
+
for ttype, value in stream:
|
| 899 |
+
# Remove ``left`` tokens from first line, ``n`` from all others.
|
| 900 |
+
parts = value.split('\n')
|
| 901 |
+
(parts[0], left) = self.gobble(parts[0], left)
|
| 902 |
+
for i in range(1, len(parts)):
|
| 903 |
+
(parts[i], left) = self.gobble(parts[i], n)
|
| 904 |
+
value = '\n'.join(parts)
|
| 905 |
+
|
| 906 |
+
if value != '':
|
| 907 |
+
yield ttype, value
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
class TokenMergeFilter(Filter):
|
| 911 |
+
"""Merge consecutive tokens with the same token type in the output stream.
|
| 912 |
+
|
| 913 |
+
.. versionadded:: 1.2
|
| 914 |
+
"""
|
| 915 |
+
def __init__(self, **options):
|
| 916 |
+
Filter.__init__(self, **options)
|
| 917 |
+
|
| 918 |
+
def filter(self, lexer, stream):
|
| 919 |
+
current_type = None
|
| 920 |
+
current_value = None
|
| 921 |
+
for ttype, value in stream:
|
| 922 |
+
if ttype is current_type:
|
| 923 |
+
current_value += value
|
| 924 |
+
else:
|
| 925 |
+
if current_type is not None:
|
| 926 |
+
yield current_type, current_value
|
| 927 |
+
current_type = ttype
|
| 928 |
+
current_value = value
|
| 929 |
+
if current_type is not None:
|
| 930 |
+
yield current_type, current_value
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
FILTERS = {
|
| 934 |
+
'codetagify': CodeTagFilter,
|
| 935 |
+
'keywordcase': KeywordCaseFilter,
|
| 936 |
+
'highlight': NameHighlightFilter,
|
| 937 |
+
'raiseonerror': RaiseOnErrorTokenFilter,
|
| 938 |
+
'whitespace': VisibleWhitespaceFilter,
|
| 939 |
+
'gobble': GobbleFilter,
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.formatters
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Pygments formatters.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
import sys
|
| 13 |
+
import types
|
| 14 |
+
import fnmatch
|
| 15 |
+
from os.path import basename
|
| 16 |
+
|
| 17 |
+
from pygments.formatters._mapping import FORMATTERS
|
| 18 |
+
from pygments.plugin import find_plugin_formatters
|
| 19 |
+
from pygments.util import ClassNotFound
|
| 20 |
+
|
| 21 |
+
__all__ = ['get_formatter_by_name', 'get_formatter_for_filename',
|
| 22 |
+
'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS)
|
| 23 |
+
|
| 24 |
+
_formatter_cache = {} # classes by name
|
| 25 |
+
_pattern_cache = {}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _fn_matches(fn, glob):
|
| 29 |
+
"""Return whether the supplied file name fn matches pattern filename."""
|
| 30 |
+
if glob not in _pattern_cache:
|
| 31 |
+
pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))
|
| 32 |
+
return pattern.match(fn)
|
| 33 |
+
return _pattern_cache[glob].match(fn)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _load_formatters(module_name):
|
| 37 |
+
"""Load a formatter (and all others in the module too)."""
|
| 38 |
+
mod = __import__(module_name, None, None, ['__all__'])
|
| 39 |
+
for formatter_name in mod.__all__:
|
| 40 |
+
cls = getattr(mod, formatter_name)
|
| 41 |
+
_formatter_cache[cls.name] = cls
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_all_formatters():
|
| 45 |
+
"""Return a generator for all formatter classes."""
|
| 46 |
+
# NB: this returns formatter classes, not info like get_all_lexers().
|
| 47 |
+
for info in FORMATTERS.values():
|
| 48 |
+
if info[1] not in _formatter_cache:
|
| 49 |
+
_load_formatters(info[0])
|
| 50 |
+
yield _formatter_cache[info[1]]
|
| 51 |
+
for _, formatter in find_plugin_formatters():
|
| 52 |
+
yield formatter
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def find_formatter_class(alias):
|
| 56 |
+
"""Lookup a formatter by alias.
|
| 57 |
+
|
| 58 |
+
Returns None if not found.
|
| 59 |
+
"""
|
| 60 |
+
for module_name, name, aliases, _, _ in FORMATTERS.values():
|
| 61 |
+
if alias in aliases:
|
| 62 |
+
if name not in _formatter_cache:
|
| 63 |
+
_load_formatters(module_name)
|
| 64 |
+
return _formatter_cache[name]
|
| 65 |
+
for _, cls in find_plugin_formatters():
|
| 66 |
+
if alias in cls.aliases:
|
| 67 |
+
return cls
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_formatter_by_name(_alias, **options):
|
| 71 |
+
"""
|
| 72 |
+
Return an instance of a :class:`.Formatter` subclass that has `alias` in its
|
| 73 |
+
aliases list. The formatter is given the `options` at its instantiation.
|
| 74 |
+
|
| 75 |
+
Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that
|
| 76 |
+
alias is found.
|
| 77 |
+
"""
|
| 78 |
+
cls = find_formatter_class(_alias)
|
| 79 |
+
if cls is None:
|
| 80 |
+
raise ClassNotFound(f"no formatter found for name {_alias!r}")
|
| 81 |
+
return cls(**options)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def load_formatter_from_file(filename, formattername="CustomFormatter", **options):
|
| 85 |
+
"""
|
| 86 |
+
Return a `Formatter` subclass instance loaded from the provided file, relative
|
| 87 |
+
to the current directory.
|
| 88 |
+
|
| 89 |
+
The file is expected to contain a Formatter class named ``formattername``
|
| 90 |
+
(by default, CustomFormatter). Users should be very careful with the input, because
|
| 91 |
+
this method is equivalent to running ``eval()`` on the input file. The formatter is
|
| 92 |
+
given the `options` at its instantiation.
|
| 93 |
+
|
| 94 |
+
:exc:`pygments.util.ClassNotFound` is raised if there are any errors loading
|
| 95 |
+
the formatter.
|
| 96 |
+
|
| 97 |
+
.. versionadded:: 2.2
|
| 98 |
+
"""
|
| 99 |
+
try:
|
| 100 |
+
# This empty dict will contain the namespace for the exec'd file
|
| 101 |
+
custom_namespace = {}
|
| 102 |
+
with open(filename, 'rb') as f:
|
| 103 |
+
exec(f.read(), custom_namespace)
|
| 104 |
+
# Retrieve the class `formattername` from that namespace
|
| 105 |
+
if formattername not in custom_namespace:
|
| 106 |
+
raise ClassNotFound(f'no valid {formattername} class found in {filename}')
|
| 107 |
+
formatter_class = custom_namespace[formattername]
|
| 108 |
+
# And finally instantiate it with the options
|
| 109 |
+
return formatter_class(**options)
|
| 110 |
+
except OSError as err:
|
| 111 |
+
raise ClassNotFound(f'cannot read {filename}: {err}')
|
| 112 |
+
except ClassNotFound:
|
| 113 |
+
raise
|
| 114 |
+
except Exception as err:
|
| 115 |
+
raise ClassNotFound(f'error when loading custom formatter: {err}')
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def get_formatter_for_filename(fn, **options):
|
| 119 |
+
"""
|
| 120 |
+
Return a :class:`.Formatter` subclass instance that has a filename pattern
|
| 121 |
+
matching `fn`. The formatter is given the `options` at its instantiation.
|
| 122 |
+
|
| 123 |
+
Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename
|
| 124 |
+
is found.
|
| 125 |
+
"""
|
| 126 |
+
fn = basename(fn)
|
| 127 |
+
for modname, name, _, filenames, _ in FORMATTERS.values():
|
| 128 |
+
for filename in filenames:
|
| 129 |
+
if _fn_matches(fn, filename):
|
| 130 |
+
if name not in _formatter_cache:
|
| 131 |
+
_load_formatters(modname)
|
| 132 |
+
return _formatter_cache[name](**options)
|
| 133 |
+
for _name, cls in find_plugin_formatters():
|
| 134 |
+
for filename in cls.filenames:
|
| 135 |
+
if _fn_matches(fn, filename):
|
| 136 |
+
return cls(**options)
|
| 137 |
+
raise ClassNotFound(f"no formatter found for file name {fn!r}")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class _automodule(types.ModuleType):
|
| 141 |
+
"""Automatically import formatters."""
|
| 142 |
+
|
| 143 |
+
def __getattr__(self, name):
|
| 144 |
+
info = FORMATTERS.get(name)
|
| 145 |
+
if info:
|
| 146 |
+
_load_formatters(info[0])
|
| 147 |
+
cls = _formatter_cache[info[1]]
|
| 148 |
+
setattr(self, name, cls)
|
| 149 |
+
return cls
|
| 150 |
+
raise AttributeError(name)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
oldmod = sys.modules[__name__]
|
| 154 |
+
newmod = _automodule(__name__)
|
| 155 |
+
newmod.__dict__.update(oldmod.__dict__)
|
| 156 |
+
sys.modules[__name__] = newmod
|
| 157 |
+
del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types
|
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/formatters/_mapping.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Automatically generated by scripts/gen_mapfiles.py.
|
| 2 |
+
# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead.
|
| 3 |
+
|
| 4 |
+
FORMATTERS = {
|
| 5 |
+
'BBCodeFormatter': ('pygments.formatters.bbcode', 'BBCode', ('bbcode', 'bb'), (), 'Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.'),
|
| 6 |
+
'BmpImageFormatter': ('pygments.formatters.img', 'img_bmp', ('bmp', 'bitmap'), ('*.bmp',), 'Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
|
| 7 |
+
'GifImageFormatter': ('pygments.formatters.img', 'img_gif', ('gif',), ('*.gif',), 'Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
|
| 8 |
+
'GroffFormatter': ('pygments.formatters.groff', 'groff', ('groff', 'troff', 'roff'), (), 'Format tokens with groff escapes to change their color and font style.'),
|
| 9 |
+
'HtmlFormatter': ('pygments.formatters.html', 'HTML', ('html',), ('*.html', '*.htm'), "Format tokens as HTML 4 ``<span>`` tags. By default, the content is enclosed in a ``<pre>`` tag, itself wrapped in a ``<div>`` tag (but see the `nowrap` option). The ``<div>``'s CSS class can be set by the `cssclass` option."),
|
| 10 |
+
'IRCFormatter': ('pygments.formatters.irc', 'IRC', ('irc', 'IRC'), (), 'Format tokens with IRC color sequences'),
|
| 11 |
+
'ImageFormatter': ('pygments.formatters.img', 'img', ('img', 'IMG', 'png'), ('*.png',), 'Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
|
| 12 |
+
'JpgImageFormatter': ('pygments.formatters.img', 'img_jpg', ('jpg', 'jpeg'), ('*.jpg',), 'Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
|
| 13 |
+
'LatexFormatter': ('pygments.formatters.latex', 'LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'),
|
| 14 |
+
'NullFormatter': ('pygments.formatters.other', 'Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'),
|
| 15 |
+
'PangoMarkupFormatter': ('pygments.formatters.pangomarkup', 'Pango Markup', ('pango', 'pangomarkup'), (), 'Format tokens as Pango Markup code. It can then be rendered to an SVG.'),
|
| 16 |
+
'RawTokenFormatter': ('pygments.formatters.other', 'Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'),
|
| 17 |
+
'RtfFormatter': ('pygments.formatters.rtf', 'RTF', ('rtf',), ('*.rtf',), 'Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents.'),
|
| 18 |
+
'SvgFormatter': ('pygments.formatters.svg', 'SVG', ('svg',), ('*.svg',), 'Format tokens as an SVG graphics file. This formatter is still experimental. Each line of code is a ``<text>`` element with explicit ``x`` and ``y`` coordinates containing ``<tspan>`` elements with the individual token styles.'),
|
| 19 |
+
'Terminal256Formatter': ('pygments.formatters.terminal256', 'Terminal256', ('terminal256', 'console256', '256'), (), 'Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),
|
| 20 |
+
'TerminalFormatter': ('pygments.formatters.terminal', 'Terminal', ('terminal', 'console'), (), 'Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.'),
|
| 21 |
+
'TerminalTrueColorFormatter': ('pygments.formatters.terminal256', 'TerminalTrueColor', ('terminal16m', 'console16m', '16m'), (), 'Format tokens with ANSI color sequences, for output in a true-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),
|
| 22 |
+
'TestcaseFormatter': ('pygments.formatters.other', 'Testcase', ('testcase',), (), 'Format tokens as appropriate for a new testcase.'),
|
| 23 |
+
}
|
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/formatters/bbcode.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.formatters.bbcode
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
BBcode formatter.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from pygments.formatter import Formatter
|
| 13 |
+
from pygments.util import get_bool_opt
|
| 14 |
+
|
| 15 |
+
__all__ = ['BBCodeFormatter']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class BBCodeFormatter(Formatter):
|
| 19 |
+
"""
|
| 20 |
+
Format tokens with BBcodes. These formatting codes are used by many
|
| 21 |
+
bulletin boards, so you can highlight your sourcecode with pygments before
|
| 22 |
+
posting it there.
|
| 23 |
+
|
| 24 |
+
This formatter has no support for background colors and borders, as there
|
| 25 |
+
are no common BBcode tags for that.
|
| 26 |
+
|
| 27 |
+
Some board systems (e.g. phpBB) don't support colors in their [code] tag,
|
| 28 |
+
so you can't use the highlighting together with that tag.
|
| 29 |
+
Text in a [code] tag usually is shown with a monospace font (which this
|
| 30 |
+
formatter can do with the ``monofont`` option) and no spaces (which you
|
| 31 |
+
need for indentation) are removed.
|
| 32 |
+
|
| 33 |
+
Additional options accepted:
|
| 34 |
+
|
| 35 |
+
`style`
|
| 36 |
+
The style to use, can be a string or a Style subclass (default:
|
| 37 |
+
``'default'``).
|
| 38 |
+
|
| 39 |
+
`codetag`
|
| 40 |
+
If set to true, put the output into ``[code]`` tags (default:
|
| 41 |
+
``false``)
|
| 42 |
+
|
| 43 |
+
`monofont`
|
| 44 |
+
If set to true, add a tag to show the code with a monospace font
|
| 45 |
+
(default: ``false``).
|
| 46 |
+
"""
|
| 47 |
+
name = 'BBCode'
|
| 48 |
+
aliases = ['bbcode', 'bb']
|
| 49 |
+
filenames = []
|
| 50 |
+
|
| 51 |
+
def __init__(self, **options):
|
| 52 |
+
Formatter.__init__(self, **options)
|
| 53 |
+
self._code = get_bool_opt(options, 'codetag', False)
|
| 54 |
+
self._mono = get_bool_opt(options, 'monofont', False)
|
| 55 |
+
|
| 56 |
+
self.styles = {}
|
| 57 |
+
self._make_styles()
|
| 58 |
+
|
| 59 |
+
def _make_styles(self):
|
| 60 |
+
for ttype, ndef in self.style:
|
| 61 |
+
start = end = ''
|
| 62 |
+
if ndef['color']:
|
| 63 |
+
start += '[color=#{}]'.format(ndef['color'])
|
| 64 |
+
end = '[/color]' + end
|
| 65 |
+
if ndef['bold']:
|
| 66 |
+
start += '[b]'
|
| 67 |
+
end = '[/b]' + end
|
| 68 |
+
if ndef['italic']:
|
| 69 |
+
start += '[i]'
|
| 70 |
+
end = '[/i]' + end
|
| 71 |
+
if ndef['underline']:
|
| 72 |
+
start += '[u]'
|
| 73 |
+
end = '[/u]' + end
|
| 74 |
+
# there are no common BBcodes for background-color and border
|
| 75 |
+
|
| 76 |
+
self.styles[ttype] = start, end
|
| 77 |
+
|
| 78 |
+
def format_unencoded(self, tokensource, outfile):
|
| 79 |
+
if self._code:
|
| 80 |
+
outfile.write('[code]')
|
| 81 |
+
if self._mono:
|
| 82 |
+
outfile.write('[font=monospace]')
|
| 83 |
+
|
| 84 |
+
lastval = ''
|
| 85 |
+
lasttype = None
|
| 86 |
+
|
| 87 |
+
for ttype, value in tokensource:
|
| 88 |
+
while ttype not in self.styles:
|
| 89 |
+
ttype = ttype.parent
|
| 90 |
+
if ttype == lasttype:
|
| 91 |
+
lastval += value
|
| 92 |
+
else:
|
| 93 |
+
if lastval:
|
| 94 |
+
start, end = self.styles[lasttype]
|
| 95 |
+
outfile.write(''.join((start, lastval, end)))
|
| 96 |
+
lastval = value
|
| 97 |
+
lasttype = ttype
|
| 98 |
+
|
| 99 |
+
if lastval:
|
| 100 |
+
start, end = self.styles[lasttype]
|
| 101 |
+
outfile.write(''.join((start, lastval, end)))
|
| 102 |
+
|
| 103 |
+
if self._mono:
|
| 104 |
+
outfile.write('[/font]')
|
| 105 |
+
if self._code:
|
| 106 |
+
outfile.write('[/code]')
|
| 107 |
+
if self._code or self._mono:
|
| 108 |
+
outfile.write('\n')
|