Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/METADATAAdded+324
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/WHEELAdded+5
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/entry_points.txtAdded+7
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/licenses/LICENSEAdded+201
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/top_level.txtAdded+1
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/__init__.pyAdded+1717
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_buckets.pyAdded+1193
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_commit_api.pyAdded+976
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_commit_scheduler.pyAdded+353
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_dataset_viewer.pyAdded+172
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_eval_results.pyAdded+211
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_inference_endpoints.pyAdded+418
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_jobs_api.pyAdded+410
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_local_folder.pyAdded+473
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_login.pyAdded+494
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_oauth.pyAdded+460
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_snapshot_download.pyAdded+471
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_space_api.pyAdded+251
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_tensorboard_logger.pyAdded+189
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_upload_large_folder.pyAdded+766
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_webhooks_payload.pyAdded+136
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_webhooks_server.pyAdded+376
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/auth.pyAdded+165
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/buckets.pyAdded+1082
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/cache.pyAdded+812
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/collections.pyAdded+331
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/datasets.pyAdded+175
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/deprecated_cli.pyAdded+35
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/discussions.pyAdded+595
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/download.pyAdded+224
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/extensions.pyAdded+620
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/hf.pyAdded+127
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/inference_endpoints.pyAdded+463
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/jobs.pyAdded+1150
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/lfs.pyAdded+175
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/models.pyAdded+133
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/papers.pyAdded+203
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/repo_files.pyAdded+86
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/repos.pyAdded+524
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/skills.pyAdded+446
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/spaces.pyAdded+437
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/system.pyAdded+28
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/upload.pyAdded+300
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/upload_large_folder.pyAdded+130
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/webhooks.pyAdded+310
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/community.pyAdded+363
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/constants.pyAdded+291
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/dataclasses.pyAdded+684
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/errors.pyAdded+473
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/fastai_utils.pyAdded+414
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324Metadata-Version: 2.4Name: huggingface_hubVersion: 1.10.1Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hubHome-page: https://github.com/huggingface/huggingface_hubAuthor: Hugging Face, Inc.Author-email: julien@huggingface.coLicense: Apache-2.0Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-modelsClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: EducationClassifier: Intended Audience :: Science/ResearchClassifier: License :: OSI Approved :: Apache Software LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Scientific/Engineering :: Artificial IntelligenceRequires-Python: >=3.10.0Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: filelock>=3.10.0Requires-Dist: fsspec>=2023.5.0Requires-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"Requires-Dist: httpx<1,>=0.23.0Requires-Dist: packaging>=20.9Requires-Dist: pyyaml>=5.1Requires-Dist: tqdm>=4.42.1Requires-Dist: typerRequires-Dist: typing-extensions>=4.1.0Provides-Extra: oauthRequires-Dist: authlib>=1.3.2; extra == "oauth"Requires-Dist: fastapi; extra == "oauth"Requires-Dist: httpx; extra == "oauth"Requires-Dist: itsdangerous; extra == "oauth"Provides-Extra: torchRequires-Dist: torch; extra == "torch"Requires-Dist: safetensors[torch]; extra == "torch"Provides-Extra: fastaiRequires-Dist: toml; extra == "fastai"Requires-Dist: fastai>=2.4; extra == "fastai"Requires-Dist: fastcore>=1.3.27; extra == "fastai"Provides-Extra: hf-xetRequires-Dist: hf-xet<2.0.0,>=1.4.3; extra == "hf-xet"Provides-Extra: mcpRequires-Dist: mcp>=1.8.0; extra == "mcp"Provides-Extra: testingRequires-Dist: authlib>=1.3.2; extra == "testing"Requires-Dist: fastapi; extra == "testing"Requires-Dist: httpx; extra == "testing"Requires-Dist: itsdangerous; extra == "testing"Requires-Dist: jedi; extra == "testing"Requires-Dist: Jinja2; extra == "testing"Requires-Dist: pytest>=8.4.2; extra == "testing"Requires-Dist: pytest-cov; extra == "testing"Requires-Dist: pytest-env; extra == "testing"Requires-Dist: pytest-xdist; extra == "testing"Requires-Dist: pytest-vcr; extra == "testing"Requires-Dist: pytest-asyncio; extra == "testing"Requires-Dist: pytest-rerunfailures<16.0; extra == "testing"Requires-Dist: pytest-mock; extra == "testing"Requires-Dist: urllib3<2.0; extra == "testing"Requires-Dist: soundfile; extra == "testing"Requires-Dist: Pillow; extra == "testing"Requires-Dist: numpy; extra == "testing"Requires-Dist: duckdb; extra == "testing"Requires-Dist: fastapi; extra == "testing"Provides-Extra: gradioRequires-Dist: gradio>=5.0.0; extra == "gradio"Requires-Dist: requests; extra == "gradio"Provides-Extra: typingRequires-Dist: typing-extensions>=4.8.0; extra == "typing"Requires-Dist: types-PyYAML; extra == "typing"Requires-Dist: types-simplejson; extra == "typing"Requires-Dist: types-toml; extra == "typing"Requires-Dist: types-tqdm; extra == "typing"Requires-Dist: types-urllib3; extra == "typing"Provides-Extra: qualityRequires-Dist: ruff>=0.9.0; extra == "quality"Requires-Dist: mypy==1.15.0; extra == "quality"Requires-Dist: libcst>=1.4.0; extra == "quality"Requires-Dist: ty; extra == "quality"Provides-Extra: allRequires-Dist: authlib>=1.3.2; extra == "all"Requires-Dist: fastapi; extra == "all"Requires-Dist: httpx; extra == "all"Requires-Dist: itsdangerous; extra == "all"Requires-Dist: jedi; extra == "all"Requires-Dist: Jinja2; extra == "all"Requires-Dist: pytest>=8.4.2; extra == "all"Requires-Dist: pytest-cov; extra == "all"Requires-Dist: pytest-env; extra == "all"Requires-Dist: pytest-xdist; extra == "all"Requires-Dist: pytest-vcr; extra == "all"Requires-Dist: pytest-asyncio; extra == "all"Requires-Dist: pytest-rerunfailures<16.0; extra == "all"Requires-Dist: pytest-mock; extra == "all"Requires-Dist: urllib3<2.0; extra == "all"Requires-Dist: soundfile; extra == "all"Requires-Dist: Pillow; extra == "all"Requires-Dist: numpy; extra == "all"Requires-Dist: duckdb; extra == "all"Requires-Dist: fastapi; extra == "all"Requires-Dist: ruff>=0.9.0; extra == "all"Requires-Dist: mypy==1.15.0; extra == "all"Requires-Dist: libcst>=1.4.0; extra == "all"Requires-Dist: ty; extra == "all"Requires-Dist: typing-extensions>=4.8.0; extra == "all"Requires-Dist: types-PyYAML; extra == "all"Requires-Dist: types-simplejson; extra == "all"Requires-Dist: types-toml; extra == "all"Requires-Dist: types-tqdm; extra == "all"Requires-Dist: types-urllib3; extra == "all"Provides-Extra: devRequires-Dist: authlib>=1.3.2; extra == "dev"Requires-Dist: fastapi; extra == "dev"Requires-Dist: httpx; extra == "dev"Requires-Dist: itsdangerous; extra == "dev"Requires-Dist: jedi; extra == "dev"Requires-Dist: Jinja2; extra == "dev"Requires-Dist: pytest>=8.4.2; extra == "dev"Requires-Dist: pytest-cov; extra == "dev"Requires-Dist: pytest-env; extra == "dev"Requires-Dist: pytest-xdist; extra == "dev"Requires-Dist: pytest-vcr; extra == "dev"Requires-Dist: pytest-asyncio; extra == "dev"Requires-Dist: pytest-rerunfailures<16.0; extra == "dev"Requires-Dist: pytest-mock; extra == "dev"Requires-Dist: urllib3<2.0; extra == "dev"Requires-Dist: soundfile; extra == "dev"Requires-Dist: Pillow; extra == "dev"Requires-Dist: numpy; extra == "dev"Requires-Dist: duckdb; extra == "dev"Requires-Dist: fastapi; extra == "dev"Requires-Dist: ruff>=0.9.0; extra == "dev"Requires-Dist: mypy==1.15.0; extra == "dev"Requires-Dist: libcst>=1.4.0; extra == "dev"Requires-Dist: ty; extra == "dev"Requires-Dist: typing-extensions>=4.8.0; extra == "dev"Requires-Dist: types-PyYAML; extra == "dev"Requires-Dist: types-simplejson; extra == "dev"Requires-Dist: types-toml; extra == "dev"Requires-Dist: types-tqdm; extra == "dev"Requires-Dist: types-urllib3; extra == "dev"Dynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: keywordsDynamic: licenseDynamic: license-fileDynamic: provides-extraDynamic: requires-distDynamic: requires-pythonDynamic: summary
<p align="center"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub-dark.svg"> <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg"> <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%"> </picture> <br/> <br/></p>
<p align="center"> <i>The official Python client for the Huggingface Hub.</i></p>
<p align="center"> <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> <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> <a href="https://github.com/huggingface/huggingface_hub"><img alt="PyPi version" src="https://img.shields.io/pypi/pyversions/huggingface_hub.svg"></a> <a href="https://pypi.org/project/huggingface-hub"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/huggingface_hub"></a> <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></p>
<h4 align="center"> <p> <b>English</b> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_de.md">Deutsch</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_fr.md">Français</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_hi.md">हिंदी</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_ko.md">한국어</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_cn.md">中文 (简体)</a> <p></h4>
---
**Documentation**: <a href="https://hf.co/docs/huggingface_hub" target="_blank">https://hf.co/docs/huggingface_hub</a>
**Source Code**: <a href="https://github.com/huggingface/huggingface_hub" target="_blank">https://github.com/huggingface/huggingface_hub</a>
---
## Welcome to the huggingface_hub library
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.
## Key features
- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub.- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub.- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository).- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models.- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces.- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models.- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments.
## Installation
Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/):
```bashpip install huggingface_hub```
If you prefer, you can also install it with [conda](https://huggingface.co/docs/huggingface_hub/en/installation#install-with-conda).
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:
```bashpip install "huggingface_hub[mcp]"```
To learn more installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation).
## Quick start
### Download files
Download a single file
```pyfrom huggingface_hub import hf_hub_download
hf_hub_download(repo_id="tiiuae/falcon-7b-instruct", filename="config.json")```
Or an entire repository
```pyfrom huggingface_hub import snapshot_download
snapshot_download("stabilityai/stable-diffusion-2-1")```
Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache).
### Login
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:
```bashhf auth login# or using an environment variablehf auth login --token $HUGGINGFACE_TOKEN```
### Create a repository
```pyfrom huggingface_hub import create_repo
create_repo(repo_id="super-cool-model")```
### Upload files
Upload a single file
```pyfrom huggingface_hub import upload_file
upload_file( path_or_fileobj="/home/lysandre/dummy-test/README.md", path_in_repo="README.md", repo_id="lysandre/test-model",)```
Or an entire folder
```pyfrom huggingface_hub import upload_folder
upload_folder( folder_path="/path/to/local/space", repo_id="username/my-cool-space", repo_type="space",)```
For details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload).
## Integrating to the Hub.
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).
The advantages are:
- Free model or dataset hosting for libraries and their users.- Built-in file versioning, even with very large files, thanks to a git-based approach.- In-browser widgets to play with the uploaded models.- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable.- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe.- Usage stats and more features to come.
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.
## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️
Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community.Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community.We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarizehow to get started to contribute to this repository.12345Wheel-Version: 1.0Generator: setuptools (79.0.1)Root-Is-Purelib: trueTag: py3-none-any
1234567[console_scripts]hf = huggingface_hub.cli.hf:mainhuggingface-cli = huggingface_hub.cli.deprecated_cli:maintiny-agents = huggingface_hub.inference._mcp.cli:app
[fsspec.specs]hf = huggingface_hub.HfFileSystem123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1huggingface_hub1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717# Copyright 2020 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# ***********# `huggingface_hub` init has 2 modes:# - Normal usage:# If imported to use it, all modules and functions are lazy-loaded. This means# they exist at top level in module but are imported only the first time they are# used. This way, `from huggingface_hub import something` will import `something`# quickly without the hassle of importing all the features from `huggingface_hub`.# - Static check:# If statically analyzed, all modules and functions are loaded normally. This way# static typing check works properly as well as autocomplete in text editors and# IDEs.## The static model imports are done inside the `if TYPE_CHECKING:` statement at# the bottom of this file. Since module/functions imports are duplicated, it is# mandatory to make sure to add them twice when adding one. This is checked in the# `make quality` command.## To update the static imports, please run the following command and commit the changes.# ```# # Use script# python utils/check_static_imports.py --update-file## # Or run style on codebase# make style# ```## ***********# Lazy loader vendored from https://github.com/scientific-python/lazy_loaderimport importlibimport osimport sysfrom typing import TYPE_CHECKING
__version__ = "1.10.1"
# Alphabetical order of definitions is ensured in tests# WARNING: any comment added in this dictionary definition will be lost when# re-generating the file !_SUBMOD_ATTRS = { "_buckets": [ "BucketFile", "BucketFileMetadata", "BucketFolder", "BucketInfo", "BucketUrl", "SyncOperation", "SyncPlan", ], "_commit_scheduler": [ "CommitScheduler", ], "_eval_results": [ "EvalResultEntry", "eval_result_entries_to_yaml", "parse_eval_result_entries", ], "_inference_endpoints": [ "InferenceEndpoint", "InferenceEndpointError", "InferenceEndpointStatus", "InferenceEndpointTimeoutError", "InferenceEndpointType", ], "_jobs_api": [ "JobAccelerator", "JobHardware", "JobInfo", "JobOwner", "JobStage", "JobStatus", ], "_login": [ "auth_list", "auth_switch", "interpreter_login", "login", "logout", "notebook_login", ], "_oauth": [ "OAuthInfo", "OAuthOrgInfo", "OAuthUserInfo", "attach_huggingface_oauth", "parse_huggingface_oauth", ], "_snapshot_download": [ "snapshot_download", ], "_space_api": [ "SpaceHardware", "SpaceRuntime", "SpaceStage", "SpaceStorage", "SpaceVariable", "Volume", ], "_tensorboard_logger": [ "HFSummaryWriter", ], "_webhooks_payload": [ "WebhookPayload", "WebhookPayloadComment", "WebhookPayloadDiscussion", "WebhookPayloadDiscussionChanges", "WebhookPayloadEvent", "WebhookPayloadMovedTo", "WebhookPayloadRepo", "WebhookPayloadUrl", "WebhookPayloadWebhook", ], "_webhooks_server": [ "WebhooksServer", "webhook_endpoint", ], "cli._cli_utils": [ "check_cli_update", "typer_factory", ], "community": [ "Discussion", "DiscussionComment", "DiscussionCommit", "DiscussionEvent", "DiscussionStatusChange", "DiscussionTitleChange", "DiscussionWithDetails", ], "constants": [ "CONFIG_NAME", "FLAX_WEIGHTS_NAME", "HUGGINGFACE_CO_URL_HOME", "HUGGINGFACE_CO_URL_TEMPLATE", "PYTORCH_WEIGHTS_NAME", "REPO_TYPE_DATASET", "REPO_TYPE_MODEL", "REPO_TYPE_SPACE", "TF2_WEIGHTS_NAME", "TF_WEIGHTS_NAME", "is_offline_mode", ], "fastai_utils": [ "_save_pretrained_fastai", "from_pretrained_fastai", "push_to_hub_fastai", ], "file_download": [ "DryRunFileInfo", "HfFileMetadata", "_CACHED_NO_EXIST", "get_hf_file_metadata", "hf_hub_download", "hf_hub_url", "try_to_load_from_cache", ], "hf_api": [ "Collection", "CollectionItem", "CommitInfo", "CommitOperation", "CommitOperationAdd", "CommitOperationCopy", "CommitOperationDelete", "DatasetInfo", "DatasetLeaderboardEntry", "GitCommitInfo", "GitRefInfo", "GitRefs", "HfApi", "KernelInfo", "ModelInfo", "Organization", "RepoFile", "RepoFolder", "RepoUrl", "SpaceInfo", "User", "UserLikes", "WebhookInfo", "WebhookWatchedItem", "accept_access_request", "add_collection_item", "add_space_secret", "add_space_variable", "auth_check", "batch_bucket_files", "bucket_info", "cancel_access_request", "cancel_job", "change_discussion_status", "comment_discussion", "copy_files", "create_branch", "create_bucket", "create_collection", "create_commit", "create_discussion", "create_inference_endpoint", "create_inference_endpoint_from_catalog", "create_pull_request", "create_repo", "create_scheduled_job", "create_scheduled_uv_job", "create_tag", "create_webhook", "dataset_info", "delete_branch", "delete_bucket", "delete_collection", "delete_collection_item", "delete_file", "delete_folder", "delete_inference_endpoint", "delete_repo", "delete_scheduled_job", "delete_space_secret", "delete_space_storage", "delete_space_variable", "delete_space_volumes", "delete_tag", "delete_webhook", "disable_space_dev_mode", "disable_webhook", "download_bucket_files", "duplicate_repo", "duplicate_space", "edit_discussion_comment", "enable_space_dev_mode", "enable_webhook", "fetch_job_logs", "fetch_job_metrics", "file_exists", "get_bucket_file_metadata", "get_bucket_paths_info", "get_collection", "get_dataset_leaderboard", "get_dataset_tags", "get_discussion_details", "get_full_repo_name", "get_inference_endpoint", "get_local_safetensors_metadata", "get_model_tags", "get_organization_overview", "get_paths_info", "get_repo_discussions", "get_safetensors_metadata", "get_space_runtime", "get_space_variables", "get_user_overview", "get_webhook", "grant_access", "inspect_job", "inspect_scheduled_job", "kernel_info", "list_accepted_access_requests", "list_bucket_tree", "list_buckets", "list_collections", "list_daily_papers", "list_dataset_parquet_files", "list_datasets", "list_inference_catalog", "list_inference_endpoints", "list_jobs", "list_jobs_hardware", "list_lfs_files", "list_liked_repos", "list_models", "list_organization_followers", "list_organization_members", "list_papers", "list_pending_access_requests", "list_rejected_access_requests", "list_repo_commits", "list_repo_files", "list_repo_likers", "list_repo_refs", "list_repo_tree", "list_spaces", "list_user_followers", "list_user_following", "list_webhooks", "merge_pull_request", "model_info", "move_bucket", "move_repo", "paper_info", "parse_local_safetensors_file_metadata", "parse_safetensors_file_metadata", "pause_inference_endpoint", "pause_space", "permanently_delete_lfs_files", "preupload_lfs_files", "read_paper", "reject_access_request", "rename_discussion", "repo_exists", "repo_info", "repo_type_and_id_from_hf_id", "request_space_hardware", "request_space_storage", "restart_space", "resume_inference_endpoint", "resume_scheduled_job", "revision_exists", "run_as_future", "run_job", "run_uv_job", "scale_to_zero_inference_endpoint", "set_space_sleep_time", "set_space_volumes", "space_info", "super_squash_history", "suspend_scheduled_job", "sync_bucket", "unlike", "update_collection_item", "update_collection_metadata", "update_inference_endpoint", "update_repo_settings", "update_webhook", "upload_file", "upload_folder", "upload_large_folder", "verify_repo_checksums", "whoami", ], "hf_file_system": [ "HfFileSystem", "HfFileSystemFile", "HfFileSystemResolvedPath", "HfFileSystemStreamFile", "hffs", ], "hub_mixin": [ "ModelHubMixin", "PyTorchModelHubMixin", ], "inference._client": [ "InferenceClient", "InferenceTimeoutError", ], "inference._generated._async_client": [ "AsyncInferenceClient", ], "inference._generated.types": [ "AudioClassificationInput", "AudioClassificationOutputElement", "AudioClassificationOutputTransform", "AudioClassificationParameters", "AudioToAudioInput", "AudioToAudioOutputElement", "AutomaticSpeechRecognitionEarlyStoppingEnum", "AutomaticSpeechRecognitionGenerationParameters", "AutomaticSpeechRecognitionInput", "AutomaticSpeechRecognitionOutput", "AutomaticSpeechRecognitionOutputChunk", "AutomaticSpeechRecognitionParameters", "ChatCompletionInput", "ChatCompletionInputFunctionDefinition", "ChatCompletionInputFunctionName", "ChatCompletionInputGrammarType", "ChatCompletionInputJSONSchema", "ChatCompletionInputMessage", "ChatCompletionInputMessageChunk", "ChatCompletionInputMessageChunkType", "ChatCompletionInputResponseFormatJSONObject", "ChatCompletionInputResponseFormatJSONSchema", "ChatCompletionInputResponseFormatText", "ChatCompletionInputStreamOptions", "ChatCompletionInputTool", "ChatCompletionInputToolCall", "ChatCompletionInputToolChoiceClass", "ChatCompletionInputToolChoiceEnum", "ChatCompletionInputURL", "ChatCompletionOutput", "ChatCompletionOutputComplete", "ChatCompletionOutputFunctionDefinition", "ChatCompletionOutputLogprob", "ChatCompletionOutputLogprobs", "ChatCompletionOutputMessage", "ChatCompletionOutputToolCall", "ChatCompletionOutputTopLogprob", "ChatCompletionOutputUsage", "ChatCompletionStreamOutput", "ChatCompletionStreamOutputChoice", "ChatCompletionStreamOutputDelta", "ChatCompletionStreamOutputDeltaToolCall", "ChatCompletionStreamOutputFunction", "ChatCompletionStreamOutputLogprob", "ChatCompletionStreamOutputLogprobs", "ChatCompletionStreamOutputTopLogprob", "ChatCompletionStreamOutputUsage", "DepthEstimationInput", "DepthEstimationOutput", "DocumentQuestionAnsweringInput", "DocumentQuestionAnsweringInputData", "DocumentQuestionAnsweringOutputElement", "DocumentQuestionAnsweringParameters", "FeatureExtractionInput", "FeatureExtractionInputTruncationDirection", "FillMaskInput", "FillMaskOutputElement", "FillMaskParameters", "ImageClassificationInput", "ImageClassificationOutputElement", "ImageClassificationOutputTransform", "ImageClassificationParameters", "ImageSegmentationInput", "ImageSegmentationOutputElement", "ImageSegmentationParameters", "ImageSegmentationSubtask", "ImageTextToImageInput", "ImageTextToImageOutput", "ImageTextToImageParameters", "ImageTextToImageTargetSize", "ImageTextToVideoInput", "ImageTextToVideoOutput", "ImageTextToVideoParameters", "ImageTextToVideoTargetSize", "ImageToImageInput", "ImageToImageOutput", "ImageToImageParameters", "ImageToImageTargetSize", "ImageToTextEarlyStoppingEnum", "ImageToTextGenerationParameters", "ImageToTextInput", "ImageToTextOutput", "ImageToTextParameters", "ImageToVideoInput", "ImageToVideoOutput", "ImageToVideoParameters", "ImageToVideoTargetSize", "ObjectDetectionBoundingBox", "ObjectDetectionInput", "ObjectDetectionOutputElement", "ObjectDetectionParameters", "Padding", "QuestionAnsweringInput", "QuestionAnsweringInputData", "QuestionAnsweringOutputElement", "QuestionAnsweringParameters", "SentenceSimilarityInput", "SentenceSimilarityInputData", "SummarizationInput", "SummarizationOutput", "SummarizationParameters", "SummarizationTruncationStrategy", "TableQuestionAnsweringInput", "TableQuestionAnsweringInputData", "TableQuestionAnsweringOutputElement", "TableQuestionAnsweringParameters", "Text2TextGenerationInput", "Text2TextGenerationOutput", "Text2TextGenerationParameters", "Text2TextGenerationTruncationStrategy", "TextClassificationInput", "TextClassificationOutputElement", "TextClassificationOutputTransform", "TextClassificationParameters", "TextGenerationInput", "TextGenerationInputGenerateParameters", "TextGenerationInputGrammarType", "TextGenerationOutput", "TextGenerationOutputBestOfSequence", "TextGenerationOutputDetails", "TextGenerationOutputFinishReason", "TextGenerationOutputPrefillToken", "TextGenerationOutputToken", "TextGenerationStreamOutput", "TextGenerationStreamOutputStreamDetails", "TextGenerationStreamOutputToken", "TextToAudioEarlyStoppingEnum", "TextToAudioGenerationParameters", "TextToAudioInput", "TextToAudioOutput", "TextToAudioParameters", "TextToImageInput", "TextToImageOutput", "TextToImageParameters", "TextToSpeechEarlyStoppingEnum", "TextToSpeechGenerationParameters", "TextToSpeechInput", "TextToSpeechOutput", "TextToSpeechParameters", "TextToVideoInput", "TextToVideoOutput", "TextToVideoParameters", "TokenClassificationAggregationStrategy", "TokenClassificationInput", "TokenClassificationOutputElement", "TokenClassificationParameters", "TranslationInput", "TranslationOutput", "TranslationParameters", "TranslationTruncationStrategy", "TypeEnum", "VideoClassificationInput", "VideoClassificationOutputElement", "VideoClassificationOutputTransform", "VideoClassificationParameters", "VisualQuestionAnsweringInput", "VisualQuestionAnsweringInputData", "VisualQuestionAnsweringOutputElement", "VisualQuestionAnsweringParameters", "ZeroShotClassificationInput", "ZeroShotClassificationOutputElement", "ZeroShotClassificationParameters", "ZeroShotImageClassificationInput", "ZeroShotImageClassificationOutputElement", "ZeroShotImageClassificationParameters", "ZeroShotObjectDetectionBoundingBox", "ZeroShotObjectDetectionInput", "ZeroShotObjectDetectionOutputElement", "ZeroShotObjectDetectionParameters", ], "inference._mcp.agent": [ "Agent", ], "inference._mcp.mcp_client": [ "MCPClient", ], "repocard": [ "DatasetCard", "ModelCard", "RepoCard", "SpaceCard", "metadata_eval_result", "metadata_load", "metadata_save", "metadata_update", ], "repocard_data": [ "CardData", "DatasetCardData", "EvalResult", "ModelCardData", "SpaceCardData", ], "serialization": [ "StateDictSplit", "get_torch_storage_id", "get_torch_storage_size", "load_state_dict_from_file", "load_torch_model", "save_torch_model", "save_torch_state_dict", "split_state_dict_into_shards_factory", "split_torch_state_dict_into_shards", ], "serialization._dduf": [ "DDUFEntry", "export_entries_as_dduf", "export_folder_as_dduf", "read_dduf_file", ], "utils": [ "ASYNC_CLIENT_FACTORY_T", "CLIENT_FACTORY_T", "CacheNotFound", "CachedFileInfo", "CachedRepoInfo", "CachedRevisionInfo", "CorruptedCacheException", "DeleteCacheStrategy", "HFCacheInfo", "cached_assets_path", "close_session", "dump_environment_info", "get_async_session", "get_session", "get_token", "hf_raise_for_status", "logging", "scan_cache_dir", "set_async_client_factory", "set_client_factory", ],}
# WARNING: __all__ is generated automatically, Any manual edit will be lost when re-generating this file !## To update the static imports, please run the following command and commit the changes.# ```# # Use script# python utils/check_all_variable.py --update## # Or run style on codebase# make style# ```
__all__ = [ "ASYNC_CLIENT_FACTORY_T", "Agent", "AsyncInferenceClient", "AudioClassificationInput", "AudioClassificationOutputElement", "AudioClassificationOutputTransform", "AudioClassificationParameters", "AudioToAudioInput", "AudioToAudioOutputElement", "AutomaticSpeechRecognitionEarlyStoppingEnum", "AutomaticSpeechRecognitionGenerationParameters", "AutomaticSpeechRecognitionInput", "AutomaticSpeechRecognitionOutput", "AutomaticSpeechRecognitionOutputChunk", "AutomaticSpeechRecognitionParameters", "BucketFile", "BucketFileMetadata", "BucketFolder", "BucketInfo", "BucketUrl", "CLIENT_FACTORY_T", "CONFIG_NAME", "CacheNotFound", "CachedFileInfo", "CachedRepoInfo", "CachedRevisionInfo", "CardData", "ChatCompletionInput", "ChatCompletionInputFunctionDefinition", "ChatCompletionInputFunctionName", "ChatCompletionInputGrammarType", "ChatCompletionInputJSONSchema", "ChatCompletionInputMessage", "ChatCompletionInputMessageChunk", "ChatCompletionInputMessageChunkType", "ChatCompletionInputResponseFormatJSONObject", "ChatCompletionInputResponseFormatJSONSchema", "ChatCompletionInputResponseFormatText", "ChatCompletionInputStreamOptions", "ChatCompletionInputTool", "ChatCompletionInputToolCall", "ChatCompletionInputToolChoiceClass", "ChatCompletionInputToolChoiceEnum", "ChatCompletionInputURL", "ChatCompletionOutput", "ChatCompletionOutputComplete", "ChatCompletionOutputFunctionDefinition", "ChatCompletionOutputLogprob", "ChatCompletionOutputLogprobs", "ChatCompletionOutputMessage", "ChatCompletionOutputToolCall", "ChatCompletionOutputTopLogprob", "ChatCompletionOutputUsage", "ChatCompletionStreamOutput", "ChatCompletionStreamOutputChoice", "ChatCompletionStreamOutputDelta", "ChatCompletionStreamOutputDeltaToolCall", "ChatCompletionStreamOutputFunction", "ChatCompletionStreamOutputLogprob", "ChatCompletionStreamOutputLogprobs", "ChatCompletionStreamOutputTopLogprob", "ChatCompletionStreamOutputUsage", "Collection", "CollectionItem", "CommitInfo", "CommitOperation", "CommitOperationAdd", "CommitOperationCopy", "CommitOperationDelete", "CommitScheduler", "CorruptedCacheException", "DDUFEntry", "DatasetCard", "DatasetCardData", "DatasetInfo", "DatasetLeaderboardEntry", "DeleteCacheStrategy", "DepthEstimationInput", "DepthEstimationOutput", "Discussion", "DiscussionComment", "DiscussionCommit", "DiscussionEvent", "DiscussionStatusChange", "DiscussionTitleChange", "DiscussionWithDetails", "DocumentQuestionAnsweringInput", "DocumentQuestionAnsweringInputData", "DocumentQuestionAnsweringOutputElement", "DocumentQuestionAnsweringParameters", "DryRunFileInfo", "EvalResult", "EvalResultEntry", "FLAX_WEIGHTS_NAME", "FeatureExtractionInput", "FeatureExtractionInputTruncationDirection", "FillMaskInput", "FillMaskOutputElement", "FillMaskParameters", "GitCommitInfo", "GitRefInfo", "GitRefs", "HFCacheInfo", "HFSummaryWriter", "HUGGINGFACE_CO_URL_HOME", "HUGGINGFACE_CO_URL_TEMPLATE", "HfApi", "HfFileMetadata", "HfFileSystem", "HfFileSystemFile", "HfFileSystemResolvedPath", "HfFileSystemStreamFile", "ImageClassificationInput", "ImageClassificationOutputElement", "ImageClassificationOutputTransform", "ImageClassificationParameters", "ImageSegmentationInput", "ImageSegmentationOutputElement", "ImageSegmentationParameters", "ImageSegmentationSubtask", "ImageTextToImageInput", "ImageTextToImageOutput", "ImageTextToImageParameters", "ImageTextToImageTargetSize", "ImageTextToVideoInput", "ImageTextToVideoOutput", "ImageTextToVideoParameters", "ImageTextToVideoTargetSize", "ImageToImageInput", "ImageToImageOutput", "ImageToImageParameters", "ImageToImageTargetSize", "ImageToTextEarlyStoppingEnum", "ImageToTextGenerationParameters", "ImageToTextInput", "ImageToTextOutput", "ImageToTextParameters", "ImageToVideoInput", "ImageToVideoOutput", "ImageToVideoParameters", "ImageToVideoTargetSize", "InferenceClient", "InferenceEndpoint", "InferenceEndpointError", "InferenceEndpointStatus", "InferenceEndpointTimeoutError", "InferenceEndpointType", "InferenceTimeoutError", "JobAccelerator", "JobHardware", "JobInfo", "JobOwner", "JobStage", "JobStatus", "KernelInfo", "MCPClient", "ModelCard", "ModelCardData", "ModelHubMixin", "ModelInfo", "OAuthInfo", "OAuthOrgInfo", "OAuthUserInfo", "ObjectDetectionBoundingBox", "ObjectDetectionInput", "ObjectDetectionOutputElement", "ObjectDetectionParameters", "Organization", "PYTORCH_WEIGHTS_NAME", "Padding", "PyTorchModelHubMixin", "QuestionAnsweringInput", "QuestionAnsweringInputData", "QuestionAnsweringOutputElement", "QuestionAnsweringParameters", "REPO_TYPE_DATASET", "REPO_TYPE_MODEL", "REPO_TYPE_SPACE", "RepoCard", "RepoFile", "RepoFolder", "RepoUrl", "SentenceSimilarityInput", "SentenceSimilarityInputData", "SpaceCard", "SpaceCardData", "SpaceHardware", "SpaceInfo", "SpaceRuntime", "SpaceStage", "SpaceStorage", "SpaceVariable", "StateDictSplit", "SummarizationInput", "SummarizationOutput", "SummarizationParameters", "SummarizationTruncationStrategy", "SyncOperation", "SyncPlan", "TF2_WEIGHTS_NAME", "TF_WEIGHTS_NAME", "TableQuestionAnsweringInput", "TableQuestionAnsweringInputData", "TableQuestionAnsweringOutputElement", "TableQuestionAnsweringParameters", "Text2TextGenerationInput", "Text2TextGenerationOutput", "Text2TextGenerationParameters", "Text2TextGenerationTruncationStrategy", "TextClassificationInput", "TextClassificationOutputElement", "TextClassificationOutputTransform", "TextClassificationParameters", "TextGenerationInput", "TextGenerationInputGenerateParameters", "TextGenerationInputGrammarType", "TextGenerationOutput", "TextGenerationOutputBestOfSequence", "TextGenerationOutputDetails", "TextGenerationOutputFinishReason", "TextGenerationOutputPrefillToken", "TextGenerationOutputToken", "TextGenerationStreamOutput", "TextGenerationStreamOutputStreamDetails", "TextGenerationStreamOutputToken", "TextToAudioEarlyStoppingEnum", "TextToAudioGenerationParameters", "TextToAudioInput", "TextToAudioOutput", "TextToAudioParameters", "TextToImageInput", "TextToImageOutput", "TextToImageParameters", "TextToSpeechEarlyStoppingEnum", "TextToSpeechGenerationParameters", "TextToSpeechInput", "TextToSpeechOutput", "TextToSpeechParameters", "TextToVideoInput", "TextToVideoOutput", "TextToVideoParameters", "TokenClassificationAggregationStrategy", "TokenClassificationInput", "TokenClassificationOutputElement", "TokenClassificationParameters", "TranslationInput", "TranslationOutput", "TranslationParameters", "TranslationTruncationStrategy", "TypeEnum", "User", "UserLikes", "VideoClassificationInput", "VideoClassificationOutputElement", "VideoClassificationOutputTransform", "VideoClassificationParameters", "VisualQuestionAnsweringInput", "VisualQuestionAnsweringInputData", "VisualQuestionAnsweringOutputElement", "VisualQuestionAnsweringParameters", "Volume", "WebhookInfo", "WebhookPayload", "WebhookPayloadComment", "WebhookPayloadDiscussion", "WebhookPayloadDiscussionChanges", "WebhookPayloadEvent", "WebhookPayloadMovedTo", "WebhookPayloadRepo", "WebhookPayloadUrl", "WebhookPayloadWebhook", "WebhookWatchedItem", "WebhooksServer", "ZeroShotClassificationInput", "ZeroShotClassificationOutputElement", "ZeroShotClassificationParameters", "ZeroShotImageClassificationInput", "ZeroShotImageClassificationOutputElement", "ZeroShotImageClassificationParameters", "ZeroShotObjectDetectionBoundingBox", "ZeroShotObjectDetectionInput", "ZeroShotObjectDetectionOutputElement", "ZeroShotObjectDetectionParameters", "_CACHED_NO_EXIST", "_save_pretrained_fastai", "accept_access_request", "add_collection_item", "add_space_secret", "add_space_variable", "attach_huggingface_oauth", "auth_check", "auth_list", "auth_switch", "batch_bucket_files", "bucket_info", "cached_assets_path", "cancel_access_request", "cancel_job", "change_discussion_status", "check_cli_update", "close_session", "comment_discussion", "copy_files", "create_branch", "create_bucket", "create_collection", "create_commit", "create_discussion", "create_inference_endpoint", "create_inference_endpoint_from_catalog", "create_pull_request", "create_repo", "create_scheduled_job", "create_scheduled_uv_job", "create_tag", "create_webhook", "dataset_info", "delete_branch", "delete_bucket", "delete_collection", "delete_collection_item", "delete_file", "delete_folder", "delete_inference_endpoint", "delete_repo", "delete_scheduled_job", "delete_space_secret", "delete_space_storage", "delete_space_variable", "delete_space_volumes", "delete_tag", "delete_webhook", "disable_space_dev_mode", "disable_webhook", "download_bucket_files", "dump_environment_info", "duplicate_repo", "duplicate_space", "edit_discussion_comment", "enable_space_dev_mode", "enable_webhook", "eval_result_entries_to_yaml", "export_entries_as_dduf", "export_folder_as_dduf", "fetch_job_logs", "fetch_job_metrics", "file_exists", "from_pretrained_fastai", "get_async_session", "get_bucket_file_metadata", "get_bucket_paths_info", "get_collection", "get_dataset_leaderboard", "get_dataset_tags", "get_discussion_details", "get_full_repo_name", "get_hf_file_metadata", "get_inference_endpoint", "get_local_safetensors_metadata", "get_model_tags", "get_organization_overview", "get_paths_info", "get_repo_discussions", "get_safetensors_metadata", "get_session", "get_space_runtime", "get_space_variables", "get_token", "get_torch_storage_id", "get_torch_storage_size", "get_user_overview", "get_webhook", "grant_access", "hf_hub_download", "hf_hub_url", "hf_raise_for_status", "hffs", "inspect_job", "inspect_scheduled_job", "interpreter_login", "is_offline_mode", "kernel_info", "list_accepted_access_requests", "list_bucket_tree", "list_buckets", "list_collections", "list_daily_papers", "list_dataset_parquet_files", "list_datasets", "list_inference_catalog", "list_inference_endpoints", "list_jobs", "list_jobs_hardware", "list_lfs_files", "list_liked_repos", "list_models", "list_organization_followers", "list_organization_members", "list_papers", "list_pending_access_requests", "list_rejected_access_requests", "list_repo_commits", "list_repo_files", "list_repo_likers", "list_repo_refs", "list_repo_tree", "list_spaces", "list_user_followers", "list_user_following", "list_webhooks", "load_state_dict_from_file", "load_torch_model", "logging", "login", "logout", "merge_pull_request", "metadata_eval_result", "metadata_load", "metadata_save", "metadata_update", "model_info", "move_bucket", "move_repo", "notebook_login", "paper_info", "parse_eval_result_entries", "parse_huggingface_oauth", "parse_local_safetensors_file_metadata", "parse_safetensors_file_metadata", "pause_inference_endpoint", "pause_space", "permanently_delete_lfs_files", "preupload_lfs_files", "push_to_hub_fastai", "read_dduf_file", "read_paper", "reject_access_request", "rename_discussion", "repo_exists", "repo_info", "repo_type_and_id_from_hf_id", "request_space_hardware", "request_space_storage", "restart_space", "resume_inference_endpoint", "resume_scheduled_job", "revision_exists", "run_as_future", "run_job", "run_uv_job", "save_torch_model", "save_torch_state_dict", "scale_to_zero_inference_endpoint", "scan_cache_dir", "set_async_client_factory", "set_client_factory", "set_space_sleep_time", "set_space_volumes", "snapshot_download", "space_info", "split_state_dict_into_shards_factory", "split_torch_state_dict_into_shards", "super_squash_history", "suspend_scheduled_job", "sync_bucket", "try_to_load_from_cache", "typer_factory", "unlike", "update_collection_item", "update_collection_metadata", "update_inference_endpoint", "update_repo_settings", "update_webhook", "upload_file", "upload_folder", "upload_large_folder", "verify_repo_checksums", "webhook_endpoint", "whoami",]
def _attach(package_name, submodules=None, submod_attrs=None): """Attach lazily loaded submodules, functions, or other attributes.
Typically, modules import submodules and attributes as follows:
```py import mysubmodule import anothersubmodule
from .foo import someattr ```
The idea is to replace a package's `__getattr__`, `__dir__`, such that all imports work exactly the way they would with normal imports, except that the import occurs upon first use.
The typical way to call this function, replacing the above imports, is:
```python __getattr__, __dir__ = lazy.attach( __name__, ['mysubmodule', 'anothersubmodule'], {'foo': ['someattr']} ) ``` This functionality requires Python 3.7 or higher.
Args: package_name (`str`): Typically use `__name__`. submodules (`set`): List of submodules to attach. submod_attrs (`dict`): Dictionary of submodule -> list of attributes / functions. These attributes are imported as they are used.
Returns: __getattr__, __dir__, __all__
""" if submod_attrs is None: submod_attrs = {}
if submodules is None: submodules = set() else: submodules = set(submodules)
attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
def __getattr__(name): if name in submodules: try: return importlib.import_module(f"{package_name}.{name}") except Exception as e: print(f"Error importing {package_name}.{name}: {e}") raise elif name in attr_to_modules: submod_path = f"{package_name}.{attr_to_modules[name]}" try: submod = importlib.import_module(submod_path) except Exception as e: print(f"Error importing {submod_path}: {e}") raise attr = getattr(submod, name)
# If the attribute lives in a file (module) with the same # name as the attribute, ensure that the attribute and *not* # the module is accessible on the package. if name == attr_to_modules[name]: pkg = sys.modules[package_name] pkg.__dict__[name] = attr
return attr else: raise AttributeError(f"No {package_name} attribute {name}")
def __dir__(): return __all__
return __getattr__, __dir__
__getattr__, __dir__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
if os.environ.get("EAGER_IMPORT", ""): for attr in __all__: __getattr__(attr)
# WARNING: any content below this statement is generated automatically. Any manual edit# will be lost when re-generating this file !## To update the static imports, please run the following command and commit the changes.# ```# # Use script# python utils/check_static_imports.py --update## # Or run style on codebase# make style# ```if TYPE_CHECKING: # pragma: no cover from ._buckets import ( BucketFile, # noqa: F401 BucketFileMetadata, # noqa: F401 BucketFolder, # noqa: F401 BucketInfo, # noqa: F401 BucketUrl, # noqa: F401 SyncOperation, # noqa: F401 SyncPlan, # noqa: F401 ) from ._commit_scheduler import CommitScheduler # noqa: F401 from ._eval_results import ( EvalResultEntry, # noqa: F401 eval_result_entries_to_yaml, # noqa: F401 parse_eval_result_entries, # noqa: F401 ) from ._inference_endpoints import ( InferenceEndpoint, # noqa: F401 InferenceEndpointError, # noqa: F401 InferenceEndpointStatus, # noqa: F401 InferenceEndpointTimeoutError, # noqa: F401 InferenceEndpointType, # noqa: F401 ) from ._jobs_api import ( JobAccelerator, # noqa: F401 JobHardware, # noqa: F401 JobInfo, # noqa: F401 JobOwner, # noqa: F401 JobStage, # noqa: F401 JobStatus, # noqa: F401 ) from ._login import ( auth_list, # noqa: F401 auth_switch, # noqa: F401 interpreter_login, # noqa: F401 login, # noqa: F401 logout, # noqa: F401 notebook_login, # noqa: F401 ) from ._oauth import ( OAuthInfo, # noqa: F401 OAuthOrgInfo, # noqa: F401 OAuthUserInfo, # noqa: F401 attach_huggingface_oauth, # noqa: F401 parse_huggingface_oauth, # noqa: F401 ) from ._snapshot_download import snapshot_download # noqa: F401 from ._space_api import ( SpaceHardware, # noqa: F401 SpaceRuntime, # noqa: F401 SpaceStage, # noqa: F401 SpaceStorage, # noqa: F401 SpaceVariable, # noqa: F401 Volume, # noqa: F401 ) from ._tensorboard_logger import HFSummaryWriter # noqa: F401 from ._webhooks_payload import ( WebhookPayload, # noqa: F401 WebhookPayloadComment, # noqa: F401 WebhookPayloadDiscussion, # noqa: F401 WebhookPayloadDiscussionChanges, # noqa: F401 WebhookPayloadEvent, # noqa: F401 WebhookPayloadMovedTo, # noqa: F401 WebhookPayloadRepo, # noqa: F401 WebhookPayloadUrl, # noqa: F401 WebhookPayloadWebhook, # noqa: F401 ) from ._webhooks_server import ( WebhooksServer, # noqa: F401 webhook_endpoint, # noqa: F401 ) from .cli._cli_utils import ( check_cli_update, # noqa: F401 typer_factory, # noqa: F401 ) from .community import ( Discussion, # noqa: F401 DiscussionComment, # noqa: F401 DiscussionCommit, # noqa: F401 DiscussionEvent, # noqa: F401 DiscussionStatusChange, # noqa: F401 DiscussionTitleChange, # noqa: F401 DiscussionWithDetails, # noqa: F401 ) from .constants import ( CONFIG_NAME, # noqa: F401 FLAX_WEIGHTS_NAME, # noqa: F401 HUGGINGFACE_CO_URL_HOME, # noqa: F401 HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401 PYTORCH_WEIGHTS_NAME, # noqa: F401 REPO_TYPE_DATASET, # noqa: F401 REPO_TYPE_MODEL, # noqa: F401 REPO_TYPE_SPACE, # noqa: F401 TF2_WEIGHTS_NAME, # noqa: F401 TF_WEIGHTS_NAME, # noqa: F401 is_offline_mode, # noqa: F401 ) from .fastai_utils import ( _save_pretrained_fastai, # noqa: F401 from_pretrained_fastai, # noqa: F401 push_to_hub_fastai, # noqa: F401 ) from .file_download import ( _CACHED_NO_EXIST, # noqa: F401 DryRunFileInfo, # noqa: F401 HfFileMetadata, # noqa: F401 get_hf_file_metadata, # noqa: F401 hf_hub_download, # noqa: F401 hf_hub_url, # noqa: F401 try_to_load_from_cache, # noqa: F401 ) from .hf_api import ( Collection, # noqa: F401 CollectionItem, # noqa: F401 CommitInfo, # noqa: F401 CommitOperation, # noqa: F401 CommitOperationAdd, # noqa: F401 CommitOperationCopy, # noqa: F401 CommitOperationDelete, # noqa: F401 DatasetInfo, # noqa: F401 DatasetLeaderboardEntry, # noqa: F401 GitCommitInfo, # noqa: F401 GitRefInfo, # noqa: F401 GitRefs, # noqa: F401 HfApi, # noqa: F401 KernelInfo, # noqa: F401 ModelInfo, # noqa: F401 Organization, # noqa: F401 RepoFile, # noqa: F401 RepoFolder, # noqa: F401 RepoUrl, # noqa: F401 SpaceInfo, # noqa: F401 User, # noqa: F401 UserLikes, # noqa: F401 WebhookInfo, # noqa: F401 WebhookWatchedItem, # noqa: F401 accept_access_request, # noqa: F401 add_collection_item, # noqa: F401 add_space_secret, # noqa: F401 add_space_variable, # noqa: F401 auth_check, # noqa: F401 batch_bucket_files, # noqa: F401 bucket_info, # noqa: F401 cancel_access_request, # noqa: F401 cancel_job, # noqa: F401 change_discussion_status, # noqa: F401 comment_discussion, # noqa: F401 copy_files, # noqa: F401 create_branch, # noqa: F401 create_bucket, # noqa: F401 create_collection, # noqa: F401 create_commit, # noqa: F401 create_discussion, # noqa: F401 create_inference_endpoint, # noqa: F401 create_inference_endpoint_from_catalog, # noqa: F401 create_pull_request, # noqa: F401 create_repo, # noqa: F401 create_scheduled_job, # noqa: F401 create_scheduled_uv_job, # noqa: F401 create_tag, # noqa: F401 create_webhook, # noqa: F401 dataset_info, # noqa: F401 delete_branch, # noqa: F401 delete_bucket, # noqa: F401 delete_collection, # noqa: F401 delete_collection_item, # noqa: F401 delete_file, # noqa: F401 delete_folder, # noqa: F401 delete_inference_endpoint, # noqa: F401 delete_repo, # noqa: F401 delete_scheduled_job, # noqa: F401 delete_space_secret, # noqa: F401 delete_space_storage, # noqa: F401 delete_space_variable, # noqa: F401 delete_space_volumes, # noqa: F401 delete_tag, # noqa: F401 delete_webhook, # noqa: F401 disable_space_dev_mode, # noqa: F401 disable_webhook, # noqa: F401 download_bucket_files, # noqa: F401 duplicate_repo, # noqa: F401 duplicate_space, # noqa: F401 edit_discussion_comment, # noqa: F401 enable_space_dev_mode, # noqa: F401 enable_webhook, # noqa: F401 fetch_job_logs, # noqa: F401 fetch_job_metrics, # noqa: F401 file_exists, # noqa: F401 get_bucket_file_metadata, # noqa: F401 get_bucket_paths_info, # noqa: F401 get_collection, # noqa: F401 get_dataset_leaderboard, # noqa: F401 get_dataset_tags, # noqa: F401 get_discussion_details, # noqa: F401 get_full_repo_name, # noqa: F401 get_inference_endpoint, # noqa: F401 get_local_safetensors_metadata, # noqa: F401 get_model_tags, # noqa: F401 get_organization_overview, # noqa: F401 get_paths_info, # noqa: F401 get_repo_discussions, # noqa: F401 get_safetensors_metadata, # noqa: F401 get_space_runtime, # noqa: F401 get_space_variables, # noqa: F401 get_user_overview, # noqa: F401 get_webhook, # noqa: F401 grant_access, # noqa: F401 inspect_job, # noqa: F401 inspect_scheduled_job, # noqa: F401 kernel_info, # noqa: F401 list_accepted_access_requests, # noqa: F401 list_bucket_tree, # noqa: F401 list_buckets, # noqa: F401 list_collections, # noqa: F401 list_daily_papers, # noqa: F401 list_dataset_parquet_files, # noqa: F401 list_datasets, # noqa: F401 list_inference_catalog, # noqa: F401 list_inference_endpoints, # noqa: F401 list_jobs, # noqa: F401 list_jobs_hardware, # noqa: F401 list_lfs_files, # noqa: F401 list_liked_repos, # noqa: F401 list_models, # noqa: F401 list_organization_followers, # noqa: F401 list_organization_members, # noqa: F401 list_papers, # noqa: F401 list_pending_access_requests, # noqa: F401 list_rejected_access_requests, # noqa: F401 list_repo_commits, # noqa: F401 list_repo_files, # noqa: F401 list_repo_likers, # noqa: F401 list_repo_refs, # noqa: F401 list_repo_tree, # noqa: F401 list_spaces, # noqa: F401 list_user_followers, # noqa: F401 list_user_following, # noqa: F401 list_webhooks, # noqa: F401 merge_pull_request, # noqa: F401 model_info, # noqa: F401 move_bucket, # noqa: F401 move_repo, # noqa: F401 paper_info, # noqa: F401 parse_local_safetensors_file_metadata, # noqa: F401 parse_safetensors_file_metadata, # noqa: F401 pause_inference_endpoint, # noqa: F401 pause_space, # noqa: F401 permanently_delete_lfs_files, # noqa: F401 preupload_lfs_files, # noqa: F401 read_paper, # noqa: F401 reject_access_request, # noqa: F401 rename_discussion, # noqa: F401 repo_exists, # noqa: F401 repo_info, # noqa: F401 repo_type_and_id_from_hf_id, # noqa: F401 request_space_hardware, # noqa: F401 request_space_storage, # noqa: F401 restart_space, # noqa: F401 resume_inference_endpoint, # noqa: F401 resume_scheduled_job, # noqa: F401 revision_exists, # noqa: F401 run_as_future, # noqa: F401 run_job, # noqa: F401 run_uv_job, # noqa: F401 scale_to_zero_inference_endpoint, # noqa: F401 set_space_sleep_time, # noqa: F401 set_space_volumes, # noqa: F401 space_info, # noqa: F401 super_squash_history, # noqa: F401 suspend_scheduled_job, # noqa: F401 sync_bucket, # noqa: F401 unlike, # noqa: F401 update_collection_item, # noqa: F401 update_collection_metadata, # noqa: F401 update_inference_endpoint, # noqa: F401 update_repo_settings, # noqa: F401 update_webhook, # noqa: F401 upload_file, # noqa: F401 upload_folder, # noqa: F401 upload_large_folder, # noqa: F401 verify_repo_checksums, # noqa: F401 whoami, # noqa: F401 ) from .hf_file_system import ( HfFileSystem, # noqa: F401 HfFileSystemFile, # noqa: F401 HfFileSystemResolvedPath, # noqa: F401 HfFileSystemStreamFile, # noqa: F401 hffs, # noqa: F401 ) from .hub_mixin import ( ModelHubMixin, # noqa: F401 PyTorchModelHubMixin, # noqa: F401 ) from .inference._client import ( InferenceClient, # noqa: F401 InferenceTimeoutError, # noqa: F401 ) from .inference._generated._async_client import AsyncInferenceClient # noqa: F401 from .inference._generated.types import ( AudioClassificationInput, # noqa: F401 AudioClassificationOutputElement, # noqa: F401 AudioClassificationOutputTransform, # noqa: F401 AudioClassificationParameters, # noqa: F401 AudioToAudioInput, # noqa: F401 AudioToAudioOutputElement, # noqa: F401 AutomaticSpeechRecognitionEarlyStoppingEnum, # noqa: F401 AutomaticSpeechRecognitionGenerationParameters, # noqa: F401 AutomaticSpeechRecognitionInput, # noqa: F401 AutomaticSpeechRecognitionOutput, # noqa: F401 AutomaticSpeechRecognitionOutputChunk, # noqa: F401 AutomaticSpeechRecognitionParameters, # noqa: F401 ChatCompletionInput, # noqa: F401 ChatCompletionInputFunctionDefinition, # noqa: F401 ChatCompletionInputFunctionName, # noqa: F401 ChatCompletionInputGrammarType, # noqa: F401 ChatCompletionInputJSONSchema, # noqa: F401 ChatCompletionInputMessage, # noqa: F401 ChatCompletionInputMessageChunk, # noqa: F401 ChatCompletionInputMessageChunkType, # noqa: F401 ChatCompletionInputResponseFormatJSONObject, # noqa: F401 ChatCompletionInputResponseFormatJSONSchema, # noqa: F401 ChatCompletionInputResponseFormatText, # noqa: F401 ChatCompletionInputStreamOptions, # noqa: F401 ChatCompletionInputTool, # noqa: F401 ChatCompletionInputToolCall, # noqa: F401 ChatCompletionInputToolChoiceClass, # noqa: F401 ChatCompletionInputToolChoiceEnum, # noqa: F401 ChatCompletionInputURL, # noqa: F401 ChatCompletionOutput, # noqa: F401 ChatCompletionOutputComplete, # noqa: F401 ChatCompletionOutputFunctionDefinition, # noqa: F401 ChatCompletionOutputLogprob, # noqa: F401 ChatCompletionOutputLogprobs, # noqa: F401 ChatCompletionOutputMessage, # noqa: F401 ChatCompletionOutputToolCall, # noqa: F401 ChatCompletionOutputTopLogprob, # noqa: F401 ChatCompletionOutputUsage, # noqa: F401 ChatCompletionStreamOutput, # noqa: F401 ChatCompletionStreamOutputChoice, # noqa: F401 ChatCompletionStreamOutputDelta, # noqa: F401 ChatCompletionStreamOutputDeltaToolCall, # noqa: F401 ChatCompletionStreamOutputFunction, # noqa: F401 ChatCompletionStreamOutputLogprob, # noqa: F401 ChatCompletionStreamOutputLogprobs, # noqa: F401 ChatCompletionStreamOutputTopLogprob, # noqa: F401 ChatCompletionStreamOutputUsage, # noqa: F401 DepthEstimationInput, # noqa: F401 DepthEstimationOutput, # noqa: F401 DocumentQuestionAnsweringInput, # noqa: F401 DocumentQuestionAnsweringInputData, # noqa: F401 DocumentQuestionAnsweringOutputElement, # noqa: F401 DocumentQuestionAnsweringParameters, # noqa: F401 FeatureExtractionInput, # noqa: F401 FeatureExtractionInputTruncationDirection, # noqa: F401 FillMaskInput, # noqa: F401 FillMaskOutputElement, # noqa: F401 FillMaskParameters, # noqa: F401 ImageClassificationInput, # noqa: F401 ImageClassificationOutputElement, # noqa: F401 ImageClassificationOutputTransform, # noqa: F401 ImageClassificationParameters, # noqa: F401 ImageSegmentationInput, # noqa: F401 ImageSegmentationOutputElement, # noqa: F401 ImageSegmentationParameters, # noqa: F401 ImageSegmentationSubtask, # noqa: F401 ImageTextToImageInput, # noqa: F401 ImageTextToImageOutput, # noqa: F401 ImageTextToImageParameters, # noqa: F401 ImageTextToImageTargetSize, # noqa: F401 ImageTextToVideoInput, # noqa: F401 ImageTextToVideoOutput, # noqa: F401 ImageTextToVideoParameters, # noqa: F401 ImageTextToVideoTargetSize, # noqa: F401 ImageToImageInput, # noqa: F401 ImageToImageOutput, # noqa: F401 ImageToImageParameters, # noqa: F401 ImageToImageTargetSize, # noqa: F401 ImageToTextEarlyStoppingEnum, # noqa: F401 ImageToTextGenerationParameters, # noqa: F401 ImageToTextInput, # noqa: F401 ImageToTextOutput, # noqa: F401 ImageToTextParameters, # noqa: F401 ImageToVideoInput, # noqa: F401 ImageToVideoOutput, # noqa: F401 ImageToVideoParameters, # noqa: F401 ImageToVideoTargetSize, # noqa: F401 ObjectDetectionBoundingBox, # noqa: F401 ObjectDetectionInput, # noqa: F401 ObjectDetectionOutputElement, # noqa: F401 ObjectDetectionParameters, # noqa: F401 Padding, # noqa: F401 QuestionAnsweringInput, # noqa: F401 QuestionAnsweringInputData, # noqa: F401 QuestionAnsweringOutputElement, # noqa: F401 QuestionAnsweringParameters, # noqa: F401 SentenceSimilarityInput, # noqa: F401 SentenceSimilarityInputData, # noqa: F401 SummarizationInput, # noqa: F401 SummarizationOutput, # noqa: F401 SummarizationParameters, # noqa: F401 SummarizationTruncationStrategy, # noqa: F401 TableQuestionAnsweringInput, # noqa: F401 TableQuestionAnsweringInputData, # noqa: F401 TableQuestionAnsweringOutputElement, # noqa: F401 TableQuestionAnsweringParameters, # noqa: F401 Text2TextGenerationInput, # noqa: F401 Text2TextGenerationOutput, # noqa: F401 Text2TextGenerationParameters, # noqa: F401 Text2TextGenerationTruncationStrategy, # noqa: F401 TextClassificationInput, # noqa: F401 TextClassificationOutputElement, # noqa: F401 TextClassificationOutputTransform, # noqa: F401 TextClassificationParameters, # noqa: F401 TextGenerationInput, # noqa: F401 TextGenerationInputGenerateParameters, # noqa: F401 TextGenerationInputGrammarType, # noqa: F401 TextGenerationOutput, # noqa: F401 TextGenerationOutputBestOfSequence, # noqa: F401 TextGenerationOutputDetails, # noqa: F401 TextGenerationOutputFinishReason, # noqa: F401 TextGenerationOutputPrefillToken, # noqa: F401 TextGenerationOutputToken, # noqa: F401 TextGenerationStreamOutput, # noqa: F401 TextGenerationStreamOutputStreamDetails, # noqa: F401 TextGenerationStreamOutputToken, # noqa: F401 TextToAudioEarlyStoppingEnum, # noqa: F401 TextToAudioGenerationParameters, # noqa: F401 TextToAudioInput, # noqa: F401 TextToAudioOutput, # noqa: F401 TextToAudioParameters, # noqa: F401 TextToImageInput, # noqa: F401 TextToImageOutput, # noqa: F401 TextToImageParameters, # noqa: F401 TextToSpeechEarlyStoppingEnum, # noqa: F401 TextToSpeechGenerationParameters, # noqa: F401 TextToSpeechInput, # noqa: F401 TextToSpeechOutput, # noqa: F401 TextToSpeechParameters, # noqa: F401 TextToVideoInput, # noqa: F401 TextToVideoOutput, # noqa: F401 TextToVideoParameters, # noqa: F401 TokenClassificationAggregationStrategy, # noqa: F401 TokenClassificationInput, # noqa: F401 TokenClassificationOutputElement, # noqa: F401 TokenClassificationParameters, # noqa: F401 TranslationInput, # noqa: F401 TranslationOutput, # noqa: F401 TranslationParameters, # noqa: F401 TranslationTruncationStrategy, # noqa: F401 TypeEnum, # noqa: F401 VideoClassificationInput, # noqa: F401 VideoClassificationOutputElement, # noqa: F401 VideoClassificationOutputTransform, # noqa: F401 VideoClassificationParameters, # noqa: F401 VisualQuestionAnsweringInput, # noqa: F401 VisualQuestionAnsweringInputData, # noqa: F401 VisualQuestionAnsweringOutputElement, # noqa: F401 VisualQuestionAnsweringParameters, # noqa: F401 ZeroShotClassificationInput, # noqa: F401 ZeroShotClassificationOutputElement, # noqa: F401 ZeroShotClassificationParameters, # noqa: F401 ZeroShotImageClassificationInput, # noqa: F401 ZeroShotImageClassificationOutputElement, # noqa: F401 ZeroShotImageClassificationParameters, # noqa: F401 ZeroShotObjectDetectionBoundingBox, # noqa: F401 ZeroShotObjectDetectionInput, # noqa: F401 ZeroShotObjectDetectionOutputElement, # noqa: F401 ZeroShotObjectDetectionParameters, # noqa: F401 ) from .inference._mcp.agent import Agent # noqa: F401 from .inference._mcp.mcp_client import MCPClient # noqa: F401 from .repocard import ( DatasetCard, # noqa: F401 ModelCard, # noqa: F401 RepoCard, # noqa: F401 SpaceCard, # noqa: F401 metadata_eval_result, # noqa: F401 metadata_load, # noqa: F401 metadata_save, # noqa: F401 metadata_update, # noqa: F401 ) from .repocard_data import ( CardData, # noqa: F401 DatasetCardData, # noqa: F401 EvalResult, # noqa: F401 ModelCardData, # noqa: F401 SpaceCardData, # noqa: F401 ) from .serialization import ( StateDictSplit, # noqa: F401 get_torch_storage_id, # noqa: F401 get_torch_storage_size, # noqa: F401 load_state_dict_from_file, # noqa: F401 load_torch_model, # noqa: F401 save_torch_model, # noqa: F401 save_torch_state_dict, # noqa: F401 split_state_dict_into_shards_factory, # noqa: F401 split_torch_state_dict_into_shards, # noqa: F401 ) from .serialization._dduf import ( DDUFEntry, # noqa: F401 export_entries_as_dduf, # noqa: F401 export_folder_as_dduf, # noqa: F401 read_dduf_file, # noqa: F401 ) from .utils import ( ASYNC_CLIENT_FACTORY_T, # noqa: F401 CLIENT_FACTORY_T, # noqa: F401 CachedFileInfo, # noqa: F401 CachedRepoInfo, # noqa: F401 CachedRevisionInfo, # noqa: F401 CacheNotFound, # noqa: F401 CorruptedCacheException, # noqa: F401 DeleteCacheStrategy, # noqa: F401 HFCacheInfo, # noqa: F401 cached_assets_path, # noqa: F401 close_session, # noqa: F401 dump_environment_info, # noqa: F401 get_async_session, # noqa: F401 get_session, # noqa: F401 get_token, # noqa: F401 hf_raise_for_status, # noqa: F401 logging, # noqa: F401 scan_cache_dir, # noqa: F401 set_async_client_factory, # noqa: F401 set_client_factory, # noqa: F401 )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193# Copyright 2026-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Shared logic for bucket operations.
This module contains the core buckets logic used by both the CLI and the Python API."""
import fnmatchimport jsonimport mimetypesimport osimport sysimport timefrom collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal
from . import constants, loggingfrom .errors import BucketNotFoundErrorfrom .utils import XetFileData, disable_progress_bars, enable_progress_bars, parse_datetimefrom .utils._terminal import StatusLine
if TYPE_CHECKING: from .hf_api import HfApi
logger = logging.get_logger(__name__)
BUCKET_PREFIX = "hf://buckets/"_SYNC_TIME_WINDOW_MS = 1000 # 1s safety-window for file modification time comparisons
# =============================================================================# Bucket data structures# =============================================================================
def _split_bucket_id_and_prefix(path: str) -> tuple[str, str]: """Split 'namespace/name(/optional/prefix)' into ('namespace/name', 'prefix').
Returns (bucket_id, prefix) where prefix may be empty string. Raises ValueError if path doesn't contain at least namespace/name. """ parts = path.split("/", 2) if len(parts) < 2 or not parts[0] or not parts[1]: raise ValueError(f"Invalid bucket path: '{path}'. Expected format: namespace/bucket_name") bucket_id = f"{parts[0]}/{parts[1]}" prefix = parts[2] if len(parts) > 2 else "" return bucket_id, prefix
@dataclassclass BucketInfo: """ Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`].
Attributes: id (`str`): ID of the bucket. private (`bool`): Is the bucket private. created_at (`datetime`): Date of creation of the bucket on the Hub. size (`int`): Size of the bucket in bytes. total_files (`int`): Total number of files in the bucket. """
id: str private: bool created_at: datetime size: int total_files: int
def __init__(self, **kwargs): self.id = kwargs.pop("id") self.private = kwargs.pop("private") self.created_at = parse_datetime(kwargs.pop("createdAt")) self.size = kwargs.pop("size") self.total_files = kwargs.pop("totalFiles") self.__dict__.update(**kwargs)
@dataclassclass _BucketAddFile: source: str | Path | bytes destination: str
xet_hash: str | None = field(default=None) size: int | None = field(default=None) mtime: int = field(init=False) content_type: str | None = field(init=False)
def __post_init__(self) -> None: self.content_type = None if isinstance(self.source, (str, Path)): # guess content type from source path self.content_type = mimetypes.guess_type(self.source)[0] if self.content_type is None: # or default to destination path content type self.content_type = mimetypes.guess_type(self.destination)[0]
self.mtime = int( os.path.getmtime(self.source) * 1000 if not isinstance(self.source, bytes) else time.time() * 1000 )
@dataclassclass _BucketCopyFile: destination: str xet_hash: str source_repo_type: str # "model", "dataset", "space", "bucket" source_repo_id: str size: int | None = field(default=None) mtime: int = field(init=False) content_type: str | None = field(init=False)
def __post_init__(self) -> None: self.content_type = mimetypes.guess_type(self.destination)[0] self.mtime = int(time.time() * 1000)
@dataclassclass _BucketDeleteFile: path: str
@dataclass(frozen=True)class BucketFileMetadata: """Data structure containing information about a file in a bucket.
Returned by [`get_bucket_file_metadata`].
Args: size (`int`): Size of the file in bytes. xet_file_data (`XetFileData`): Xet information for the file (hash and refresh route). """
size: int xet_file_data: XetFileData
@dataclassclass BucketUrl: """Describes a bucket URL on the Hub.
`BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties: - endpoint (`str`) - namespace (`str`) - bucket_id (`str`) - url (`str`) - handle (`str`)
Args: url (`str`): String value of the bucket url. endpoint (`str`, *optional*): Endpoint of the Hub. Defaults to <https://huggingface.co>. """
url: str endpoint: str = "" namespace: str = field(init=False) bucket_id: str = field(init=False) handle: str = field(init=False)
def __post_init__(self) -> None: self.endpoint = self.endpoint or constants.ENDPOINT
# Parse URL: expected format is `{endpoint}/buckets/{namespace}/{bucket_name}` url_path = self.url.replace(self.endpoint, "").strip("/") # Remove leading "buckets/" prefix if url_path.startswith("buckets/"): url_path = url_path[len("buckets/") :] bucket_id, prefix = _split_bucket_id_and_prefix(url_path) if prefix: raise ValueError(f"Unable to parse bucket URL: {self.url}") self.namespace = bucket_id.split("/")[0] self.bucket_id = bucket_id
self.handle = f"hf://buckets/{self.bucket_id}"
@dataclassclass BucketFile: """ Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
Similar to [`RepoFile`] but for files in buckets. """
type: Literal["file"] path: str size: int xet_hash: str mtime: datetime | None uploaded_at: datetime | None
def __init__(self, **kwargs): self.type = kwargs.pop("type") self.path = kwargs.pop("path") self.size = kwargs.pop("size") self.xet_hash = kwargs.pop("xetHash") mtime = kwargs.pop("mtime", None) self.mtime = parse_datetime(mtime) if mtime else None uploaded_at = kwargs.pop("uploadedAt", None) self.uploaded_at = parse_datetime(uploaded_at) if uploaded_at else None
@dataclassclass BucketFolder: """ Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
Similar to [`RepoFolder`] but for directories in buckets. """
type: Literal["directory"] path: str uploaded_at: datetime | None
def __init__(self, **kwargs): self.type = kwargs.pop("type") self.path = kwargs.pop("path") uploaded_at = kwargs.pop("uploadedAt", None) or kwargs.pop("uploaded_at", None) self.uploaded_at = ( (uploaded_at if isinstance(uploaded_at, datetime) else parse_datetime(uploaded_at)) if uploaded_at else None )
# =============================================================================# Bucket path parsing# =============================================================================
def _parse_bucket_path(path: str) -> tuple[str, str]: """Parse a bucket path like hf://buckets/namespace/bucket_name/prefix into (bucket_id, prefix).
Returns: tuple: (bucket_id, prefix) where bucket_id is "namespace/bucket_name" and prefix may be empty string. """ if not path.startswith(BUCKET_PREFIX): raise ValueError(f"Invalid bucket path: {path}. Must start with {BUCKET_PREFIX}") return _split_bucket_id_and_prefix(path.removeprefix(BUCKET_PREFIX))
def _is_bucket_path(path: str) -> bool: """Check if a path is a bucket path.""" return path.startswith(BUCKET_PREFIX)
# =============================================================================# Sync data structures# =============================================================================
@dataclassclass SyncOperation: """Represents a sync operation to be performed."""
action: Literal["upload", "download", "delete", "skip"] path: str size: int | None = None reason: str = "" local_mtime: str | None = None remote_mtime: str | None = None bucket_file: BucketFile | None = None # BucketFile when available (not serialized to plan file)
@dataclassclass SyncPlan: """Represents a complete sync plan."""
source: str dest: str timestamp: str operations: list[SyncOperation] = field(default_factory=list)
def summary(self) -> dict[str, int | str]: uploads = sum(1 for op in self.operations if op.action == "upload") downloads = sum(1 for op in self.operations if op.action == "download") deletes = sum(1 for op in self.operations if op.action == "delete") skips = sum(1 for op in self.operations if op.action == "skip") total_size = sum(op.size or 0 for op in self.operations if op.action in ("upload", "download")) return { "uploads": uploads, "downloads": downloads, "deletes": deletes, "skips": skips, "total_size": total_size, }
# =============================================================================# Filter matching# =============================================================================
class FilterMatcher: """Matches file paths against include/exclude patterns."""
def __init__( self, include_patterns: list[str] | None = None, exclude_patterns: list[str] | None = None, filter_rules: list[tuple[str, str]] | None = None, ): """Initialize the filter matcher.
Args: include_patterns: Patterns to include (from --include) exclude_patterns: Patterns to exclude (from --exclude) filter_rules: Rules from filter file as list of ("+"/"-", pattern) tuples """ self.include_patterns = include_patterns or [] self.exclude_patterns = exclude_patterns or [] self.filter_rules = filter_rules or []
def matches(self, path: str) -> bool: """Check if a path should be included based on the filter rules.
Filtering rules: - Filters are evaluated in order, first matching rule decides - If no rules match, include by default (unless include patterns are specified) """ # First check filter rules from file (in order) for sign, pattern in self.filter_rules: if fnmatch.fnmatch(path, pattern): return sign == "+"
# Then check CLI patterns for pattern in self.exclude_patterns: if fnmatch.fnmatch(path, pattern): return False
for pattern in self.include_patterns: if fnmatch.fnmatch(path, pattern): return True
# If include patterns were specified but none matched, exclude if self.include_patterns: return False
# Default: include return True
def _parse_filter_file(filter_file: str) -> list[tuple[str, str]]: """Parse a filter file and return a list of (sign, pattern) tuples.
Filter file format: - Lines starting with "+" are include patterns - Lines starting with "-" are exclude patterns - Empty lines and lines starting with "#" are ignored """ rules = [] with open(filter_file) as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue if line.startswith("+"): rules.append(("+", line[1:].strip())) elif line.startswith("-"): rules.append(("-", line[1:].strip())) else: # Default to include if no prefix rules.append(("+", line)) return rules
# =============================================================================# File listing# =============================================================================
def _list_local_files(local_path: str) -> Iterator[tuple[str, int, float]]: """List all files in a local directory.
Yields: tuple: (relative_path, size, mtime_ms) for each file """ local_path = os.path.abspath(local_path) if not os.path.isdir(local_path): raise ValueError(f"Local path must be a directory: {local_path}")
for root, _, files in os.walk(local_path): for filename in files: full_path = os.path.join(root, filename) rel_path = os.path.relpath(full_path, local_path) # Normalize to forward slashes for consistency rel_path = rel_path.replace(os.sep, "/") size = os.path.getsize(full_path) mtime_ms = os.path.getmtime(full_path) * 1000 yield rel_path, size, mtime_ms
def _list_remote_files(api: "HfApi", bucket_id: str, prefix: str) -> Iterator[tuple[str, int, float, Any]]: """List all files in a bucket with a given prefix.
Yields: tuple: (relative_path, size, mtime_ms, bucket_file) for each file. bucket_file is the BucketFile object from list_bucket_tree. """ for item in api.list_bucket_tree(bucket_id, prefix=prefix or None, recursive=True): if isinstance(item, BucketFolder): continue path = item.path # Remove prefix from path to get relative path # Only strip prefix if it's followed by "/" (directory boundary) or is exact match if prefix: if path.startswith(prefix + "/"): rel_path = path[len(prefix) + 1 :] elif path == prefix: # Exact match: the file IS the prefix (e.g., single file download) rel_path = path.rsplit("/", 1)[-1] if "/" in path else path else: # Path doesn't match prefix pattern (e.g., "submarine.txt" for prefix "sub") # Skip this file - it was returned by the API but doesn't belong to this prefix continue else: rel_path = path mtime_ms = item.mtime.timestamp() * 1000 if item.mtime else 0 yield rel_path, item.size, mtime_ms, item
# =============================================================================# Sync plan computation# =============================================================================
def _mtime_to_iso(mtime_ms: float) -> str: """Convert mtime in milliseconds to ISO format string.""" return datetime.fromtimestamp(mtime_ms / 1000, tz=timezone.utc).isoformat()
def _compare_files_for_sync( *, path: str, action: Literal["upload", "download"], source_size: int, source_mtime: float, dest_size: int, dest_mtime: float, source_newer_label: str, dest_newer_label: str, ignore_sizes: bool, ignore_times: bool, ignore_existing: bool, bucket_file: Any | None = None,) -> SyncOperation: """Compare source and dest files and return the appropriate sync operation.
This is a unified helper for both upload and download directions.
Args: path: Relative file path action: "upload" or "download" source_size: Size of the source file (bytes) source_mtime: Mtime of the source file (milliseconds) dest_size: Size of the destination file (bytes) dest_mtime: Mtime of the destination file (milliseconds) source_newer_label: Label when source is newer (e.g., "local newer" or "remote newer") dest_newer_label: Label when dest is newer (e.g., "remote newer" or "local newer") ignore_sizes: Only compare mtime ignore_times: Only compare size ignore_existing: Skip files that exist on receiver bucket_file: BucketFile object (for downloads only)
Returns: SyncOperation describing the action to take """ local_mtime_iso = _mtime_to_iso(source_mtime if action == "upload" else dest_mtime) remote_mtime_iso = _mtime_to_iso(dest_mtime if action == "upload" else source_mtime)
base_kwargs: dict[str, Any] = { "path": path, "size": source_size, "local_mtime": local_mtime_iso, "remote_mtime": remote_mtime_iso, }
if ignore_existing: return SyncOperation(action="skip", reason="exists on receiver (--ignore-existing)", **base_kwargs)
size_differs = source_size != dest_size source_newer = (source_mtime - dest_mtime) > _SYNC_TIME_WINDOW_MS
if ignore_sizes: if source_newer: return SyncOperation(action=action, reason=source_newer_label, bucket_file=bucket_file, **base_kwargs) else: dest_newer = (dest_mtime - source_mtime) > _SYNC_TIME_WINDOW_MS skip_reason = dest_newer_label if dest_newer else "same mtime" return SyncOperation(action="skip", reason=skip_reason, **base_kwargs) elif ignore_times: if size_differs: return SyncOperation(action=action, reason="size differs", bucket_file=bucket_file, **base_kwargs) else: return SyncOperation(action="skip", reason="same size", **base_kwargs) else: if size_differs or source_newer: reason = "size differs" if size_differs else source_newer_label return SyncOperation(action=action, reason=reason, bucket_file=bucket_file, **base_kwargs) else: return SyncOperation(action="skip", reason="identical", **base_kwargs)
def _compute_sync_plan( source: str, dest: str, api: "HfApi", delete: bool = False, ignore_times: bool = False, ignore_sizes: bool = False, existing: bool = False, ignore_existing: bool = False, filter_matcher: FilterMatcher | None = None, status: Any | None = None,) -> SyncPlan: """Compute the sync plan by comparing source and destination.
Returns: SyncPlan with all operations to be performed """ filter_matcher = filter_matcher or FilterMatcher() is_upload = not _is_bucket_path(source) and _is_bucket_path(dest) is_download = _is_bucket_path(source) and not _is_bucket_path(dest)
if not is_upload and not is_download: raise ValueError("One of source or dest must be a bucket path (hf://buckets/...) and the other must be local.")
plan = SyncPlan( source=source, dest=dest, timestamp=datetime.now(timezone.utc).isoformat(), )
remote_total: int | None = None if is_upload: # Local -> Remote local_path = os.path.abspath(source) bucket_id, prefix = _parse_bucket_path(dest)
if not os.path.isdir(local_path): raise ValueError(f"Source must be a directory: {local_path}")
# Get local and remote file lists local_files = {} for rel_path, size, mtime_ms in _list_local_files(local_path): if filter_matcher.matches(rel_path): local_files[rel_path] = (size, mtime_ms) if status: status.update(f"Scanning local directory ({len(local_files)} files)") if status: status.done(f"Scanning local directory ({len(local_files)} files)")
remote_files = {} if status: try: remote_total = api.bucket_info(bucket_id).total_files except Exception: pass try: for rel_path, size, mtime_ms, _ in _list_remote_files(api, bucket_id, prefix): if filter_matcher.matches(rel_path): remote_files[rel_path] = (size, mtime_ms) if status: total_str = f"/{remote_total}" if remote_total is not None else "" status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)") except BucketNotFoundError: # Bucket doesn't exist yet - this is expected for new uploads logger.debug(f"Bucket '{bucket_id}' not found, treating as empty.") if status: status.done(f"Scanning remote bucket ({len(remote_files)} files)")
# Compare files all_paths = set(local_files.keys()) | set(remote_files.keys()) if status: status.done(f"Comparing files ({len(all_paths)} paths)") for path in sorted(all_paths): local_info = local_files.get(path) remote_info = remote_files.get(path)
if local_info and not remote_info: # New file if existing: # --existing: skip new files plan.operations.append( SyncOperation( action="skip", path=path, size=local_info[0], reason="new file (--existing)", local_mtime=_mtime_to_iso(local_info[1]), ) ) else: plan.operations.append( SyncOperation( action="upload", path=path, size=local_info[0], reason="new file", local_mtime=_mtime_to_iso(local_info[1]), ) ) elif local_info and remote_info: # File exists in both - use helper to determine action local_size, local_mtime = local_info remote_size, remote_mtime = remote_info plan.operations.append( _compare_files_for_sync( path=path, action="upload", source_size=local_size, source_mtime=local_mtime, dest_size=remote_size, dest_mtime=remote_mtime, source_newer_label="local newer", dest_newer_label="remote newer", ignore_sizes=ignore_sizes, ignore_times=ignore_times, ignore_existing=ignore_existing, ) ) elif not local_info and remote_info and delete: # File only in remote and --delete mode plan.operations.append( SyncOperation( action="delete", path=path, size=remote_info[0], reason="not in source (--delete)", remote_mtime=_mtime_to_iso(remote_info[1]), ) )
else: # Remote -> Local (download) bucket_id, prefix = _parse_bucket_path(source) local_path = os.path.abspath(dest)
# Get remote and local file lists remote_files = {} bucket_file_map: dict[str, Any] = {} if status: try: remote_total = api.bucket_info(bucket_id).total_files except Exception: pass for rel_path, size, mtime_ms, bucket_file in _list_remote_files(api, bucket_id, prefix): if filter_matcher.matches(rel_path): remote_files[rel_path] = (size, mtime_ms) bucket_file_map[rel_path] = bucket_file if status: total_str = f"/{remote_total}" if remote_total is not None else "" status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)") if status: status.done(f"Scanning remote bucket ({len(remote_files)} files)")
local_files = {} if os.path.isdir(local_path): for rel_path, size, mtime_ms in _list_local_files(local_path): if filter_matcher.matches(rel_path): local_files[rel_path] = (size, mtime_ms) if status: status.update(f"Scanning local directory ({len(local_files)} files)") if status: status.done(f"Scanning local directory ({len(local_files)} files)")
# Compare files all_paths = set(remote_files.keys()) | set(local_files.keys()) if status: status.done(f"Comparing files ({len(all_paths)} paths)") for path in sorted(all_paths): remote_info = remote_files.get(path) local_info = local_files.get(path)
if remote_info and not local_info: # New file if existing: # --existing: skip new files plan.operations.append( SyncOperation( action="skip", path=path, size=remote_info[0], reason="new file (--existing)", remote_mtime=_mtime_to_iso(remote_info[1]), ) ) else: plan.operations.append( SyncOperation( action="download", path=path, size=remote_info[0], reason="new file", remote_mtime=_mtime_to_iso(remote_info[1]), bucket_file=bucket_file_map.get(path), ) ) elif remote_info and local_info: # File exists in both - use helper to determine action remote_size, remote_mtime = remote_info local_size, local_mtime = local_info plan.operations.append( _compare_files_for_sync( path=path, action="download", source_size=remote_size, source_mtime=remote_mtime, dest_size=local_size, dest_mtime=local_mtime, source_newer_label="remote newer", dest_newer_label="local newer", ignore_sizes=ignore_sizes, ignore_times=ignore_times, ignore_existing=ignore_existing, bucket_file=bucket_file_map.get(path), ) ) elif not remote_info and local_info and delete: # File only in local and --delete mode plan.operations.append( SyncOperation( action="delete", path=path, size=local_info[0], reason="not in source (--delete)", local_mtime=_mtime_to_iso(local_info[1]), ) )
return plan
# =============================================================================# Plan serialization# =============================================================================
def _write_plan(plan: SyncPlan, f) -> None: """Write a sync plan as JSONL to a file-like object.""" # Write header header = { "type": "header", "source": plan.source, "dest": plan.dest, "timestamp": plan.timestamp, "summary": plan.summary(), } f.write(json.dumps(header) + "\n")
# Write operations for op in plan.operations: op_dict: dict[str, Any] = { "type": "operation", "action": op.action, "path": op.path, "reason": op.reason, } if op.size is not None: op_dict["size"] = op.size if op.local_mtime is not None: op_dict["local_mtime"] = op.local_mtime if op.remote_mtime is not None: op_dict["remote_mtime"] = op.remote_mtime f.write(json.dumps(op_dict) + "\n")
def _save_plan(plan: SyncPlan, plan_file: str) -> None: """Save a sync plan to a JSONL file.""" with open(plan_file, "w") as f: _write_plan(plan, f)
def _load_plan(plan_file: str) -> SyncPlan: """Load a sync plan from a JSONL file.""" with open(plan_file) as f: lines = f.readlines()
if not lines: raise ValueError(f"Empty plan file: {plan_file}")
# Parse header header = json.loads(lines[0]) if header.get("type") != "header": raise ValueError("Invalid plan file: expected header as first line")
plan = SyncPlan( source=header["source"], dest=header["dest"], timestamp=header["timestamp"], )
# Parse operations for line in lines[1:]: op_dict = json.loads(line) if op_dict.get("type") != "operation": continue plan.operations.append( SyncOperation( action=op_dict["action"], path=op_dict["path"], size=op_dict.get("size"), reason=op_dict.get("reason", ""), local_mtime=op_dict.get("local_mtime"), remote_mtime=op_dict.get("remote_mtime"), ) )
return plan
# =============================================================================# Plan execution# =============================================================================
def _execute_plan(plan: SyncPlan, api: "HfApi", verbose: bool = False, status: Any | None = None) -> None: """Execute a sync plan.""" is_upload = not _is_bucket_path(plan.source) and _is_bucket_path(plan.dest) is_download = _is_bucket_path(plan.source) and not _is_bucket_path(plan.dest)
if is_upload: local_path = os.path.abspath(plan.source) bucket_id, prefix = _parse_bucket_path(plan.dest) prefix = prefix.rstrip("/") # Avoid double slashes in remote paths
# Collect operations add_files: list[tuple[str | Path | bytes, str]] = [] delete_paths: list[str] = []
for op in plan.operations: match op.action: case "upload": local_file = os.path.join(local_path, op.path) remote_path = f"{prefix}/{op.path}" if prefix else op.path if verbose: print(f" Uploading: {op.path} ({op.reason})") add_files.append((local_file, remote_path)) case "delete": remote_path = f"{prefix}/{op.path}" if prefix else op.path if verbose: print(f" Deleting: {op.path} ({op.reason})") delete_paths.append(remote_path) case "skip" if verbose: print(f" Skipping: {op.path} ({op.reason})")
# Execute batch operations if add_files or delete_paths: if status: parts = [] if add_files: parts.append(f"uploading {len(add_files)} files") if delete_paths: parts.append(f"deleting {len(delete_paths)} files") status.done(", ".join(parts).capitalize()) api.batch_bucket_files( bucket_id, add=add_files or None, delete=delete_paths or None, )
elif is_download: bucket_id, prefix = _parse_bucket_path(plan.source) prefix = prefix.rstrip("/") # Avoid double slashes in remote paths local_path = os.path.abspath(plan.dest)
# Ensure local directory exists os.makedirs(local_path, exist_ok=True)
# Collect download operations download_files: list[tuple[str | BucketFile, str | Path]] = [] delete_files: list[str] = []
for op in plan.operations: if op.action == "download": local_file = os.path.join(local_path, op.path) # Ensure parent directory exists os.makedirs(os.path.dirname(local_file), exist_ok=True) if verbose: print(f" Downloading: {op.path} ({op.reason})") # Use BucketFile when available (avoids extra metadata fetch per file) if op.bucket_file is not None: download_files.append((op.bucket_file, local_file)) else: remote_path = f"{prefix}/{op.path}" if prefix else op.path download_files.append((remote_path, local_file)) elif op.action == "delete": local_file = os.path.join(local_path, op.path) if verbose: print(f" Deleting: {op.path} ({op.reason})") delete_files.append(local_file) elif op.action == "skip" and verbose: print(f" Skipping: {op.path} ({op.reason})")
# Execute downloads if len(download_files) > 0: if status: status.done(f"Downloading {len(download_files)} files") api.download_bucket_files(bucket_id, download_files)
# Execute deletes if status and delete_files: status.done(f"Deleting {len(delete_files)} local files") for file_path in delete_files: if os.path.exists(file_path): os.remove(file_path) # Remove empty parent directories parent = os.path.dirname(file_path) while parent != local_path: try: os.rmdir(parent) parent = os.path.dirname(parent) except OSError: break
def _print_plan_summary(plan: SyncPlan) -> None: """Print a summary of the sync plan.""" summary = plan.summary() print(f"Sync plan: {plan.source} -> {plan.dest}") print(f" Uploads: {summary['uploads']}") print(f" Downloads: {summary['downloads']}") print(f" Deletes: {summary['deletes']}") print(f" Skips: {summary['skips']}")
# =============================================================================# Public sync function (Python API)# =============================================================================
def sync_bucket_internal( source: str | None = None, dest: str | None = None, *, api: "HfApi", delete: bool = False, ignore_times: bool = False, ignore_sizes: bool = False, existing: bool = False, ignore_existing: bool = False, include: list[str] | None = None, exclude: list[str] | None = None, filter_from: str | None = None, plan: str | None = None, apply: str | None = None, dry_run: bool = False, verbose: bool = False, quiet: bool = False, token: bool | str | None = None,) -> SyncPlan: """Sync files between a local directory and a bucket.
This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path (``hf://buckets/...``) and the other must be a local directory path.
Args: source (`str`, *optional*): Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. Required unless using ``apply``. dest (`str`, *optional*): Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. Required unless using ``apply``. api ([`HfApi`]): The HfApi instance to use for API calls. delete (`bool`, *optional*, defaults to `False`): Delete destination files not present in source. ignore_times (`bool`, *optional*, defaults to `False`): Skip files only based on size, ignoring modification times. ignore_sizes (`bool`, *optional*, defaults to `False`): Skip files only based on modification times, ignoring sizes. existing (`bool`, *optional*, defaults to `False`): Skip creating new files on receiver (only update existing files). ignore_existing (`bool`, *optional*, defaults to `False`): Skip updating files that exist on receiver (only create new files). include (`list[str]`, *optional*): Include files matching patterns (fnmatch-style). exclude (`list[str]`, *optional*): Exclude files matching patterns (fnmatch-style). filter_from (`str`, *optional*): Path to a filter file with include/exclude rules. plan (`str`, *optional*): Save sync plan to this JSONL file instead of executing. apply (`str`, *optional*): Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed. dry_run (`bool`, *optional*, defaults to `False`): Print sync plan to stdout as JSONL without executing. verbose (`bool`, *optional*, defaults to `False`): Show detailed per-file operations. quiet (`bool`, *optional*, defaults to `False`): Suppress all output and progress bars. token (Union[bool, str, None], optional): A valid user access token. If not provided, the locally saved token will be used.
Returns: [`SyncPlan`]: The computed (or loaded) sync plan.
Raises: `ValueError`: If arguments are invalid (e.g., both paths are remote, conflicting options).
Example: ```python >>> from huggingface_hub import HfApi >>> api = HfApi()
# Upload local directory to bucket >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
# Download bucket to local directory >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
# Sync with delete and filtering >>> api.sync_bucket( ... "./data", ... "hf://buckets/username/my-bucket", ... delete=True, ... include=["*.safetensors"], ... )
# Dry run: preview what would be synced >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True) >>> plan.summary() {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
# Save plan for review, then apply >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl") >>> api.sync_bucket(apply="sync-plan.jsonl") ``` """ # Build API with token if needed if token is not None: from .hf_api import HfApi
api = HfApi(token=token) # --- Apply mode --- if apply: if source or dest: raise ValueError("Cannot specify source/dest when using apply.") if plan is not None: raise ValueError("Cannot specify both plan and apply.") if delete: raise ValueError("Cannot specify delete when using apply.") if ignore_times: raise ValueError("Cannot specify ignore_times when using apply.") if ignore_sizes: raise ValueError("Cannot specify ignore_sizes when using apply.") if include: raise ValueError("Cannot specify include when using apply.") if exclude: raise ValueError("Cannot specify exclude when using apply.") if filter_from: raise ValueError("Cannot specify filter_from when using apply.") if existing: raise ValueError("Cannot specify existing when using apply.") if ignore_existing: raise ValueError("Cannot specify ignore_existing when using apply.") if dry_run: raise ValueError("Cannot specify dry_run when using apply.")
sync_plan = _load_plan(apply) status = StatusLine(enabled=not quiet) if not quiet: _print_plan_summary(sync_plan) print("Executing plan...")
if quiet: disable_progress_bars() try: _execute_plan(sync_plan, api, verbose=verbose, status=status) finally: if quiet: enable_progress_bars()
if not quiet: print("Sync completed.")
return sync_plan
# --- Normal mode --- if not source or not dest: raise ValueError("Both source and dest are required (unless using apply).")
source_is_bucket = _is_bucket_path(source) dest_is_bucket = _is_bucket_path(dest)
if source_is_bucket and dest_is_bucket: raise ValueError("Remote to remote sync is not supported. One path must be local.")
if not source_is_bucket and not dest_is_bucket: raise ValueError("One of source or dest must be a bucket path (hf://buckets/...).")
if ignore_times and ignore_sizes: raise ValueError("Cannot specify both ignore_times and ignore_sizes.")
if existing and ignore_existing: raise ValueError("Cannot specify both existing and ignore_existing.")
if dry_run and plan: raise ValueError("Cannot specify both dry_run and plan.")
# Validate local path if source_is_bucket: if os.path.exists(dest) and not os.path.isdir(dest): raise ValueError(f"Destination must be a directory: {dest}") else: if not os.path.isdir(source): raise ValueError(f"Source must be an existing directory: {source}")
# Build filter matcher filter_rules = None if filter_from: filter_rules = _parse_filter_file(filter_from)
filter_matcher = FilterMatcher( include_patterns=include, exclude_patterns=exclude, filter_rules=filter_rules, )
# Compute sync plan status = StatusLine(enabled=not quiet and not dry_run) sync_plan = _compute_sync_plan( source=source, dest=dest, api=api, delete=delete, ignore_times=ignore_times, ignore_sizes=ignore_sizes, existing=existing, ignore_existing=ignore_existing, filter_matcher=filter_matcher, status=status, )
if dry_run: _write_plan(sync_plan, sys.stdout) return sync_plan
if plan: _save_plan(sync_plan, plan) if not quiet: _print_plan_summary(sync_plan) print(f"Plan saved to: {plan}") return sync_plan
# Execute plan if not quiet: _print_plan_summary(sync_plan)
summary = sync_plan.summary() if summary["uploads"] == 0 and summary["downloads"] == 0 and summary["deletes"] == 0: if not quiet: print("Nothing to sync.") return sync_plan
if not quiet: print("Syncing...")
if quiet: disable_progress_bars() try: _execute_plan(sync_plan, api, verbose=verbose, status=status) finally: if quiet: enable_progress_bars()
if not quiet: print("Sync completed.")
return sync_plan123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976"""Type definitions and utilities for the `create_commit` API"""
import base64import ioimport osimport warningsfrom collections import defaultdictfrom collections.abc import Iterable, Iteratorfrom contextlib import contextmanagerfrom dataclasses import dataclass, fieldfrom itertools import groupbyfrom pathlib import Path, PurePosixPathfrom typing import TYPE_CHECKING, Any, BinaryIO, Literal, Union
from tqdm.contrib.concurrent import thread_map
from . import constantsfrom .errors import EntryNotFoundError, HfHubHTTPError, XetAuthorizationError, XetRefreshTokenErrorfrom .file_download import hf_hub_urlfrom .lfs import UploadInfo, lfs_upload, post_lfs_batch_infofrom .utils import ( FORBIDDEN_FOLDERS, XetTokenType, are_progress_bars_disabled, chunk_iterable, fetch_xet_connection_info_from_repo_info, get_session, hf_raise_for_status, http_backoff, logging, sha, tqdm_stream_file, validate_hf_hub_args,)from .utils import tqdm as hf_tqdmfrom .utils._runtime import is_xet_available
if TYPE_CHECKING: from .hf_api import RepoFile
logger = logging.get_logger(__name__)
UploadMode = Literal["lfs", "regular"]
# Max is 1,000 per request on the Hub for HfApi.get_paths_info# Otherwise we get:# HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters# See https://github.com/huggingface/huggingface_hub/issues/1503FETCH_LFS_BATCH_SIZE = 500
UPLOAD_BATCH_MAX_NUM_FILES = 256
@dataclassclass CommitOperationDelete: """ Data structure holding necessary info to delete a file or a folder from a repository on the Hub.
Args: path_in_repo (`str`): Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` for a file or `"checkpoints/1fec34a/"` for a folder. is_folder (`bool` or `Literal["auto"]`, *optional*) Whether the Delete Operation applies to a folder or not. If "auto", the path type (file or folder) is guessed automatically by looking if path ends with a "/" (folder) or not (file). To explicitly set the path type, you can set `is_folder=True` or `is_folder=False`. """
path_in_repo: str is_folder: bool | Literal["auto"] = "auto"
def __post_init__(self): self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
if self.is_folder == "auto": self.is_folder = self.path_in_repo.endswith("/") if not isinstance(self.is_folder, bool): raise ValueError( f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'." )
@dataclassclass CommitOperationCopy: """ Data structure holding necessary info to copy a file in a repository on the Hub.
Limitations: - Only LFS files can be copied. To copy a regular file, you need to download it locally and re-upload it - Cross-repository copies are not supported.
Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
Args: src_path_in_repo (`str`): Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`. path_in_repo (`str`): Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`. src_revision (`str`, *optional*): The git revision of the file to be copied. Can be any valid git revision. Default to the target commit revision. """
src_path_in_repo: str path_in_repo: str src_revision: str | None = None # set to the OID of the file to be copied if it has already been uploaded # useful to determine if a commit will be empty or not. _src_oid: str | None = None # set to the OID of the file to copy to if it has already been uploaded # useful to determine if a commit will be empty or not. _dest_oid: str | None = None
def __post_init__(self): self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo) self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
@dataclassclass CommitOperationAdd: """ Data structure holding necessary info to upload a file to a repository on the Hub.
Args: path_in_repo (`str`): Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`): Either: - a path to a local file (as `str` or `pathlib.Path`) to upload - a buffer of bytes (`bytes`) holding the content of the file to upload - a "file object" (subclass of `io.BufferedIOBase`), typically obtained with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
Raises: [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both `seek()` and `tell()`. """
path_in_repo: str path_or_fileobj: str | Path | bytes | BinaryIO upload_info: UploadInfo = field(init=False, repr=False)
# Internal attributes
# set to "lfs" or "regular" once known _upload_mode: UploadMode | None = field(init=False, repr=False, default=None)
# set to True if .gitignore rules prevent the file from being uploaded as LFS # (server-side check) _should_ignore: bool | None = field(init=False, repr=False, default=None)
# set to the remote OID of the file if it has already been uploaded # useful to determine if a commit will be empty or not _remote_oid: str | None = field(init=False, repr=False, default=None)
# set to True once the file has been uploaded as LFS _is_uploaded: bool = field(init=False, repr=False, default=False)
# set to True once the file has been committed _is_committed: bool = field(init=False, repr=False, default=False)
def __post_init__(self) -> None: """Validates `path_or_fileobj` and compute `upload_info`.""" self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
# Validate `path_or_fileobj` value if isinstance(self.path_or_fileobj, Path): self.path_or_fileobj = str(self.path_or_fileobj) if isinstance(self.path_or_fileobj, str): path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj)) if not os.path.isfile(path_or_fileobj): raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system") elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)): # ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode raise ValueError( "path_or_fileobj must be either an instance of str, bytes or" " io.BufferedIOBase. If you passed a file-like object, make sure it is" " in binary mode." ) if isinstance(self.path_or_fileobj, io.BufferedIOBase): try: self.path_or_fileobj.tell() self.path_or_fileobj.seek(0, os.SEEK_CUR) except (OSError, AttributeError) as exc: raise ValueError( "path_or_fileobj is a file-like object but does not implement seek() and tell()" ) from exc
# Compute "upload_info" attribute if isinstance(self.path_or_fileobj, str): self.upload_info = UploadInfo.from_path(self.path_or_fileobj) elif isinstance(self.path_or_fileobj, bytes): self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj) else: self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj)
@contextmanager def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]: """ A context manager that yields a file-like object allowing to read the underlying data behind `path_or_fileobj`.
Args: with_tqdm (`bool`, *optional*, defaults to `False`): If True, iterating over the file object will display a progress bar. Only works if the file-like object is a path to a file. Pure bytes and buffers are not supported.
Example:
```python >>> operation = CommitOperationAdd( ... path_in_repo="remote/dir/weights.h5", ... path_or_fileobj="./local/weights.h5", ... ) CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
>>> with operation.as_file() as file: ... content = file.read()
>>> with operation.as_file(with_tqdm=True) as file: ... while True: ... data = file.read(1024) ... if not data: ... break config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
>>> with operation.as_file(with_tqdm=True) as file: ... httpx.put(..., data=file) config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s] ``` """ if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path): if with_tqdm: with tqdm_stream_file(self.path_or_fileobj) as file: yield file else: with open(self.path_or_fileobj, "rb") as file: yield file elif isinstance(self.path_or_fileobj, bytes): yield io.BytesIO(self.path_or_fileobj) elif isinstance(self.path_or_fileobj, io.BufferedIOBase): prev_pos = self.path_or_fileobj.tell() yield self.path_or_fileobj self.path_or_fileobj.seek(prev_pos, io.SEEK_SET)
def b64content(self) -> bytes: """ The base64-encoded content of `path_or_fileobj`
Returns: `bytes` """ with self.as_file() as file: return base64.b64encode(file.read())
@property def _local_oid(self) -> str | None: """Return the OID of the local file.
This OID is then compared to `self._remote_oid` to check if the file has changed compared to the remote one. If the file did not change, we won't upload it again to prevent empty commits.
For LFS files, the OID corresponds to the SHA256 of the file content (used a LFS ref). For regular files, the OID corresponds to the SHA1 of the file content. Note: this is slightly different to git OID computation since the oid of an LFS file is usually the git-SHA1 of the pointer file content (not the actual file content). However, using the SHA256 is enough to detect changes and more convenient client-side. """ if self._upload_mode is None: return None elif self._upload_mode == "lfs": return self.upload_info.sha256.hex() else: # Regular file => compute sha1 # => no need to read by chunk since the file is guaranteed to be <=5MB. with self.as_file() as file: return sha.git_hash(file.read())
def _validate_path_in_repo(path_in_repo: str) -> str: # Validate `path_in_repo` value to prevent a server-side issue if path_in_repo.startswith("/"): path_in_repo = path_in_repo[1:] if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"): raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'") if path_in_repo.startswith("./"): path_in_repo = path_in_repo[2:] for forbidden in FORBIDDEN_FOLDERS: if any(part == forbidden for part in path_in_repo.split("/")): raise ValueError( f"Invalid `path_in_repo` in CommitOperation: cannot update files under a '{forbidden}/' folder (path:" f" '{path_in_repo}')." ) return path_in_repo
CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
def _warn_on_overwriting_operations(operations: list[CommitOperation]) -> None: """ Warn user when a list of operations is expected to overwrite itself in a single commit.
Rules: - If a filepath is updated by multiple `CommitOperationAdd` operations, a warning message is triggered. - If a filepath is updated at least once by a `CommitOperationAdd` and then deleted by a `CommitOperationDelete`, a warning is triggered. - If a `CommitOperationDelete` deletes a filepath that is then updated by a `CommitOperationAdd`, no warning is triggered. This is usually useless (no need to delete before upload) but can happen if a user deletes an entire folder and then add new files to it. """ nb_additions_per_path: dict[str, int] = defaultdict(int) for operation in operations: path_in_repo = operation.path_in_repo if isinstance(operation, CommitOperationAdd): if nb_additions_per_path[path_in_repo] > 0: warnings.warn( "About to update multiple times the same file in the same commit:" f" '{path_in_repo}'. This can cause undesired inconsistencies in" " your repo." ) nb_additions_per_path[path_in_repo] += 1 for parent in PurePosixPath(path_in_repo).parents: # Also keep track of number of updated files per folder # => warns if deleting a folder overwrite some contained files nb_additions_per_path[str(parent)] += 1 if isinstance(operation, CommitOperationDelete): if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0: if operation.is_folder: warnings.warn( "About to delete a folder containing files that have just been" f" updated within the same commit: '{path_in_repo}'. This can" " cause undesired inconsistencies in your repo." ) else: warnings.warn( "About to delete a file that have just been updated within the" f" same commit: '{path_in_repo}'. This can cause undesired" " inconsistencies in your repo." )
@validate_hf_hub_argsdef _upload_files( *, additions: list[CommitOperationAdd], repo_type: str, repo_id: str, headers: dict[str, str], endpoint: str | None = None, num_threads: int = 5, revision: str | None = None, create_pr: bool | None = None,): """ Negotiates per-file transfer (LFS vs Xet) and uploads in batches. """ xet_additions: list[CommitOperationAdd] = [] lfs_actions: list[dict[str, Any]] = [] lfs_oid2addop: dict[str, CommitOperationAdd] = {}
for chunk in chunk_iterable(additions, chunk_size=UPLOAD_BATCH_MAX_NUM_FILES): chunk_list = [op for op in chunk]
transfers: list[str] = ["basic", "multipart"] has_buffered_io_data = any(isinstance(op.path_or_fileobj, io.BufferedIOBase) for op in chunk_list) if is_xet_available(): if not has_buffered_io_data: transfers.append("xet") else: logger.warning( "Uploading files as a binary IO buffer is not supported by Xet Storage. " "Falling back to HTTP upload." )
actions_chunk, errors_chunk, chosen_transfer = post_lfs_batch_info( upload_infos=[op.upload_info for op in chunk_list], repo_id=repo_id, repo_type=repo_type, revision=revision, endpoint=endpoint, headers=headers, token=None, # already passed in 'headers' transfers=transfers, ) if errors_chunk: message = "\n".join( [ f"Encountered error for file with OID {err.get('oid')}: `{err.get('error', {}).get('message')}" for err in errors_chunk ] ) raise ValueError(f"LFS batch API returned errors:\n{message}")
# If server returns a transfer we didn't offer (e.g "xet" while uploading from BytesIO), # fall back to LFS for this chunk. if chosen_transfer == "xet" and ("xet" in transfers): xet_additions.extend(chunk_list) else: lfs_actions.extend(actions_chunk) for op in chunk_list: lfs_oid2addop[op.upload_info.sha256.hex()] = op
if len(lfs_actions) > 0: _upload_lfs_files( actions=lfs_actions, oid2addop=lfs_oid2addop, headers=headers, endpoint=endpoint, num_threads=num_threads, )
if len(xet_additions) > 0: _upload_xet_files( additions=xet_additions, repo_type=repo_type, repo_id=repo_id, headers=headers, endpoint=endpoint, revision=revision, create_pr=create_pr, )
@validate_hf_hub_argsdef _upload_lfs_files( *, actions: list[dict[str, Any]], oid2addop: dict[str, CommitOperationAdd], headers: dict[str, str], endpoint: str | None = None, num_threads: int = 5,): """ Uploads the content of `additions` to the Hub using the large file storage protocol.
Relevant external documentation: - LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
Args: actions (`list[dict[str, Any]]`): LFS batch actions returned by the server. oid2addop (`dict[str, CommitOperationAdd]`): A dictionary mapping the OID of the file to the corresponding `CommitOperationAdd` object. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. endpoint (`str`, *optional*): The endpoint to use for the request. Defaults to `constants.ENDPOINT`. num_threads (`int`, *optional*): The number of concurrent threads to use when uploading. Defaults to 5.
Raises: [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) If an upload failed for any reason [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. repo_id (`str`): A namespace (user or an organization) and a repo name separated by a `/`. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. num_threads (`int`, *optional*): The number of concurrent threads to use when uploading. Defaults to 5. revision (`str`, *optional*): The git revision to upload to.
Raises: [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) If an upload failed for any reason [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If the server returns malformed responses [`HfHubHTTPError`] If the LFS batch endpoint returned an HTTP error. """ # Filter out files already present upstream filtered_actions = [] for action in actions: if action.get("actions") is None: logger.debug( f"Content of file {oid2addop[action['oid']].path_in_repo} is already present upstream - skipping upload." ) else: filtered_actions.append(action)
# Upload according to server-provided actions def _wrapped_lfs_upload(batch_action) -> None: try: operation = oid2addop[batch_action["oid"]] lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint) except Exception as exc: raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
if len(filtered_actions) == 1: logger.debug("Uploading 1 LFS file to the Hub") _wrapped_lfs_upload(filtered_actions[0]) else: logger.debug( f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently" ) thread_map( _wrapped_lfs_upload, filtered_actions, desc=f"Upload {len(filtered_actions)} LFS files", max_workers=num_threads, tqdm_class=hf_tqdm, )
@validate_hf_hub_argsdef _upload_xet_files( *, additions: list[CommitOperationAdd], repo_type: str, repo_id: str, headers: dict[str, str], endpoint: str | None = None, revision: str | None = None, create_pr: bool | None = None,): """ Uploads the content of `additions` to the Hub using the xet storage protocol. This chunks the files and deduplicates the chunks before uploading them to xetcas storage.
Args: additions (`` of `CommitOperationAdd`): The files to be uploaded. repo_type (`str`): Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. repo_id (`str`): A namespace (user or an organization) and a repo name separated by a `/`. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. endpoint: (`str`, *optional*): The endpoint to use for the xetcas service. Defaults to `constants.ENDPOINT`. revision (`str`, *optional*): The git revision to upload to. create_pr (`bool`, *optional*): Whether or not to create a Pull Request with that commit.
Raises: [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) If an upload failed for any reason. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If the server returns malformed responses or if the user is unauthorized to upload to xet storage. [`HfHubHTTPError`] If the LFS batch endpoint returned an HTTP error.
**How it works:** The file download system uses Xet storage, which is a content-addressable storage system that breaks files into chunks for efficient storage and transfer.
`hf_xet.upload_files` manages uploading files by: - Taking a list of file paths to upload - Breaking files into smaller chunks for efficient storage - Avoiding duplicate storage by recognizing identical chunks across files - Connecting to a storage server (CAS server) that manages these chunks
The upload process works like this: 1. Create a local folder at ~/.cache/huggingface/xet/chunk-cache to store file chunks for reuse. 2. Process files in parallel (up to 8 files at once): 2.1. Read the file content. 2.2. Split the file content into smaller chunks based on content patterns: each chunk gets a unique ID based on what's in it. 2.3. For each chunk: - Check if it already exists in storage. - Skip uploading chunks that already exist. 2.4. Group chunks into larger blocks for efficient transfer. 2.5. Upload these blocks to the storage server. 2.6. Create and upload information about how the file is structured. 3. Return reference files that contain information about the uploaded files, which can be used later to download them. """ if len(additions) == 0: return
# at this point, we know that hf_xet is installed from hf_xet import upload_bytes, upload_files
from .utils._xet_progress_reporting import XetProgressReporter
try: xet_connection_info = fetch_xet_connection_info_from_repo_info( token_type=XetTokenType.WRITE, repo_id=repo_id, repo_type=repo_type, revision=revision, headers=headers, endpoint=endpoint, params={"create_pr": "1"} if create_pr else None, ) except HfHubHTTPError as e: if e.response.status_code == 401: raise XetAuthorizationError( f"You are unauthorized to upload to xet storage for {repo_type}/{repo_id}. " f"Please check that you have configured your access token with write access to the repo." ) from e raise
xet_endpoint = xet_connection_info.endpoint access_token_info = (xet_connection_info.access_token, xet_connection_info.expiration_unix_epoch)
def token_refresher() -> tuple[str, int]: new_xet_connection = fetch_xet_connection_info_from_repo_info( token_type=XetTokenType.WRITE, repo_id=repo_id, repo_type=repo_type, revision=revision, headers=headers, endpoint=endpoint, params={"create_pr": "1"} if create_pr else None, ) if new_xet_connection is None: raise XetRefreshTokenError("Failed to refresh xet token") return new_xet_connection.access_token, new_xet_connection.expiration_unix_epoch
if not are_progress_bars_disabled(): progress = XetProgressReporter() progress_callback = progress.update_progress else: progress, progress_callback = None, None
try: all_bytes_ops = [op for op in additions if isinstance(op.path_or_fileobj, bytes)] all_paths_ops = [op for op in additions if isinstance(op.path_or_fileobj, (str, Path))]
xet_headers = headers.copy() xet_headers.pop("authorization", None)
if len(all_paths_ops) > 0: all_paths = [str(op.path_or_fileobj) for op in all_paths_ops] all_sha256s = [op.upload_info.sha256.hex() for op in all_paths_ops] upload_files( all_paths, xet_endpoint, access_token_info, token_refresher, progress_callback, repo_type, request_headers=xet_headers, sha256s=all_sha256s, )
if len(all_bytes_ops) > 0: all_bytes = [op.path_or_fileobj for op in all_bytes_ops] all_sha256s = [op.upload_info.sha256.hex() for op in all_bytes_ops] upload_bytes( all_bytes, xet_endpoint, access_token_info, token_refresher, progress_callback, repo_type, request_headers=xet_headers, sha256s=all_sha256s, )
finally: if progress is not None: progress.close(False)
return
def _validate_preupload_info(preupload_info: dict): files = preupload_info.get("files") if not isinstance(files, list): raise ValueError("preupload_info is improperly formatted") for file_info in files: if not ( isinstance(file_info, dict) and isinstance(file_info.get("path"), str) and isinstance(file_info.get("uploadMode"), str) and (file_info["uploadMode"] in ("lfs", "regular")) ): raise ValueError("preupload_info is improperly formatted:") return preupload_info
@validate_hf_hub_argsdef _fetch_upload_modes( additions: Iterable[CommitOperationAdd], repo_type: str, repo_id: str, headers: dict[str, str], revision: str, endpoint: str | None = None, create_pr: bool = False, gitignore_content: str | None = None,) -> None: """ Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob, as a git LFS blob, or as a XET file. Input `additions` are mutated in-place with the upload mode.
Args: additions (`Iterable` of :class:`CommitOperationAdd`): Iterable of :class:`CommitOperationAdd` describing the files to upload to the Hub. repo_type (`str`): Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. repo_id (`str`): A namespace (user or an organization) and a repo name separated by a `/`. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. revision (`str`): The git revision to upload the files to. Can be any valid git revision. gitignore_content (`str`, *optional*): The content of the `.gitignore` file to know which files should be ignored. The order of priority is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub (if any). Raises: [`~utils.HfHubHTTPError`] If the Hub API returned an error. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If the Hub API response is improperly formatted. """ endpoint = endpoint if endpoint is not None else constants.ENDPOINT
# Fetch upload mode (LFS or regular) chunk by chunk. upload_modes: dict[str, UploadMode] = {} should_ignore_info: dict[str, bool] = {} oid_info: dict[str, str | None] = {}
for chunk in chunk_iterable(additions, 256): payload: dict = { "files": [ { "path": op.path_in_repo, "sample": base64.b64encode(op.upload_info.sample).decode("ascii"), "size": op.upload_info.size, } for op in chunk ] } if gitignore_content is not None: payload["gitIgnore"] = gitignore_content
resp = http_backoff( "POST", f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}", json=payload, headers=headers, params={"create_pr": "1"} if create_pr else None, ) hf_raise_for_status(resp) preupload_info = _validate_preupload_info(resp.json()) upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]}) should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]}) oid_info.update(**{file["path"]: file.get("oid") for file in preupload_info["files"]})
# Set upload mode for each addition operation for addition in additions: addition._upload_mode = upload_modes[addition.path_in_repo] addition._should_ignore = should_ignore_info[addition.path_in_repo] addition._remote_oid = oid_info[addition.path_in_repo]
# Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented) # => empty files are uploaded as "regular" to still allow users to commit them. for addition in additions: if addition.upload_info.size == 0: addition._upload_mode = "regular"
@validate_hf_hub_argsdef _fetch_files_to_copy( copies: Iterable[CommitOperationCopy], repo_type: str, repo_id: str, headers: dict[str, str], revision: str, endpoint: str | None = None,) -> dict[tuple[str, str | None], Union["RepoFile", bytes]]: """ Fetch information about the files to copy.
For LFS files, we only need their metadata (file size and sha256) while for regular files we need to download the raw content from the Hub.
Args: copies (`Iterable` of :class:`CommitOperationCopy`): Iterable of :class:`CommitOperationCopy` describing the files to copy on the Hub. repo_type (`str`): Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. repo_id (`str`): A namespace (user or an organization) and a repo name separated by a `/`. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. revision (`str`): The git revision to upload the files to. Can be any valid git revision.
Returns: `dict[tuple[str, Optional[str]], Union[RepoFile, bytes]]]` Key is the file path and revision of the file to copy. Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files).
Raises: [`~utils.HfHubHTTPError`] If the Hub API returned an error. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If the Hub API response is improperly formatted. """ from .hf_api import HfApi, RepoFolder
hf_api = HfApi(endpoint=endpoint, headers=headers) files_to_copy: dict[tuple[str, str | None], Union["RepoFile", bytes]] = {} # Store (path, revision) -> oid mapping oid_info: dict[tuple[str, str | None], str | None] = {} # 1. Fetch OIDs for destination paths in batches. dest_paths = [op.path_in_repo for op in copies] for offset in range(0, len(dest_paths), FETCH_LFS_BATCH_SIZE): dest_repo_files = hf_api.get_paths_info( repo_id=repo_id, paths=dest_paths[offset : offset + FETCH_LFS_BATCH_SIZE], revision=revision, repo_type=repo_type, ) for file in dest_repo_files: if not isinstance(file, RepoFolder): oid_info[(file.path, revision)] = file.blob_id
# 2. Group by source revision and fetch source file info in batches. for src_revision, operations in groupby(copies, key=lambda op: op.src_revision): operations = list(operations) # type: ignore src_paths = [op.src_path_in_repo for op in operations] for offset in range(0, len(src_paths), FETCH_LFS_BATCH_SIZE): src_repo_files = hf_api.get_paths_info( repo_id=repo_id, paths=src_paths[offset : offset + FETCH_LFS_BATCH_SIZE], revision=src_revision or revision, repo_type=repo_type, )
for src_repo_file in src_repo_files: if isinstance(src_repo_file, RepoFolder): raise NotImplementedError("Copying a folder is not implemented.") oid_info[(src_repo_file.path, src_revision)] = src_repo_file.blob_id # If it's an LFS file, store the RepoFile object. Otherwise, download raw bytes. if src_repo_file.lfs: files_to_copy[(src_repo_file.path, src_revision)] = src_repo_file else: # TODO: (optimization) download regular files to copy concurrently url = hf_hub_url( endpoint=endpoint, repo_type=repo_type, repo_id=repo_id, revision=src_revision or revision, filename=src_repo_file.path, ) response = get_session().get(url, headers=headers) hf_raise_for_status(response) files_to_copy[(src_repo_file.path, src_revision)] = response.content # 3. Ensure all operations found a corresponding file in the Hub # and track src/dest OIDs for each operation. for operation in operations: if (operation.src_path_in_repo, src_revision) not in files_to_copy: raise EntryNotFoundError( f"Cannot copy {operation.src_path_in_repo} at revision " f"{src_revision or revision}: file is missing on repo." ) operation._src_oid = oid_info.get((operation.src_path_in_repo, operation.src_revision)) operation._dest_oid = oid_info.get((operation.path_in_repo, revision)) return files_to_copy
def _prepare_commit_payload( operations: Iterable[CommitOperation], files_to_copy: dict[tuple[str, str | None], Union["RepoFile", bytes]], commit_message: str, commit_description: str | None = None, parent_commit: str | None = None,) -> Iterable[dict[str, Any]]: """ Builds the payload to POST to the `/commit` API of the Hub.
Payload is returned as an iterator so that it can be streamed as a ndjson in the POST request.
For more information, see: - https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073 - http://ndjson.org/ """ commit_description = commit_description if commit_description is not None else ""
# 1. Send a header item with the commit metadata header_value = {"summary": commit_message, "description": commit_description} if parent_commit is not None: header_value["parentCommit"] = parent_commit yield {"key": "header", "value": header_value}
nb_ignored_files = 0
# 2. Send operations, one per line for operation in operations: # Skip ignored files if isinstance(operation, CommitOperationAdd) and operation._should_ignore: logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).") nb_ignored_files += 1 continue
# 2.a. Case adding a regular file if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular": yield { "key": "file", "value": { "content": operation.b64content().decode(), "path": operation.path_in_repo, "encoding": "base64", }, } # 2.b. Case adding an LFS file elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs": yield { "key": "lfsFile", "value": { "path": operation.path_in_repo, "algo": "sha256", "oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size, }, } # 2.c. Case deleting a file or folder elif isinstance(operation, CommitOperationDelete): yield { "key": "deletedFolder" if operation.is_folder else "deletedFile", "value": {"path": operation.path_in_repo}, } # 2.d. Case copying a file or folder elif isinstance(operation, CommitOperationCopy): file_to_copy = files_to_copy[(operation.src_path_in_repo, operation.src_revision)] if isinstance(file_to_copy, bytes): yield { "key": "file", "value": { "content": base64.b64encode(file_to_copy).decode(), "path": operation.path_in_repo, "encoding": "base64", }, } elif file_to_copy.lfs: yield { "key": "lfsFile", "value": { "path": operation.path_in_repo, "algo": "sha256", "oid": file_to_copy.lfs.sha256, }, } else: raise ValueError( "Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info." ) # 2.e. Never expected to happen else: raise ValueError( f"Unknown operation to commit. Operation: {operation}. Upload mode:" f" {getattr(operation, '_upload_mode', None)}" )
if nb_ignored_files > 0: logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353import atexitimport loggingimport osimport timefrom concurrent.futures import Futurefrom dataclasses import dataclassfrom io import SEEK_END, SEEK_SET, BytesIOfrom pathlib import Pathfrom threading import Lock, Threadfrom typing import Optional
from .hf_api import DEFAULT_IGNORE_PATTERNS, CommitInfo, CommitOperationAdd, HfApifrom .utils import filter_repo_objects
logger = logging.getLogger(__name__)
@dataclass(frozen=True)class _FileToUpload: """Temporary dataclass to store info about files to upload. Not meant to be used directly."""
local_path: Path path_in_repo: str size_limit: int last_modified: float
class CommitScheduler: """ Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads) to learn more about how to use it.
Args: repo_id (`str`): The id of the repo to commit to. folder_path (`str` or `Path`): Path to the local folder to upload regularly. every (`int` or `float`, *optional*): The number of minutes between each commit. Defaults to 5 minutes. path_in_repo (`str`, *optional*): Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder of the repository. repo_type (`str`, *optional*): The type of the repo to commit to. Defaults to `model`. revision (`str`, *optional*): The revision of the repo to commit to. Defaults to `main`. private (`bool`, *optional*): Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. token (`str`, *optional*): The token to use to commit to the repo. Defaults to the token saved on the machine. allow_patterns (`list[str]` or `str`, *optional*): If provided, only files matching at least one pattern are uploaded. ignore_patterns (`list[str]` or `str`, *optional*): If provided, files matching any of the patterns are not uploaded. squash_history (`bool`, *optional*): Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is useful to avoid degraded performances on the repo when it grows too large. hf_api (`HfApi`, *optional*): The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
Example: ```py >>> from pathlib import Path >>> from huggingface_hub import CommitScheduler
# Scheduler uploads every 10 minutes >>> csv_path = Path("watched_folder/data.csv") >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
>>> with csv_path.open("a") as f: ... f.write("first line")
# Some time later (...) >>> with csv_path.open("a") as f: ... f.write("second line") ```
Example using a context manager: ```py >>> from pathlib import Path >>> from huggingface_hub import CommitScheduler
>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler: ... csv_path = Path("watched_folder/data.csv") ... with csv_path.open("a") as f: ... f.write("first line") ... (...) ... with csv_path.open("a") as f: ... f.write("second line")
# Scheduler is now stopped and last commit have been triggered ``` """
def __init__( self, *, repo_id: str, folder_path: str | Path, every: int | float = 5, path_in_repo: str | None = None, repo_type: str | None = None, revision: str | None = None, private: bool | None = None, token: str | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, squash_history: bool = False, hf_api: Optional["HfApi"] = None, ) -> None: self.api = hf_api or HfApi(token=token)
# Folder self.folder_path = Path(folder_path).expanduser().resolve() self.path_in_repo = path_in_repo or "" self.allow_patterns = allow_patterns
if ignore_patterns is None: ignore_patterns = [] elif isinstance(ignore_patterns, str): ignore_patterns = [ignore_patterns] self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
if self.folder_path.is_file(): raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.") self.folder_path.mkdir(parents=True, exist_ok=True)
# Repository repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True) self.repo_id = repo_url.repo_id self.repo_type = repo_type self.revision = revision self.token = token
# Keep track of already uploaded files self.last_uploaded: dict[Path, float] = {} # key is local path, value is timestamp
# Scheduler if not every > 0: raise ValueError(f"'every' must be a positive integer, not '{every}'.") self.lock = Lock() self.every = every self.squash_history = squash_history
logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.") self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True) self._scheduler_thread.start() atexit.register(self._push_to_hub)
self.__stopped = False
def stop(self) -> None: """Stop the scheduler.
A stopped scheduler cannot be restarted. Mostly for tests purposes. """ self.__stopped = True
def __enter__(self) -> "CommitScheduler": return self
def __exit__(self, exc_type, exc_value, traceback) -> None: # Upload last changes before exiting self.trigger().result() self.stop() return
def _run_scheduler(self) -> None: """Dumb thread waiting between each scheduled push to Hub.""" while True: self.last_future = self.trigger() time.sleep(self.every * 60) if self.__stopped: break
def trigger(self) -> Future: """Trigger a `push_to_hub` and return a future.
This method is automatically called every `every` minutes. You can also call it manually to trigger a commit immediately, without waiting for the next scheduled commit. """ return self.api.run_as_future(self._push_to_hub)
def _push_to_hub(self) -> CommitInfo | None: if self.__stopped: # If stopped, already scheduled commits are ignored return None
logger.info("(Background) scheduled commit triggered.") try: value = self.push_to_hub() if self.squash_history: logger.info("(Background) squashing repo history.") self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision) return value except Exception as e: logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced raise
def push_to_hub(self) -> CommitInfo | None: """ Push folder to the Hub and return the commit info.
> [!WARNING] > This method is not meant to be called directly. It is run in the background by the scheduler, respecting a > queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency > issues.
The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and uploads only changed files. If no changes are found, the method returns without committing anything. If you want to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful for example to compress data together in a single file before committing. For more details and examples, check out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads). """ # Check files to upload (with lock) with self.lock: logger.debug("Listing files to upload for scheduled commit.")
# List files from folder (taken from `_prepare_upload_folder_additions`) relpath_to_abspath = { path.relative_to(self.folder_path).as_posix(): path for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic if path.is_file() } prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
# Filter with pattern + filter out unchanged files + retrieve current file size files_to_upload: list[_FileToUpload] = [] for relpath in filter_repo_objects( relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns ): local_path = relpath_to_abspath[relpath] stat = local_path.stat() if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime: files_to_upload.append( _FileToUpload( local_path=local_path, path_in_repo=prefix + relpath, size_limit=stat.st_size, last_modified=stat.st_mtime, ) )
# Return if nothing to upload if len(files_to_upload) == 0: logger.debug("Dropping schedule commit: no changed file to upload.") return None
# Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size) logger.debug("Removing unchanged files since previous scheduled commit.") add_operations = [ CommitOperationAdd( # Cap the file to its current size, even if the user append data to it while a scheduled commit is happening path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit), path_in_repo=file_to_upload.path_in_repo, ) for file_to_upload in files_to_upload ]
# Upload files (append mode expected - no need for lock) logger.debug("Uploading files for scheduled commit.") commit_info = self.api.create_commit( repo_id=self.repo_id, repo_type=self.repo_type, operations=add_operations, commit_message="Scheduled Commit", revision=self.revision, )
# Successful commit: keep track of the latest "last_modified" for each file for file in files_to_upload: self.last_uploaded[file.local_path] = file.last_modified return commit_info
class PartialFileIO(BytesIO): """A file-like object that reads only the first part of a file.
Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the file is uploaded (i.e. the part that was available when the filesystem was first scanned).
In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal disturbance for the user. The object is passed to `CommitOperationAdd`.
Only supports `read`, `tell` and `seek` methods.
Args: file_path (`str` or `Path`): Path to the file to read. size_limit (`int`): The maximum number of bytes to read from the file. If the file is larger than this, only the first part will be read (and uploaded). """
def __init__(self, file_path: str | Path, size_limit: int) -> None: self._file_path = Path(file_path) self._file = self._file_path.open("rb") self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
def __del__(self) -> None: self._file.close() return super().__del__()
def __repr__(self) -> str: return f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
def __len__(self) -> int: return self._size_limit
def __getattribute__(self, name: str): if name.startswith("_") or name in ("read", "tell", "seek", "fileno"): # only 4 public methods supported return super().__getattribute__(name) raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
def fileno(self): raise AttributeError("PartialFileIO does not have a fileno.")
def tell(self) -> int: """Return the current file position.""" return self._file.tell()
def seek(self, __offset: int, __whence: int = SEEK_SET) -> int: """Change the stream position to the given offset.
Behavior is the same as a regular file, except that the position is capped to the size limit. """ if __whence == SEEK_END: # SEEK_END => set from the truncated end __offset = len(self) + __offset __whence = SEEK_SET
pos = self._file.seek(__offset, __whence) if pos > self._size_limit: return self._file.seek(self._size_limit) return pos
def read(self, __size: int | None = -1) -> bytes: """Read at most `__size` bytes from the file.
Behavior is the same as a regular file, except that it is capped to the size limit. """ current = self._file.tell() if __size is None or __size < 0: # Read until file limit truncated_size = self._size_limit - current else: # Read until file limit or __size truncated_size = min(__size, self._size_limit - current) return self._file.read(truncated_size)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import jsonimport osimport shutilimport subprocessfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Union
from . import constantsfrom .utils import get_token
if TYPE_CHECKING: import duckdb
@dataclass(frozen=True)class DatasetParquetEntry: """Represents a single parquet file available for a dataset on the Hub."""
config: str split: str url: str size: int
def execute_raw_sql_query(sql_query: str, *, token: str | bool | None = None) -> list[dict[str, Any]]: normalized_query = sql_query.strip().rstrip(";").strip() _raise_on_forbidden_query(normalized_query)
connection = None try: connection = _get_duckdb_connection(token=token) relation = connection.sql(normalized_query) if relation is None: raise ValueError("SQL query must return rows.")
if isinstance(relation, _DuckDBCliRelation): # DuckDB binary => run CLI => parse JSON return relation.execute() else: # DuckDB Python API => fetch columns + rows => convert to dicts columns = tuple(column[0] for column in relation.description) rows = tuple(tuple(row) for row in relation.fetchall()) return [dict(zip(columns, row)) for row in rows] finally: if connection is not None: connection.close()
def _raise_on_forbidden_query(query: str) -> None: if len(query) == 0: raise ValueError("SQL query cannot be empty.")
# DuckDB CLI meta-commands are dot-prefixed words (e.g. `.shell`, `.output`). # Let's forbid them for now but allow SQL expressions like `.5` that can legitimately start a line. for line in query.splitlines(): stripped = line.lstrip() if stripped.startswith(".") and stripped[1:2].isalpha(): raise ValueError("DuckDB CLI meta-commands are not allowed in SQL queries.")
def _get_duckdb_connection( token: str | bool | None,) -> Union["duckdb.DuckDBPyConnection", "_DuckDBCliConnection"]: try: # If DuckDB is installed as a Python package, use it! import duckdb except ImportError as error: # Otherwise, use the DuckDB CLI binary. duckdb_binary = shutil.which("duckdb") if duckdb_binary is None: raise ImportError( "DuckDB is required for `hf datasets sql`. Install the Python package with `pip install duckdb` or " "install the DuckDB CLI binary (for example `brew install duckdb`)." ) from error return _DuckDBCliConnection(binary_path=duckdb_binary, token=token)
# Create a new connection (Python API). connection = duckdb.connect() try: for statement in _build_duckdb_secret_statements(token): connection.execute(statement) return connection except Exception: connection.close() raise
@dataclassclass _DuckDBCliConnection: """DuckDB connection.
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary. """
binary_path: str token: str | bool | None
def __post_init__(self) -> None: self._setup_statements = _build_duckdb_secret_statements(self.token)
def sql(self, query: str) -> "_DuckDBCliRelation": return _DuckDBCliRelation(binary_path=self.binary_path, setup_statements=self._setup_statements, query=query)
def close(self) -> None: pass
@dataclassclass _DuckDBCliRelation: """DuckDB relation.
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary. """
binary_path: str setup_statements: list[str] query: str
def execute(self) -> list[dict[str, Any]]: # Build the DuckDB CLI input. setup = [] if self.setup_statements: setup = [ f".output {os.devnull}", *(f"{stmt};" for stmt in self.setup_statements), ".output", ] full_query = "\n".join(setup + [self.query + ";"])
# Run DuckDB binary result = subprocess.run( [self.binary_path, "-json"], input=full_query, capture_output=True, text=True, check=False, ) if result.returncode != 0: error_message = result.stderr.strip() or result.stdout.strip() or "DuckDB CLI command failed." raise RuntimeError(error_message)
# Parse JSON output and return return json.loads(result.stdout.strip())
def _build_duckdb_secret_statements(token: str | bool | None) -> list[str]: if token is None or token is True: token = get_token()
if not token: return []
escaped_token = token.replace("'", "''") escaped_endpoint = constants.ENDPOINT.replace("'", "''") return [ f"CREATE OR REPLACE SECRET hf_hub_token (TYPE HTTP, BEARER_TOKEN '{escaped_token}', SCOPE '{escaped_endpoint}')", f"CREATE OR REPLACE SECRET hf_token (TYPE HUGGINGFACE, TOKEN '{escaped_token}')", ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211"""Evaluation results utilities for the `.eval_results/*.yaml` format.
See https://huggingface.co/docs/hub/eval-results for more details.Specifications are available at https://github.com/huggingface/hub-docs/blob/main/eval_results.yaml."""
from dataclasses import dataclassfrom typing import Any
@dataclassclass EvalResultEntry: """ Evaluation result entry for the `.eval_results/*.yaml` format.
Represents evaluation scores stored in model repos that automatically appear on the model page and the benchmark dataset's leaderboard.
For the legacy `model-index` format in `README.md`, use [`EvalResult`] instead.
See https://huggingface.co/docs/hub/eval-results for more details.
Args: dataset_id (`str`): Benchmark dataset ID from the Hub. Example: "cais/hle", "Idavidrein/gpqa". task_id (`str`): Task identifier within the benchmark. Example: "gpqa_diamond". value (`Any`): The metric value. Example: 20.90. dataset_revision (`str`, *optional*): Git SHA of the benchmark dataset. verify_token (`str`, *optional*): A signature that can be used to prove that evaluation is provably auditable and reproducible. date (`str`, *optional*): When the evaluation was run (ISO-8601 datetime). Defaults to git commit time. source_url (`str`, *optional*): Link to the evaluation source (e.g., https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro). Required if `source_name`, `source_user`, or `source_org` is provided. source_name (`str`, *optional*): Display name for the source. Example: "Eval Logs". source_user (`str`, *optional*): HF user name for attribution. Example: "celinah". source_org (`str`, *optional*): HF org name for attribution. Example: "cais". notes (`str`, *optional*): Details about the evaluation setup. Example: "tools", "no-tools", "chain-of-thought".
Example: ```python >>> from huggingface_hub import EvalResultEntry >>> # Minimal example with required fields only >>> result = EvalResultEntry( ... dataset_id="Idavidrein/gpqa", ... task_id="gpqa_diamond", ... value=0.412, ... ) >>> # Full example with all fields >>> result = EvalResultEntry( ... dataset_id="cais/hle", ... task_id="default", ... value=20.90, ... dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb", ... verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", ... date="2025-01-15T10:30:00Z", ... source_url="https://huggingface.co/datasets/cais/hle", ... source_name="CAIS HLE", ... source_org="cais", ... notes="no-tools", ... )
``` """
dataset_id: str task_id: str value: Any dataset_revision: str | None = None verify_token: str | None = None date: str | None = None source_url: str | None = None source_name: str | None = None source_user: str | None = None source_org: str | None = None notes: str | None = None
def __post_init__(self) -> None: if ( self.source_name is not None or self.source_user is not None or self.source_org is not None ) and self.source_url is None: raise ValueError( "If `source_name`, `source_user`, or `source_org` is provided, `source_url` must also be provided." )
def eval_result_entries_to_yaml(entries: list[EvalResultEntry]) -> list[dict[str, Any]]: """Convert a list of [`EvalResultEntry`] objects to a YAML-serializable list of dicts.
This produces the format expected in `.eval_results/*.yaml` files.
Args: entries (`list[EvalResultEntry]`): List of evaluation result entries to serialize.
Returns: `list[dict[str, Any]]`: A list of dictionaries ready to be dumped to YAML.
Example: ```python >>> from huggingface_hub import EvalResultEntry, eval_result_entries_to_yaml >>> entries = [ ... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90), ... EvalResultEntry(dataset_id="Idavidrein/gpqa", task_id="gpqa_diamond", value=0.412), ... ] >>> yaml_data = eval_result_entries_to_yaml(entries) >>> yaml_data[0] {'dataset': {'id': 'cais/hle', 'task_id': 'default'}, 'value': 20.9}
```
To upload eval results to the Hub: ```python >>> import yaml >>> from huggingface_hub import upload_file, EvalResultEntry, eval_result_entries_to_yaml >>> entries = [ ... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90), ... ] >>> yaml_content = yaml.dump(eval_result_entries_to_yaml(entries)) >>> upload_file( ... path_or_fileobj=yaml_content.encode(), ... path_in_repo=".eval_results/hle.yaml", ... repo_id="your-username/your-model", ... )
``` """ result = [] for entry in entries: # build the dataset object dataset: dict[str, Any] = {"id": entry.dataset_id, "task_id": entry.task_id} if entry.dataset_revision is not None: dataset["revision"] = entry.dataset_revision
data: dict[str, Any] = {"dataset": dataset, "value": entry.value} if entry.verify_token is not None: data["verifyToken"] = entry.verify_token if entry.date is not None: data["date"] = entry.date # build the source object if entry.source_url is not None: source: dict[str, Any] = {"url": entry.source_url} if entry.source_name is not None: source["name"] = entry.source_name if entry.source_user is not None: source["user"] = entry.source_user if entry.source_org is not None: source["org"] = entry.source_org data["source"] = source if entry.notes is not None: data["notes"] = entry.notes
result.append(data) return result
def parse_eval_result_entries(data: list[dict[str, Any]]) -> list[EvalResultEntry]: """Parse a list of dicts into [`EvalResultEntry`] objects.
This parses the `.eval_results/*.yaml` format. For the legacy `model-index` format, use [`model_index_to_eval_results`] instead.
Args: data (`list[dict[str, Any]]`): A list of dictionaries (e.g., parsed from YAML or API response).
Returns: `list[EvalResultEntry]`: A list of evaluation result entry objects.
Example: ```python >>> from huggingface_hub import parse_eval_result_entries >>> data = [ ... {"dataset": {"id": "cais/hle", "task_id": "default"}, "value": 20.90}, ... {"dataset": {"id": "Idavidrein/gpqa", "task_id": "gpqa_diamond"}, "value": 0.412}, ... ] >>> entries = parse_eval_result_entries(data) >>> entries[0].dataset_id 'cais/hle' >>> entries[0].value 20.9
``` """ entries = [] for item in data: entry_data = item.get("data", item) dataset = entry_data.get("dataset", {}) source = entry_data.get("source", {}) entry = EvalResultEntry( dataset_id=dataset["id"], value=entry_data["value"], task_id=dataset["task_id"], dataset_revision=dataset.get("revision"), verify_token=entry_data.get("verifyToken"), date=entry_data.get("date"), source_url=source.get("url") if source else None, source_name=source.get("name") if source else None, source_user=source.get("user") if source else None, source_org=source.get("org") if source else None, notes=entry_data.get("notes"), ) entries.append(entry) return entries123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418import timefrom dataclasses import dataclass, fieldfrom datetime import datetimefrom enum import Enumfrom typing import TYPE_CHECKING, Optional
from huggingface_hub.errors import InferenceEndpointError, InferenceEndpointTimeoutError
from .utils import get_session, logging, parse_datetime
if TYPE_CHECKING: from .hf_api import HfApi from .inference._client import InferenceClient from .inference._generated._async_client import AsyncInferenceClient
logger = logging.get_logger(__name__)
class InferenceEndpointStatus(str, Enum): PENDING = "pending" INITIALIZING = "initializing" UPDATING = "updating" UPDATE_FAILED = "updateFailed" RUNNING = "running" PAUSED = "paused" FAILED = "failed" SCALED_TO_ZERO = "scaledToZero"
class InferenceEndpointType(str, Enum): PUBlIC = "public" PROTECTED = "protected" PRIVATE = "private"
class InferenceEndpointScalingMetric(str, Enum): PENDING_REQUESTS = "pendingRequests" HARDWARE_USAGE = "hardwareUsage"
@dataclassclass InferenceEndpoint: """ Contains information about a deployed Inference Endpoint.
Args: name (`str`): The unique name of the Inference Endpoint. namespace (`str`): The namespace where the Inference Endpoint is located. repository (`str`): The name of the model repository deployed on this Inference Endpoint. status ([`InferenceEndpointStatus`]): The current status of the Inference Endpoint. url (`str`, *optional*): The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL. framework (`str`): The machine learning framework used for the model. revision (`str`): The specific model revision deployed on the Inference Endpoint. task (`str`): The task associated with the deployed model. created_at (`datetime.datetime`): The timestamp when the Inference Endpoint was created. updated_at (`datetime.datetime`): The timestamp of the last update of the Inference Endpoint. type ([`InferenceEndpointType`]): The type of the Inference Endpoint (public, protected, private). raw (`dict`): The raw dictionary data returned from the API. token (`str` or `bool`, *optional*): Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server.
Example: ```python >>> from huggingface_hub import get_inference_endpoint >>> endpoint = get_inference_endpoint("my-text-to-image") >>> endpoint InferenceEndpoint(name='my-text-to-image', ...)
# Get status >>> endpoint.status 'running' >>> endpoint.url 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
# Run inference >>> endpoint.client.text_to_image(...)
# Pause endpoint to save $$$ >>> endpoint.pause()
# ... # Resume and wait for deployment >>> endpoint.resume() >>> endpoint.wait() >>> endpoint.client.text_to_image(...) ``` """
# Field in __repr__ name: str = field(init=False) namespace: str repository: str = field(init=False) status: InferenceEndpointStatus = field(init=False) health_route: str = field(init=False) url: str | None = field(init=False)
# Other fields framework: str = field(repr=False, init=False) revision: str = field(repr=False, init=False) task: str = field(repr=False, init=False) created_at: datetime = field(repr=False, init=False) updated_at: datetime = field(repr=False, init=False) type: InferenceEndpointType = field(repr=False, init=False)
# Raw dict from the API raw: dict = field(repr=False)
# Internal fields _token: str | bool | None = field(repr=False, compare=False) _api: "HfApi" = field(repr=False, compare=False)
@classmethod def from_raw( cls, raw: dict, namespace: str, token: str | bool | None = None, api: Optional["HfApi"] = None ) -> "InferenceEndpoint": """Initialize object from raw dictionary.""" if api is None: from .hf_api import HfApi
api = HfApi() if token is None: token = api.token
# All other fields are populated in __post_init__ return cls(raw=raw, namespace=namespace, _token=token, _api=api)
def __post_init__(self) -> None: """Populate fields from raw dictionary.""" self._populate_from_raw()
@property def client(self) -> "InferenceClient": """Returns a client to make predictions on this Inference Endpoint.
Returns: [`InferenceClient`]: an inference client pointing to the deployed endpoint.
Raises: [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed. """ if self.url is None: raise InferenceEndpointError( "Cannot create a client for this Inference Endpoint as it is not yet deployed. " "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again." ) from .inference._client import InferenceClient
return InferenceClient( model=self.url, token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok. )
@property def async_client(self) -> "AsyncInferenceClient": """Returns a client to make predictions on this Inference Endpoint.
Returns: [`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint.
Raises: [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed. """ if self.url is None: raise InferenceEndpointError( "Cannot create a client for this Inference Endpoint as it is not yet deployed. " "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again." ) from .inference._generated._async_client import AsyncInferenceClient
return AsyncInferenceClient( model=self.url, token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok. )
def wait(self, timeout: int | None = None, refresh_every: int = 5) -> "InferenceEndpoint": """Wait for the Inference Endpoint to be deployed.
Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout` seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest data.
Args: timeout (`int`, *optional*): The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait indefinitely. refresh_every (`int`, *optional*): The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s.
Returns: [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
Raises: [`InferenceEndpointError`] If the Inference Endpoint ended up in a failed state. [`InferenceEndpointTimeoutError`] If the Inference Endpoint is not deployed after `timeout` seconds. """ if timeout is not None and timeout < 0: raise ValueError("`timeout` cannot be negative.") if refresh_every <= 0: raise ValueError("`refresh_every` must be positive.")
start = time.time() while True: if self.status == InferenceEndpointStatus.FAILED: raise InferenceEndpointError( f"Inference Endpoint {self.name} failed to deploy. Please check the logs for more information." ) if self.status == InferenceEndpointStatus.UPDATE_FAILED: raise InferenceEndpointError( f"Inference Endpoint {self.name} failed to update. Please check the logs for more information." ) if self.status == InferenceEndpointStatus.RUNNING and self.url is not None: # Verify the endpoint is actually reachable _health_url = f"{self.url.rstrip('/')}/{self.health_route.lstrip('/')}" response = get_session().get(_health_url, headers=self._api._build_hf_headers(token=self._token)) if response.status_code == 200: logger.info("Inference Endpoint is ready to be used.") return self
if timeout is not None: if time.time() - start > timeout: raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.") logger.info(f"Inference Endpoint is not deployed yet ({self.status}). Waiting {refresh_every}s...") time.sleep(refresh_every) self.fetch()
def fetch(self) -> "InferenceEndpoint": """Fetch latest information about the Inference Endpoint.
Returns: [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. """ obj = self._api.get_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] self.raw = obj.raw self._populate_from_raw() return self
def update( self, *, # Compute update accelerator: str | None = None, instance_size: str | None = None, instance_type: str | None = None, min_replica: int | None = None, max_replica: int | None = None, scale_to_zero_timeout: int | None = None, # Model update repository: str | None = None, framework: str | None = None, revision: str | None = None, task: str | None = None, custom_image: dict | None = None, secrets: dict[str, str] | None = None, ) -> "InferenceEndpoint": """Update the Inference Endpoint.
This method allows the update of either the compute configuration, the deployed model, or both. All arguments are optional but at least one must be provided.
This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the latest data from the server.
Args: accelerator (`str`, *optional*): The hardware accelerator to be used for inference (e.g. `"cpu"`). instance_size (`str`, *optional*): The size or type of the instance to be used for hosting the model (e.g. `"x4"`). instance_type (`str`, *optional*): The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`). min_replica (`int`, *optional*): The minimum number of replicas (instances) to keep running for the Inference Endpoint. max_replica (`int`, *optional*): The maximum number of replicas (instances) to scale to for the Inference Endpoint. scale_to_zero_timeout (`int`, *optional*): The duration in minutes before an inactive endpoint is scaled to zero.
repository (`str`, *optional*): The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). framework (`str`, *optional*): The machine learning framework used for the model (e.g. `"custom"`). revision (`str`, *optional*): The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). task (`str`, *optional*): The task on which to deploy the model (e.g. `"text-classification"`). custom_image (`dict`, *optional*): A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples). secrets (`dict[str, str]`, *optional*): Secret values to inject in the container environment. Returns: [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. """ # Make API call obj = self._api.update_inference_endpoint( name=self.name, namespace=self.namespace, accelerator=accelerator, instance_size=instance_size, instance_type=instance_type, min_replica=min_replica, max_replica=max_replica, scale_to_zero_timeout=scale_to_zero_timeout, repository=repository, framework=framework, revision=revision, task=task, custom_image=custom_image, secrets=secrets, token=self._token, # type: ignore [arg-type] )
# Mutate current object self.raw = obj.raw self._populate_from_raw() return self
def pause(self) -> "InferenceEndpoint": """Pause the Inference Endpoint.
A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`]. This is different from scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which would be automatically restarted when a request is made to it.
This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the latest data from the server.
Returns: [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. """ obj = self._api.pause_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] self.raw = obj.raw self._populate_from_raw() return self
def resume(self, running_ok: bool = True) -> "InferenceEndpoint": """Resume the Inference Endpoint.
This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the latest data from the server.
Args: running_ok (`bool`, *optional*): If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to `True`.
Returns: [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. """ obj = self._api.resume_inference_endpoint( name=self.name, namespace=self.namespace, running_ok=running_ok, token=self._token ) # type: ignore [arg-type] self.raw = obj.raw self._populate_from_raw() return self
def scale_to_zero(self) -> "InferenceEndpoint": """Scale Inference Endpoint to zero.
An Inference Endpoint scaled to zero will not be charged. It will be resumed on the next request to it, with a cold start delay. This is different from pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which would require a manual resume with [`InferenceEndpoint.resume`].
This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the latest data from the server.
Returns: [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. """ obj = self._api.scale_to_zero_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] self.raw = obj.raw self._populate_from_raw() return self
def delete(self) -> None: """Delete the Inference Endpoint.
This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`].
This is an alias for [`HfApi.delete_inference_endpoint`]. """ self._api.delete_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
def _populate_from_raw(self) -> None: """Populate fields from raw dictionary.
Called in __post_init__ + each time the Inference Endpoint is updated. """ # Repr fields self.name = self.raw["name"] self.repository = self.raw["model"]["repository"] self.status = self.raw["status"]["state"] self.url = self.raw["status"].get("url") self.health_route = self.raw["healthRoute"]
# Other fields self.framework = self.raw["model"]["framework"] self.revision = self.raw["model"]["revision"] self.task = self.raw["model"]["task"] self.created_at = parse_datetime(self.raw["status"]["createdAt"]) self.updated_at = parse_datetime(self.raw["status"]["updatedAt"]) self.type = self.raw["type"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410# Copyright 2025-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.from dataclasses import dataclassfrom datetime import datetimefrom enum import Enumfrom typing import Any
from huggingface_hub import constantsfrom huggingface_hub._space_api import SpaceHardware, Volumefrom huggingface_hub.utils._datetime import parse_datetime
class JobStage(str, Enum): """ Enumeration of possible stage of a Job on the Hub.
Value can be compared to a string: ```py assert JobStage.COMPLETED == "COMPLETED" ``` Possible values are: `COMPLETED`, `CANCELED`, `ERROR`, `DELETED`, `RUNNING`. Taken from https://github.com/huggingface/moon-landing/blob/main/server/job_types/JobInfo.ts#L61 (private url). """
# Copied from moon-landing > server > lib > Job.ts COMPLETED = "COMPLETED" CANCELED = "CANCELED" ERROR = "ERROR" DELETED = "DELETED" RUNNING = "RUNNING"
@dataclassclass JobStatus: stage: JobStage message: str | None
@dataclassclass JobOwner: id: str name: str type: str
@dataclassclass JobInfo: """ Contains information about a Job.
Args: id (`str`): Job ID. created_at (`datetime` or `None`): When the Job was created. docker_image (`str` or `None`): The Docker image from Docker Hub used for the Job. Can be None if space_id is present instead. space_id (`str` or `None`): The Docker image from Hugging Face Spaces used for the Job. Can be None if docker_image is present instead. command (`list[str]` or `None`): Command of the Job, e.g. `["python", "-c", "print('hello world')"]` arguments (`list[str]` or `None`): Arguments passed to the command environment (`dict[str]` or `None`): Environment variables of the Job as a dictionary. secrets (`dict[str]` or `None`): Secret environment variables of the Job (encrypted). flavor (`str` or `None`): Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values. E.g. `"cpu-basic"`. labels (`dict[str, str]` or `None`): Labels to attach to the job (key-value pairs). volumes (`list[Volume]` or `None`): Volumes mounted in the job container (buckets, models, datasets, spaces). status: (`JobStatus` or `None`): Status of the Job, e.g. `JobStatus(stage="RUNNING", message=None)` See [`JobStage`] for possible stage values. owner: (`JobOwner` or `None`): Owner of the Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")`
Example:
```python >>> from huggingface_hub import run_job >>> job = run_job( ... image="python:3.12", ... command=["python", "-c", "print('Hello from the cloud!')"] ... ) >>> job JobInfo(id='687fb701029421ae5549d998', created_at=datetime.datetime(2025, 7, 22, 16, 6, 25, 79000, tzinfo=datetime.timezone.utc), docker_image='python:3.12', space_id=None, command=['python', '-c', "print('Hello from the cloud!')"], arguments=[], environment={}, secrets={}, flavor='cpu-basic', labels=None, status=JobStatus(stage='RUNNING', message=None), owner=JobOwner(id='5e9ecfc04957053f60648a3e', name='lhoestq', type='user'), endpoint='https://huggingface.co', url='https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998') >>> job.id '687fb701029421ae5549d998' >>> job.url 'https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998' >>> job.status.stage 'RUNNING' ``` """
id: str created_at: datetime | None docker_image: str | None space_id: str | None command: list[str] | None arguments: list[str] | None environment: dict[str, Any] | None secrets: dict[str, Any] | None flavor: SpaceHardware | None labels: dict[str, str] | None volumes: list[Volume] | None status: JobStatus owner: JobOwner
# Inferred fields endpoint: str url: str
def __init__(self, **kwargs) -> None: self.id = kwargs["id"] created_at = kwargs.get("createdAt") or kwargs.get("created_at") self.created_at = parse_datetime(created_at) if created_at else None self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image") self.space_id = kwargs.get("spaceId") or kwargs.get("space_id") owner = kwargs.get("owner", {}) self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"]) self.command = kwargs.get("command") self.arguments = kwargs.get("arguments") self.environment = kwargs.get("environment") self.secrets = kwargs.get("secrets") self.flavor = kwargs.get("flavor") self.labels = kwargs.get("labels") volumes = kwargs.get("volumes") self.volumes = [Volume(**v) for v in volumes] if volumes else None status = kwargs.get("status", {}) self.status = JobStatus(stage=status["stage"], message=status.get("message"))
# Inferred fields self.endpoint = kwargs.get("endpoint", constants.ENDPOINT) self.url = f"{self.endpoint}/jobs/{self.owner.name}/{self.id}"
@dataclassclass JobSpec: docker_image: str | None space_id: str | None command: list[str] | None arguments: list[str] | None environment: dict[str, Any] | None secrets: dict[str, Any] | None flavor: SpaceHardware | None timeout: int | None tags: list[str] | None arch: str | None labels: dict[str, str] | None volumes: list[Volume] | None
def __init__(self, **kwargs) -> None: self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image") self.space_id = kwargs.get("spaceId") or kwargs.get("space_id") self.command = kwargs.get("command") self.arguments = kwargs.get("arguments") self.environment = kwargs.get("environment") self.secrets = kwargs.get("secrets") self.flavor = kwargs.get("flavor") self.timeout = kwargs.get("timeout") self.tags = kwargs.get("tags") self.arch = kwargs.get("arch") self.labels = kwargs.get("labels") volumes = kwargs.get("volumes") self.volumes = [Volume(**v) for v in volumes] if volumes else None
@dataclassclass LastJobInfo: id: str at: datetime
def __init__(self, **kwargs) -> None: self.id = kwargs["id"] self.at = parse_datetime(kwargs["at"])
@dataclassclass ScheduledJobStatus: last_job: LastJobInfo | None next_job_run_at: datetime | None
def __init__(self, **kwargs) -> None: last_job = kwargs.get("lastJob") or kwargs.get("last_job") self.last_job = LastJobInfo(**last_job) if last_job else None next_job_run_at = kwargs.get("nextJobRunAt") or kwargs.get("next_job_run_at") self.next_job_run_at = parse_datetime(str(next_job_run_at)) if next_job_run_at else None
@dataclassclass ScheduledJobInfo: """ Contains information about a Job.
Args: id (`str`): Scheduled Job ID. created_at (`datetime` or `None`): When the scheduled Job was created. tags (`list[str]` or `None`): The tags of the scheduled Job. schedule (`str` or `None`): One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday). suspend (`bool` or `None`): Whether the scheduled job is suspended (paused). concurrency (`bool` or `None`): Whether multiple instances of this Job can run concurrently. status (`ScheduledJobStatus` or `None`): Status of the scheduled Job. owner: (`JobOwner` or `None`): Owner of the scheduled Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")` job_spec: (`JobSpec` or `None`): Specifications of the Job.
Example:
```python >>> from huggingface_hub import run_job >>> scheduled_job = create_scheduled_job( ... image="python:3.12", ... command=["python", "-c", "print('Hello from the cloud!')"], ... schedule="@hourly", ... ) >>> scheduled_job.id '687fb701029421ae5549d999' >>> scheduled_job.status.next_job_run_at datetime.datetime(2025, 7, 22, 17, 6, 25, 79000, tzinfo=datetime.timezone.utc) ``` """
id: str created_at: datetime | None job_spec: JobSpec schedule: str | None suspend: bool | None concurrency: bool | None status: ScheduledJobStatus owner: JobOwner
def __init__(self, **kwargs) -> None: self.id = kwargs["id"] created_at = kwargs.get("createdAt") or kwargs.get("created_at") self.created_at = parse_datetime(created_at) if created_at else None self.job_spec = JobSpec(**(kwargs.get("job_spec") or kwargs.get("jobSpec", {}))) self.schedule = kwargs.get("schedule") self.suspend = kwargs.get("suspend") self.concurrency = kwargs.get("concurrency") status = kwargs.get("status", {}) self.status = ScheduledJobStatus( last_job=status.get("last_job") or status.get("lastJob"), next_job_run_at=status.get("next_job_run_at") or status.get("nextJobRunAt"), ) owner = kwargs.get("owner", {}) self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"])
@dataclassclass JobAccelerator: """ Contains information about a Job accelerator (GPU).
Args: type (`str`): Type of accelerator, e.g. `"gpu"`. model (`str`): Model of accelerator, e.g. `"T4"`, `"A10G"`, `"A100"`, `"L4"`, `"L40S"`. quantity (`str`): Number of accelerators, e.g. `"1"`, `"2"`, `"4"`, `"8"`. vram (`str`): Total VRAM, e.g. `"16 GB"`, `"24 GB"`. manufacturer (`str`): Manufacturer of the accelerator, e.g. `"Nvidia"`. """
type: str model: str quantity: str vram: str manufacturer: str
def __init__(self, **kwargs) -> None: self.type = kwargs["type"] self.model = kwargs["model"] self.quantity = kwargs["quantity"] self.vram = kwargs["vram"] self.manufacturer = kwargs["manufacturer"]
@dataclassclass JobHardware: """ Contains information about available Job hardware.
Args: name (`str`): Machine identifier, e.g. `"cpu-basic"`, `"a10g-large"`. pretty_name (`str`): Human-readable name, e.g. `"CPU Basic"`, `"Nvidia A10G - large"`. cpu (`str`): CPU specification, e.g. `"2 vCPU"`, `"12 vCPU"`. ram (`str`): RAM specification, e.g. `"16 GB"`, `"46 GB"`. accelerator (`JobAccelerator` or `None`): GPU/accelerator details if available. unit_cost_micro_usd (`int`): Cost in micro-dollars per unit, e.g. `167` (= $0.000167). unit_cost_usd (`float`): Cost in USD per unit, e.g. `0.000167`. unit_label (`str`): Cost unit period, e.g. `"minute"`.
Example:
```python >>> from huggingface_hub import list_jobs_hardware >>> hardware_list = list_jobs_hardware() >>> hardware_list[0] JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute') >>> hardware_list[0].name 'cpu-basic' ``` """
name: str pretty_name: str cpu: str ram: str accelerator: JobAccelerator | None unit_cost_micro_usd: int unit_cost_usd: float unit_label: str
def __init__(self, **kwargs) -> None: self.name = kwargs["name"] self.pretty_name = kwargs["prettyName"] self.cpu = kwargs["cpu"] self.ram = kwargs["ram"] accelerator = kwargs.get("accelerator") self.accelerator = JobAccelerator(**accelerator) if accelerator else None self.unit_cost_micro_usd = kwargs["unitCostMicroUSD"] self.unit_cost_usd = kwargs["unitCostUSD"] self.unit_label = kwargs["unitLabel"]
def _create_job_spec( *, image: str, command: list[str], env: dict[str, Any] | None, secrets: dict[str, Any] | None, flavor: SpaceHardware | None, timeout: int | float | str | None, labels: dict[str, str] | None = None, volumes: list[Volume] | None = None,) -> dict[str, Any]: # prepare job spec to send to HF Jobs API job_spec: dict[str, Any] = { "command": command, "arguments": [], "environment": env or {}, "flavor": flavor or SpaceHardware.CPU_BASIC, } # secrets are optional if secrets: job_spec["secrets"] = secrets # timeout is optional if timeout: time_units_factors = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24} if isinstance(timeout, str) and timeout[-1] in time_units_factors: job_spec["timeoutSeconds"] = int(float(timeout[:-1]) * time_units_factors[timeout[-1]]) else: job_spec["timeoutSeconds"] = int(timeout) # labels are optional if labels: job_spec["labels"] = labels # volumes are optional if volumes: job_spec["volumes"] = [vol.to_dict() for vol in volumes] # input is either from docker hub or from HF spaces for prefix in ( "https://huggingface.co/spaces/", "https://hf.co/spaces/", "huggingface.co/spaces/", "hf.co/spaces/", ): if image.startswith(prefix): job_spec["spaceId"] = image[len(prefix) :] break else: job_spec["dockerImage"] = image return job_spec123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473# Copyright 2024-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains utilities to handle the `../.cache/huggingface` folder in local directories.
First discussed in https://github.com/huggingface/huggingface_hub/issues/1738 to storedownload metadata when downloading files from the hub to a local directory (withoutusing the cache).
./.cache/huggingface folder structure:[4.0K] data├── [4.0K] .cache│ └── [4.0K] huggingface│ └── [4.0K] download│ ├── [ 16] file.parquet.metadata│ ├── [ 16] file.txt.metadata│ └── [4.0K] folder│ └── [ 16] file.parquet.metadata│├── [6.5G] file.parquet├── [1.5K] file.txt└── [4.0K] folder └── [ 16] file.parquet
Download metadata file structure:```# file.txt.metadata11c5a3d5811f50298f278a704980280950aedb10a16a55fda99d2f2e7b69cce5cf93ff4ad30499301712656091.123
# file.parquet.metadata11c5a3d5811f50298f278a704980280950aedb107c5d3f4b8b76583b422fcb9189ad6c89d5d97a094541ce8932dce3ecabde14211712656091.123}```"""
import base64import hashlibimport loggingimport osimport timefrom dataclasses import dataclassfrom pathlib import Path
from .utils import WeakFileLock
logger = logging.getLogger(__name__)
CACHEDIR_TAG_CONTENT = ( "Signature: 8a477f597d28d172789f06886806bc55\n" "# This file is a cache directory tag created by huggingface_hub.\n" "# For information about cache directory tags, see:\n" "#\thttps://bford.info/cachedir/\n")
@dataclassclass LocalDownloadFilePaths: """ Paths to the files related to a download process in a local dir.
Returned by [`get_local_download_paths`].
Attributes: file_path (`Path`): Path where the file will be saved. lock_path (`Path`): Path to the lock file used to ensure atomicity when reading/writing metadata. metadata_path (`Path`): Path to the metadata file. """
file_path: Path lock_path: Path metadata_path: Path
def incomplete_path(self, etag: str) -> Path: """Return the path where a file will be temporarily downloaded before being moved to `file_path`.""" path = self.metadata_path.parent / f"{_short_hash(self.metadata_path.name)}.{etag}.incomplete" resolved_path = str(path.resolve()) # Some Windows versions do not allow for paths longer than 255 characters. # In this case, we must specify it as an extended path by using the "\\?\" prefix. if os.name == "nt" and len(resolved_path) > 255 and not resolved_path.startswith("\\\\?\\"): path = Path("\\\\?\\" + resolved_path) return path
@dataclass(frozen=True)class LocalUploadFilePaths: """ Paths to the files related to an upload process in a local dir.
Returned by [`get_local_upload_paths`].
Attributes: path_in_repo (`str`): Path of the file in the repo. file_path (`Path`): Path where the file will be saved. lock_path (`Path`): Path to the lock file used to ensure atomicity when reading/writing metadata. metadata_path (`Path`): Path to the metadata file. """
path_in_repo: str file_path: Path lock_path: Path metadata_path: Path
@dataclassclass LocalDownloadFileMetadata: """ Metadata about a file in the local directory related to a download process.
Attributes: filename (`str`): Path of the file in the repo. commit_hash (`str`): Commit hash of the file in the repo. etag (`str`): ETag of the file in the repo. Used to check if the file has changed. For LFS files, this is the sha256 of the file. For regular files, it corresponds to the git hash. timestamp (`int`): Unix timestamp of when the metadata was saved i.e. when the metadata was accurate. """
filename: str commit_hash: str etag: str timestamp: float
@dataclassclass LocalUploadFileMetadata: """ Metadata about a file in the local directory related to an upload process. """
size: int
# Default values correspond to "we don't know yet" timestamp: float | None = None should_ignore: bool | None = None sha256: str | None = None upload_mode: str | None = None remote_oid: str | None = None is_uploaded: bool = False is_committed: bool = False
def save(self, paths: LocalUploadFilePaths) -> None: """Save the metadata to disk.""" with WeakFileLock(paths.lock_path): with paths.metadata_path.open("w") as f: new_timestamp = time.time() f.write(str(new_timestamp) + "\n")
f.write(str(self.size)) # never None f.write("\n")
if self.should_ignore is not None: f.write(str(int(self.should_ignore))) f.write("\n")
if self.sha256 is not None: f.write(self.sha256) f.write("\n")
if self.upload_mode is not None: f.write(self.upload_mode) f.write("\n")
if self.remote_oid is not None: f.write(self.remote_oid) f.write("\n")
f.write(str(int(self.is_uploaded)) + "\n") f.write(str(int(self.is_committed)) + "\n")
self.timestamp = new_timestamp
def get_local_download_paths(local_dir: Path, filename: str) -> LocalDownloadFilePaths: """Compute paths to the files related to a download process.
Folders containing the paths are all guaranteed to exist.
Args: local_dir (`Path`): Path to the local directory in which files are downloaded. filename (`str`): Path of the file in the repo.
Return: [`LocalDownloadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path, incomplete_path). """ # filename is the path in the Hub repository (separated by '/') # make sure to have a cross-platform transcription sanitized_filename = os.path.join(*filename.split("/")) if os.name == "nt": if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename: raise ValueError( f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository" " owner to rename this file." ) file_path = local_dir / sanitized_filename metadata_path = _huggingface_dir(local_dir) / "download" / f"{sanitized_filename}.metadata" lock_path = metadata_path.with_suffix(".lock")
# Some Windows versions do not allow for paths longer than 255 characters. # In this case, we must specify it as an extended path by using the "\\?\" prefix if os.name == "nt": if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255: file_path = Path("\\\\?\\" + os.path.abspath(file_path)) lock_path = Path("\\\\?\\" + os.path.abspath(lock_path)) metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
file_path.parent.mkdir(parents=True, exist_ok=True) metadata_path.parent.mkdir(parents=True, exist_ok=True) return LocalDownloadFilePaths(file_path=file_path, lock_path=lock_path, metadata_path=metadata_path)
def get_local_upload_paths(local_dir: Path, filename: str) -> LocalUploadFilePaths: """Compute paths to the files related to an upload process.
Folders containing the paths are all guaranteed to exist.
Args: local_dir (`Path`): Path to the local directory that is uploaded. filename (`str`): Path of the file in the repo.
Return: [`LocalUploadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path). """ # filename is the path in the Hub repository (separated by '/') # make sure to have a cross-platform transcription sanitized_filename = os.path.join(*filename.split("/")) if os.name == "nt": if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename: raise ValueError( f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository" " owner to rename this file." ) file_path = local_dir / sanitized_filename metadata_path = _huggingface_dir(local_dir) / "upload" / f"{sanitized_filename}.metadata" lock_path = metadata_path.with_suffix(".lock")
# Some Windows versions do not allow for paths longer than 255 characters. # In this case, we must specify it as an extended path by using the "\\?\" prefix if os.name == "nt": if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255: file_path = Path("\\\\?\\" + os.path.abspath(file_path)) lock_path = Path("\\\\?\\" + os.path.abspath(lock_path)) metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
file_path.parent.mkdir(parents=True, exist_ok=True) metadata_path.parent.mkdir(parents=True, exist_ok=True) return LocalUploadFilePaths( path_in_repo=filename, file_path=file_path, lock_path=lock_path, metadata_path=metadata_path )
def read_download_metadata(local_dir: Path, filename: str) -> LocalDownloadFileMetadata | None: """Read metadata about a file in the local directory related to a download process.
Args: local_dir (`Path`): Path to the local directory in which files are downloaded. filename (`str`): Path of the file in the repo.
Return: `[LocalDownloadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise. """ paths = get_local_download_paths(local_dir, filename) with WeakFileLock(paths.lock_path): if paths.metadata_path.exists(): try: with paths.metadata_path.open() as f: commit_hash = f.readline().strip() etag = f.readline().strip() timestamp = float(f.readline().strip()) metadata = LocalDownloadFileMetadata( filename=filename, commit_hash=commit_hash, etag=etag, timestamp=timestamp, ) except Exception as e: # remove the metadata file if it is corrupted / not the right format logger.warning( f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue." ) try: paths.metadata_path.unlink() except Exception as e: logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}") return None
try: # check if the file exists and hasn't been modified since the metadata was saved stat = paths.file_path.stat() if ( stat.st_mtime - 1 <= metadata.timestamp ): # allow 1s difference as stat.st_mtime might not be precise return metadata logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.") except FileNotFoundError: # file does not exist => metadata is outdated return None return None
def read_upload_metadata(local_dir: Path, filename: str) -> LocalUploadFileMetadata: """Read metadata about a file in the local directory related to an upload process.
TODO: factorize logic with `read_download_metadata`.
Args: local_dir (`Path`): Path to the local directory in which files are downloaded. filename (`str`): Path of the file in the repo.
Return: `[LocalUploadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise. """ paths = get_local_upload_paths(local_dir, filename) with WeakFileLock(paths.lock_path): if paths.metadata_path.exists(): try: with paths.metadata_path.open() as f: timestamp = float(f.readline().strip())
size = int(f.readline().strip()) # never None
_should_ignore = f.readline().strip() should_ignore = None if _should_ignore == "" else bool(int(_should_ignore))
_sha256 = f.readline().strip() sha256 = None if _sha256 == "" else _sha256
_upload_mode = f.readline().strip() upload_mode = None if _upload_mode == "" else _upload_mode if upload_mode not in (None, "regular", "lfs"): raise ValueError(f"Invalid upload mode in metadata {paths.path_in_repo}: {upload_mode}")
_remote_oid = f.readline().strip() remote_oid = None if _remote_oid == "" else _remote_oid
is_uploaded = bool(int(f.readline().strip())) is_committed = bool(int(f.readline().strip()))
metadata = LocalUploadFileMetadata( timestamp=timestamp, size=size, should_ignore=should_ignore, sha256=sha256, upload_mode=upload_mode, remote_oid=remote_oid, is_uploaded=is_uploaded, is_committed=is_committed, ) except Exception as e: # remove the metadata file if it is corrupted / not the right format logger.warning( f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue." ) try: paths.metadata_path.unlink() except Exception as e: logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
# corrupted metadata => we don't know anything expect its size return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
# TODO: can we do better? if ( metadata.timestamp is not None and metadata.is_uploaded # file was uploaded and not metadata.is_committed # but not committed and time.time() - metadata.timestamp > 20 * 3600 # and it's been more than 20 hours ): # => we consider it as garbage-collected by S3 metadata.is_uploaded = False
# check if the file exists and hasn't been modified since the metadata was saved try: if metadata.timestamp is not None and paths.file_path.stat().st_mtime <= metadata.timestamp: return metadata logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.") except FileNotFoundError: # file does not exist => metadata is outdated pass
# empty metadata => we don't know anything expect its size return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
def write_download_metadata(local_dir: Path, filename: str, commit_hash: str, etag: str) -> None: """Write metadata about a file in the local directory related to a download process.
Args: local_dir (`Path`): Path to the local directory in which files are downloaded. """ paths = get_local_download_paths(local_dir, filename) with WeakFileLock(paths.lock_path): with paths.metadata_path.open("w") as f: f.write(f"{commit_hash}\n{etag}\n{time.time()}\n")
def _huggingface_dir(local_dir: Path) -> Path: """Return the path to the `.cache/huggingface` directory in a local directory.""" # Wrap in lru_cache to avoid overwriting the .gitignore file if called multiple times path = local_dir / ".cache" / "huggingface" path.mkdir(exist_ok=True, parents=True)
# Create a CACHEDIR.TAG so backup tools can skip this directory. _create_cachedir_tag(path)
# Create a .gitignore file in the .cache/huggingface directory if it doesn't exist # Should be thread-safe enough like this. gitignore = path / ".gitignore" gitignore_lock = path / ".gitignore.lock" if not gitignore.exists(): try: with WeakFileLock(gitignore_lock, timeout=0.1): gitignore.write_text("*") except IndexError: pass except OSError: # TimeoutError, FileNotFoundError, PermissionError, etc. pass try: gitignore_lock.unlink() except OSError: pass return path
def _create_cachedir_tag(cache_dir: Path) -> None: """Create a CACHEDIR.TAG file in ``cache_dir`` if one does not already exist.
The tag follows the `Cache Directory Tagging Standard <http://www.brynosaurus.com/cachedir/>`_ so that backup tools can recognize and skip cache directories. """ tag_path = cache_dir / "CACHEDIR.TAG" if not tag_path.exists(): try: tag_path.write_text(CACHEDIR_TAG_CONTENT) except OSError: pass
def _short_hash(filename: str) -> str: return base64.urlsafe_b64encode(hashlib.sha1(filename.encode()).digest()).decode()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494# Copyright 2020 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains methods to log in to the Hub."""
import osimport subprocessfrom getpass import getpassfrom pathlib import Path
import typer
from . import constantsfrom .utils import ( ANSI, capture_output, get_token, is_google_colab, is_notebook, list_credential_helpers, logging, run_subprocess, set_git_credential, unset_git_credential,)from .utils._auth import ( _get_token_by_name, _get_token_from_environment, _get_token_from_file, _get_token_from_google_colab, _save_stored_tokens, _save_token, get_stored_tokens,)
logger = logging.get_logger(__name__)
_HF_LOGO_ASCII = """ _| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _| _|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_| _| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _| _| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|"""
def login( token: str | None = None, *, add_to_git_credential: bool = False, skip_if_logged_in: bool = True,) -> None: """Login the machine to access the Hub.
The `token` is persisted in cache and set as a git credential. Once done, the machine is logged in and the access token will be available across all `huggingface_hub` components. If `token` is not provided, it will be prompted to the user either with a widget (in a notebook) or via the terminal.
To log in from outside of a script, one can also use `hf auth login` which is a cli command that wraps [`login`].
> [!TIP] > [`login`] is a drop-in replacement method for [`notebook_login`] as it wraps and > extends its capabilities.
> [!TIP] > When the token is not passed, [`login`] will automatically detect if the script runs > in a notebook or not. However, this detection might not be accurate due to the > variety of notebooks that exists nowadays. If that is the case, you can always force > the UI by using [`notebook_login`] or [`interpreter_login`].
Args: token (`str`, *optional*): User access token to generate from https://huggingface.co/settings/token. add_to_git_credential (`bool`, defaults to `False`): If `True`, token will be set as git credential. If no git credential helper is configured, a warning will be displayed to the user. If `token` is `None`, the value of `add_to_git_credential` is ignored and will be prompted again to the end user. skip_if_logged_in (`bool`, defaults to `True`): If `True`, do not prompt for token if user is already logged in. Set to `False` to force re-login. In CLI, use `--force` instead. Raises: [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If an organization token is passed. Only personal account tokens are valid to log in. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If token is invalid. [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) If running in a notebook but `ipywidgets` is not installed. """ if token is not None: if not add_to_git_credential: logger.info( "The token has not been saved to the git credentials helper. Pass " "`add_to_git_credential=True` in this function directly or " "`--add-to-git-credential` if using via `hf`CLI if " "you want to set the git credential as well." ) _login(token, add_to_git_credential=add_to_git_credential) elif is_notebook(): notebook_login(skip_if_logged_in=skip_if_logged_in) else: interpreter_login(skip_if_logged_in=skip_if_logged_in)
def logout(token_name: str | None = None) -> None: """Logout the machine from the Hub.
Token is deleted from the machine and removed from git credential.
Args: token_name (`str`, *optional*): Name of the access token to logout from. If `None`, will log out from all saved access tokens. Raises: [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError): If the access token name is not found. """ if get_token() is None and not get_stored_tokens(): # No active token and no saved access tokens logger.warning("Not logged in!") return if not token_name: # Delete all saved access tokens and token for file_path in (constants.HF_TOKEN_PATH, constants.HF_STORED_TOKENS_PATH): try: Path(file_path).unlink() except FileNotFoundError: pass logger.info("Successfully logged out from all access tokens.") else: _logout_from_token(token_name) logger.info(f"Successfully logged out from access token: {token_name}.")
unset_git_credential()
# Check if still logged in if _get_token_from_google_colab() is not None: raise OSError( "You are automatically logged in using a Google Colab secret.\n" "To log out, you must unset the `HF_TOKEN` secret in your Colab settings." ) if _get_token_from_environment() is not None: raise OSError( "Token has been deleted from your machine but you are still logged in.\n" "To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables." )
def auth_switch(token_name: str, add_to_git_credential: bool = False) -> None: """Switch to a different access token.
Args: token_name (`str`): Name of the access token to switch to. add_to_git_credential (`bool`, defaults to `False`): If `True`, token will be set as git credential. If no git credential helper is configured, a warning will be displayed to the user. If `token` is `None`, the value of `add_to_git_credential` is ignored and will be prompted again to the end user.
Raises: [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError): If the access token name is not found. """ token = _get_token_by_name(token_name) if not token: raise ValueError(f"Access token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}") # Write token to HF_TOKEN_PATH _set_active_token(token_name, add_to_git_credential) logger.info(f"The current active token is: {token_name}") token_from_environment = _get_token_from_environment() if token_from_environment is not None and token_from_environment != token: logger.warning( "The environment variable `HF_TOKEN` is set and will override the access token you've just switched to." )
def auth_list() -> None: """List all stored access tokens.""" tokens = get_stored_tokens()
if not tokens: if _get_token_from_environment(): logger.info("No stored access tokens found.") logger.warning("Note: Environment variable `HF_TOKEN` is set and is the current active token.") else: logger.info("No access tokens found.") return # Find current token current_token = get_token() current_token_name = None for token_name in tokens: if tokens.get(token_name) == current_token: current_token_name = token_name # Print header max_offset = max(len("token"), max(len(token) for token in tokens)) + 2 print(f" {{:<{max_offset}}}| {{:<15}}".format("name", "token")) print("-" * (max_offset + 2) + "|" + "-" * 15)
# Print saved access tokens for token_name in tokens: token = tokens.get(token_name, "<not set>") masked_token = f"{token[:3]}****{token[-4:]}" if token != "<not set>" else token is_current = "*" if token == current_token else " "
print(f"{is_current} {{:<{max_offset}}}| {{:<15}}".format(token_name, masked_token))
if _get_token_from_environment(): logger.warning( "\nNote: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above." ) elif current_token_name is None: logger.warning( "\nNote: No active token is set and no environment variable `HF_TOKEN` is found. Use `hf auth login` to log in." )
#### Interpreter-based login (text)###
def interpreter_login(*, skip_if_logged_in: bool = True) -> None: """ Displays a prompt to log in to the HF website and store the token.
This is equivalent to [`login`] without passing a token when not run in a notebook. [`interpreter_login`] is useful if you want to force the use of the terminal prompt instead of a notebook widget.
For more details, see [`login`].
Args: skip_if_logged_in (`bool`, defaults to `True`): If `True`, do not prompt for token if user is already logged in. Set to `False` to force re-login. In CLI, use `--force` instead. """ if skip_if_logged_in and get_token() is not None: logger.info("User is already logged in. Use `hf auth login --force` to force re-login.") return
print(_HF_LOGO_ASCII) if get_token() is not None: logger.info( " A token is already saved on your machine. Run `hf auth whoami`" " to get more information or `hf auth logout` if you want" " to log out." ) logger.info(" Setting a new token will erase the existing one.")
logger.info( " To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens ." ) if os.name == "nt": logger.info("Token can be pasted using 'Right-Click'.") token = getpass("Enter your token (input will not be visible): ") add_to_git_credential = typer.confirm("Add token as git credential?")
_login(token=token, add_to_git_credential=add_to_git_credential)
#### Notebook-based login (widget)###
NOTEBOOK_LOGIN_PASSWORD_HTML = """<center> <imgsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.svgalt='Hugging Face'> <br> Immediately click login after typing your password orit might be stored in plain text in this notebook file. </center>"""
NOTEBOOK_LOGIN_TOKEN_HTML_START = """<center> <imgsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.svgalt='Hugging Face'> <br> Copy a token from <ahref="https://huggingface.co/settings/tokens" target="_blank">your Hugging Facetokens page</a> and paste it below. <br> Immediately click login after copyingyour token or it might be stored in plain text in this notebook file. </center>"""
NOTEBOOK_LOGIN_TOKEN_HTML_END = """<b>Pro Tip:</b> If you don't already have one, you can create a dedicated'notebooks' token with 'write' access, that you can then easily reuse for allnotebooks. </center>"""
def notebook_login(*, skip_if_logged_in: bool = True) -> None: """ Displays a widget to log in to the HF website and store the token.
This is equivalent to [`login`] without passing a token when run in a notebook. [`notebook_login`] is useful if you want to force the use of the notebook widget instead of a prompt in the terminal.
For more details, see [`login`].
Args: skip_if_logged_in (`bool`, defaults to `True`): If `True`, do not prompt for token if user is already logged in. Set to `False` to force re-login. In CLI, use `--force` instead. """ try: import ipywidgets.widgets as widgets # type: ignore from IPython.display import display # type: ignore except ImportError: raise ImportError( "The `notebook_login` function can only be used in a notebook (Jupyter or" " Colab) and you need the `ipywidgets` module: `pip install ipywidgets`." ) if skip_if_logged_in and get_token() is not None: logger.info("User is already logged in. Use `hf auth login --force` to force re-login.") return
box_layout = widgets.Layout(display="flex", flex_flow="column", align_items="center", width="50%")
token_widget = widgets.Password(description="Token:") git_checkbox_widget = widgets.Checkbox(value=True, description="Add token as git credential?") token_finish_button = widgets.Button(description="Login")
login_token_widget = widgets.VBox( [ widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_START), token_widget, git_checkbox_widget, token_finish_button, widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_END), ], layout=box_layout, ) display(login_token_widget)
# On click events def login_token_event(t): """Event handler for the login button.""" token = token_widget.value add_to_git_credential = git_checkbox_widget.value # Erase token and clear value to make sure it's not saved in the notebook. token_widget.value = "" # Hide inputs login_token_widget.children = [widgets.Label("Connecting...")] try: with capture_output() as captured: _login(token, add_to_git_credential=add_to_git_credential) message = captured.getvalue() except Exception as error: message = str(error) # Print result (success message or error) login_token_widget.children = [widgets.Label(line) for line in message.split("\n") if line.strip()]
token_finish_button.on_click(login_token_event)
#### Login private helpers###
def _login( token: str, add_to_git_credential: bool,) -> None: from .hf_api import whoami # avoid circular import
if token.startswith("api_org"): raise ValueError("You must use your personal account token, not an organization token.")
token_info = whoami(token) permission = token_info["auth"]["accessToken"]["role"] logger.info(f"Token is valid (permission: {permission}).")
token_name = token_info["auth"]["accessToken"]["displayName"] # Store token locally _save_token(token=token, token_name=token_name) # Set active token _set_active_token(token_name=token_name, add_to_git_credential=add_to_git_credential) logger.info("Login successful.") if _get_token_from_environment(): logger.warning( "Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured." ) else: logger.info(f"The current active token is: `{token_name}`")
def _logout_from_token(token_name: str) -> None: """Logout from a specific access token.
Args: token_name (`str`): The name of the access token to logout from. Raises: [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError): If the access token name is not found. """ stored_tokens = get_stored_tokens() # If there is no access tokens saved or the access token name is not found, do nothing if not stored_tokens or token_name not in stored_tokens: return
token = stored_tokens.pop(token_name) _save_stored_tokens(stored_tokens)
if token == _get_token_from_file(): logger.warning(f"Active token '{token_name}' has been deleted.") Path(constants.HF_TOKEN_PATH).unlink(missing_ok=True)
def _set_active_token( token_name: str, add_to_git_credential: bool,) -> None: """Set the active access token.
Args: token_name (`str`): The name of the token to set as active. """ token = _get_token_by_name(token_name) if not token: raise ValueError(f"Token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}") if add_to_git_credential: if _is_git_credential_helper_configured(): set_git_credential(token) logger.info( "Your token has been saved in your configured git credential helpers" + f" ({','.join(list_credential_helpers())})." ) else: logger.warning("Token has not been saved to git credential helper.") # Write token to HF_TOKEN_PATH path = Path(constants.HF_TOKEN_PATH) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(token) logger.info(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
def _is_git_credential_helper_configured() -> bool: """Check if a git credential helper is configured.
Warns user if not the case (except for Google Colab where "store" is set by default by `huggingface_hub`). """ helpers = list_credential_helpers() if len(helpers) > 0: return True # Do not warn: at least 1 helper is set
# Only in Google Colab to avoid the warning message # See https://github.com/huggingface/huggingface_hub/issues/1043#issuecomment-1247010710 if is_google_colab(): _set_store_as_git_credential_helper_globally() return True # Do not warn: "store" is used by default in Google Colab
# Otherwise, warn user print( ANSI.red( "Cannot authenticate through git-credential as no helper is defined on your" " machine.\nYou might have to re-authenticate when pushing to the Hugging" " Face Hub.\nRun the following command in your terminal in case you want to" " set the 'store' credential helper as default.\n\ngit config --global" " credential.helper store\n\nRead" " https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more" " details." ) ) return False
def _set_store_as_git_credential_helper_globally() -> None: """Set globally the credential.helper to `store`.
To be used only in Google Colab as we assume the user doesn't care about the git credential config. It is the only particular case where we don't want to display the warning message in [`notebook_login()`].
Related: - https://github.com/huggingface/huggingface_hub/issues/1043 - https://github.com/huggingface/huggingface_hub/issues/1051 - https://git-scm.com/docs/git-credential-store """ try: run_subprocess("git config --global credential.helper store") except subprocess.CalledProcessError as exc: raise OSError(exc.stderr)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460import datetimeimport hashlibimport loggingimport osimport timeimport urllib.parseimport warningsfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Literal
from . import constantsfrom .hf_api import whoamifrom .utils import experimental, get_token
logger = logging.getLogger(__name__)
if TYPE_CHECKING: import fastapi
@dataclassclass OAuthOrgInfo: """ Information about an organization linked to a user logged in with OAuth.
Attributes: sub (`str`): Unique identifier for the org. OpenID Connect field. name (`str`): The org's full name. OpenID Connect field. preferred_username (`str`): The org's username. OpenID Connect field. picture (`str`): The org's profile picture URL. OpenID Connect field. plan (`str`, *optional*): The org's plan (e.g., "enterprise", "team"). Hugging Face field. can_pay (`Optional[bool]`, *optional*): Whether the org has a payment method set up. Hugging Face field. role_in_org (`Optional[str]`, *optional*): The user's role in the org. Hugging Face field. security_restrictions (`Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]]`, *optional*): Array of security restrictions that the user hasn't completed for this org. Possible values: "ip", "token-policy", "mfa", "sso". Hugging Face field. """
sub: str name: str preferred_username: str picture: str plan: str | None = None can_pay: bool | None = None role_in_org: str | None = None security_restrictions: list[Literal["ip", "token-policy", "mfa", "sso"]] | None = None
@dataclassclass OAuthUserInfo: """ Information about a user logged in with OAuth.
Attributes: sub (`str`): Unique identifier for the user, even in case of rename. OpenID Connect field. name (`str`): The user's full name. OpenID Connect field. preferred_username (`str`): The user's username. OpenID Connect field. email_verified (`Optional[bool]`, *optional*): Indicates if the user's email is verified. OpenID Connect field. email (`Optional[str]`, *optional*): The user's email address. OpenID Connect field. picture (`str`): The user's profile picture URL. OpenID Connect field. profile (`str`): The user's profile URL. OpenID Connect field. website (`Optional[str]`, *optional*): The user's website URL. OpenID Connect field. is_pro (`bool`): Whether the user is a pro user. Hugging Face field. can_pay (`Optional[bool]`, *optional*): Whether the user has a payment method set up. Hugging Face field. orgs (`Optional[list[OrgInfo]]`, *optional*): List of organizations the user is part of. Hugging Face field. """
sub: str name: str preferred_username: str email_verified: bool | None email: str | None picture: str profile: str website: str | None is_pro: bool can_pay: bool | None orgs: list[OAuthOrgInfo] | None
@dataclassclass OAuthInfo: """ Information about the OAuth login.
Attributes: access_token (`str`): The access token. access_token_expires_at (`datetime.datetime`): The expiration date of the access token. user_info ([`OAuthUserInfo`]): The user information. state (`str`, *optional*): State passed to the OAuth provider in the original request to the OAuth provider. scope (`str`): Granted scope. """
access_token: str access_token_expires_at: datetime.datetime user_info: OAuthUserInfo state: str | None scope: str
@experimentaldef attach_huggingface_oauth(app: "fastapi.FastAPI", route_prefix: str = "/"): """ Add OAuth endpoints to a FastAPI app to enable OAuth login with Hugging Face.
How to use: - Call this method on your FastAPI app to add the OAuth endpoints. - Inside your route handlers, call `parse_huggingface_oauth(request)` to retrieve the OAuth info. - If user is logged in, an [`OAuthInfo`] object is returned with the user's info. If not, `None` is returned. - In your app, make sure to add links to `/oauth/huggingface/login` and `/oauth/huggingface/logout` for the user to log in and out.
Example: ```py from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth
# Create a FastAPI app app = FastAPI()
# Add OAuth endpoints to the FastAPI app attach_huggingface_oauth(app)
# Add a route that greets the user if they are logged in @app.get("/") def greet_json(request: Request): # Retrieve the OAuth info from the request oauth_info = parse_huggingface_oauth(request) # e.g. OAuthInfo dataclass if oauth_info is None: return {"msg": "Not logged in!"} return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"} ``` """ # TODO: handle generic case (handling OAuth in a non-Space environment with custom dev values) (low priority)
# Add SessionMiddleware to the FastAPI app to store the OAuth info in the session. # Session Middleware requires a secret key to sign the cookies. Let's use a hash # of the OAuth secret key to make it unique to the Space + updated in case OAuth # config gets updated. When ran locally, we use an empty string as a secret key. try: from starlette.middleware.sessions import SessionMiddleware except ImportError as e: raise ImportError( "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add " "`huggingface_hub[oauth]` to your requirements.txt file in order to install the required dependencies." ) from e session_secret = (constants.OAUTH_CLIENT_SECRET or "") + "-v1" app.add_middleware( SessionMiddleware, # type: ignore secret_key=hashlib.sha256(session_secret.encode()).hexdigest(), same_site="none", https_only=True, ) # type: ignore
# Add OAuth endpoints to the FastAPI app: # - {route_prefix}/oauth/huggingface/login # - {route_prefix}/oauth/huggingface/callback # - {route_prefix}/oauth/huggingface/logout # If the app is running in a Space, OAuth is enabled normally. # Otherwise, we mock the endpoints to make the user log in with a fake user profile - without any calls to hf.co. route_prefix = route_prefix.strip("/") if os.getenv("SPACE_ID") is not None: logger.info("OAuth is enabled in the Space. Adding OAuth routes.") _add_oauth_routes(app, route_prefix=route_prefix) else: logger.info("App is not running in a Space. Adding mocked OAuth routes.") _add_mocked_oauth_routes(app, route_prefix=route_prefix)
def parse_huggingface_oauth(request: "fastapi.Request") -> OAuthInfo | None: """ Returns the information from a logged-in user as a [`OAuthInfo`] object.
For flexibility and future-proofing, this method is very lax in its parsing and does not raise errors. Missing fields are set to `None` without a warning.
Return `None`, if the user is not logged in (no info in session cookie).
See [`attach_huggingface_oauth`] for an example on how to use this method. """ if "oauth_info" not in request.session: logger.debug("No OAuth info in session.") return None
logger.debug("Parsing OAuth info from session.") oauth_data = request.session["oauth_info"] user_data = oauth_data.get("userinfo", {}) orgs_data = user_data.get("orgs", [])
orgs = ( [ OAuthOrgInfo( sub=org.get("sub"), name=org.get("name"), preferred_username=org.get("preferred_username"), picture=org.get("picture"), plan=org.get("plan"), can_pay=org.get("canPay"), role_in_org=org.get("roleInOrg"), security_restrictions=org.get("securityRestrictions"), ) for org in orgs_data ] if orgs_data else None )
user_info = OAuthUserInfo( sub=user_data.get("sub"), name=user_data.get("name"), preferred_username=user_data.get("preferred_username"), email_verified=user_data.get("email_verified"), email=user_data.get("email"), picture=user_data.get("picture"), profile=user_data.get("profile"), website=user_data.get("website"), is_pro=user_data.get("isPro"), can_pay=user_data.get("canPay"), orgs=orgs, )
return OAuthInfo( access_token=oauth_data.get("access_token"), access_token_expires_at=datetime.datetime.fromtimestamp(oauth_data.get("expires_at")), user_info=user_info, state=oauth_data.get("state"), scope=oauth_data.get("scope"), )
def _add_oauth_routes(app: "fastapi.FastAPI", route_prefix: str) -> None: """Add OAuth routes to the FastAPI app (login, callback handler and logout).""" try: import fastapi from authlib.integrations.base_client.errors import MismatchingStateError from authlib.integrations.starlette_client import OAuth from fastapi.responses import RedirectResponse except ImportError as e: raise ImportError( "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add " "`huggingface_hub[oauth]` to your requirements.txt file." ) from e
# Check environment variables msg = ( "OAuth is required but '{}' environment variable is not set. Make sure you've enabled OAuth in your Space by" " setting `hf_oauth: true` in the Space metadata." ) if constants.OAUTH_CLIENT_ID is None: raise ValueError(msg.format("OAUTH_CLIENT_ID")) if constants.OAUTH_CLIENT_SECRET is None: raise ValueError(msg.format("OAUTH_CLIENT_SECRET")) if constants.OAUTH_SCOPES is None: raise ValueError(msg.format("OAUTH_SCOPES")) if constants.OPENID_PROVIDER_URL is None: raise ValueError(msg.format("OPENID_PROVIDER_URL"))
# Register OAuth server oauth = OAuth() oauth.register( name="huggingface", client_id=constants.OAUTH_CLIENT_ID, client_secret=constants.OAUTH_CLIENT_SECRET, client_kwargs={"scope": constants.OAUTH_SCOPES}, server_metadata_url=constants.OPENID_PROVIDER_URL + "/.well-known/openid-configuration", )
login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix)
# Register OAuth endpoints @app.get(login_uri) async def oauth_login(request: fastapi.Request) -> RedirectResponse: """Endpoint that redirects to HF OAuth page.""" redirect_uri = _generate_redirect_uri(request) return await oauth.huggingface.authorize_redirect(request, redirect_uri) # type: ignore
@app.get(callback_uri) async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse: """Endpoint that handles the OAuth callback.""" try: oauth_info = await oauth.huggingface.authorize_access_token(request) # type: ignore except MismatchingStateError: # Parse query params nb_redirects = int(request.query_params.get("_nb_redirects", 0)) target_url = request.query_params.get("_target_url")
# Build redirect URI with the same query params as before and bump nb_redirects count query_params: dict[str, int | str] = {"_nb_redirects": nb_redirects + 1} if target_url: query_params["_target_url"] = target_url
redirect_uri = f"{login_uri}?{urllib.parse.urlencode(query_params)}"
# If the user is redirected more than 3 times, it is very likely that the cookie is not working properly. # (e.g. browser is blocking third-party cookies in iframe). In this case, redirect the user in the # non-iframe view. if nb_redirects > constants.OAUTH_MAX_REDIRECTS: host = os.environ.get("SPACE_HOST") if host is None: # cannot happen in a Space raise RuntimeError( "App is not running in a Space (SPACE_HOST environment variable is not set). Cannot redirect to non-iframe view." ) from None host_url = "https://" + host.rstrip("/") return RedirectResponse(host_url + redirect_uri)
# Redirect the user to the login page again return RedirectResponse(redirect_uri)
# OAuth login worked => store the user info in the session and redirect logger.debug("Successfully logged in with OAuth. Storing user info in session.") request.session["oauth_info"] = oauth_info return RedirectResponse(_get_redirect_target(request))
@app.get(logout_uri) async def oauth_logout(request: fastapi.Request) -> RedirectResponse: """Endpoint that logs out the user (e.g. delete info from cookie session).""" logger.debug("Logged out with OAuth. Removing user info from session.") request.session.pop("oauth_info", None) return RedirectResponse(_get_redirect_target(request))
def _add_mocked_oauth_routes(app: "fastapi.FastAPI", route_prefix: str = "/") -> None: """Add fake oauth routes if app is run locally and OAuth is enabled.
Using OAuth will have the same behavior as in a Space but instead of authenticating with HF, a mocked user profile is added to the session. """ try: import fastapi from fastapi.responses import RedirectResponse from starlette.datastructures import URL except ImportError as e: raise ImportError( "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add " "`huggingface_hub[oauth]` to your requirements.txt file." ) from e
warnings.warn( "OAuth is not supported outside of a Space environment. To help you debug your app locally, the oauth endpoints" " are mocked to return your profile and token. To make it work, your machine must be logged in to Huggingface." ) mocked_oauth_info = _get_mocked_oauth_info()
login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix)
# Define OAuth routes @app.get(login_uri) async def oauth_login(request: fastapi.Request) -> RedirectResponse: """Fake endpoint that redirects to HF OAuth page.""" # Define target (where to redirect after login) redirect_uri = _generate_redirect_uri(request) return RedirectResponse(callback_uri + "?" + urllib.parse.urlencode({"_target_url": redirect_uri}))
@app.get(callback_uri) async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse: """Endpoint that handles the OAuth callback.""" request.session["oauth_info"] = mocked_oauth_info return RedirectResponse(_get_redirect_target(request))
@app.get(logout_uri) async def oauth_logout(request: fastapi.Request) -> RedirectResponse: """Endpoint that logs out the user (e.g. delete cookie session).""" request.session.pop("oauth_info", None) logout_url = URL("/").include_query_params(**request.query_params) return RedirectResponse(url=logout_url, status_code=302) # see https://github.com/gradio-app/gradio/pull/9659
def _generate_redirect_uri(request: "fastapi.Request") -> str: if "_target_url" in request.query_params: # if `_target_url` already in query params => respect it target = request.query_params["_target_url"] else: # otherwise => keep query params target = "/?" + urllib.parse.urlencode(request.query_params)
redirect_uri = request.url_for("oauth_redirect_callback").include_query_params(_target_url=target) redirect_uri_as_str = str(redirect_uri) if redirect_uri.netloc.endswith(".hf.space"): # In Space, FastAPI redirect as http but we want https redirect_uri_as_str = redirect_uri_as_str.replace("http://", "https://") return redirect_uri_as_str
def _get_redirect_target(request: "fastapi.Request", default_target: str = "/") -> str: return request.query_params.get("_target_url", default_target)
def _get_mocked_oauth_info() -> dict: token = get_token() if token is None: raise ValueError( "Your machine must be logged in to HF to debug an OAuth app locally. Please" " run `hf auth login` or set `HF_TOKEN` as environment variable " "with one of your access token. You can generate a new token in your " "settings page (https://huggingface.co/settings/tokens)." )
user = whoami() if user["type"] != "user": raise ValueError( "Your machine is not logged in with a personal account. Please use a " "personal access token. You can generate a new token in your settings page" " (https://huggingface.co/settings/tokens)." )
return { "access_token": token, "token_type": "bearer", "expires_in": 8 * 60 * 60, # 8 hours "id_token": "FOOBAR", "scope": "openid profile", "refresh_token": "hf_oauth__refresh_token", "expires_at": int(time.time()) + 8 * 60 * 60, # 8 hours "userinfo": { "sub": "0123456789", "name": user["fullname"], "preferred_username": user["name"], "profile": f"https://huggingface.co/{user['name']}", "picture": user["avatarUrl"], "website": "", "aud": "00000000-0000-0000-0000-000000000000", "auth_time": 1691672844, "nonce": "aaaaaaaaaaaaaaaaaaa", "iat": 1691672844, "exp": 1691676444, "iss": "https://huggingface.co", }, }
def _get_oauth_uris(route_prefix: str = "/") -> tuple[str, str, str]: route_prefix = route_prefix.strip("/") if route_prefix: route_prefix = f"/{route_prefix}" return ( f"{route_prefix}/oauth/huggingface/login", f"{route_prefix}/oauth/huggingface/callback", f"{route_prefix}/oauth/huggingface/logout", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471import osfrom collections.abc import Iterablefrom pathlib import Pathfrom typing import Literal, overload
import httpxfrom tqdm.auto import tqdm as base_tqdmfrom tqdm.contrib.concurrent import thread_map
from . import constantsfrom .errors import ( DryRunError, GatedRepoError, HfHubHTTPError, LocalEntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError,)from .file_download import REGEX_COMMIT_HASH, DryRunFileInfo, hf_hub_download, repo_folder_namefrom .hf_api import DatasetInfo, HfApi, KernelInfo, ModelInfo, RepoFile, SpaceInfofrom .utils import OfflineModeIsEnabled, filter_repo_objects, logging, validate_hf_hub_argsfrom .utils.tqdm import _create_progress_barfrom .utils.tqdm import tqdm as hf_tqdm
logger = logging.get_logger(__name__)
LARGE_REPO_THRESHOLD = 1000 # After this limit, we don't consider `repo_info.siblings` to be reliable enough
@overloaddef snapshot_download( repo_id: str, *, repo_type: str | None = None, revision: str | None = None, cache_dir: str | Path | None = None, local_dir: str | Path | None = None, library_name: str | None = None, library_version: str | None = None, user_agent: dict | str | None = None, etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, force_download: bool = False, token: bool | str | None = None, local_files_only: bool = False, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, max_workers: int = 8, tqdm_class: type[base_tqdm] | None = None, headers: dict[str, str] | None = None, endpoint: str | None = None, dry_run: Literal[False] = False,) -> str: ...
@overloaddef snapshot_download( repo_id: str, *, repo_type: str | None = None, revision: str | None = None, cache_dir: str | Path | None = None, local_dir: str | Path | None = None, library_name: str | None = None, library_version: str | None = None, user_agent: dict | str | None = None, etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, force_download: bool = False, token: bool | str | None = None, local_files_only: bool = False, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, max_workers: int = 8, tqdm_class: type[base_tqdm] | None = None, headers: dict[str, str] | None = None, endpoint: str | None = None, dry_run: Literal[True] = True,) -> list[DryRunFileInfo]: ...
@overloaddef snapshot_download( repo_id: str, *, repo_type: str | None = None, revision: str | None = None, cache_dir: str | Path | None = None, local_dir: str | Path | None = None, library_name: str | None = None, library_version: str | None = None, user_agent: dict | str | None = None, etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, force_download: bool = False, token: bool | str | None = None, local_files_only: bool = False, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, max_workers: int = 8, tqdm_class: type[base_tqdm] | None = None, headers: dict[str, str] | None = None, endpoint: str | None = None, dry_run: bool = False,) -> str | list[DryRunFileInfo]: ...
@validate_hf_hub_argsdef snapshot_download( repo_id: str, *, repo_type: str | None = None, revision: str | None = None, cache_dir: str | Path | None = None, local_dir: str | Path | None = None, library_name: str | None = None, library_version: str | None = None, user_agent: dict | str | None = None, etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, force_download: bool = False, token: bool | str | None = None, local_files_only: bool = False, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, max_workers: int = 8, tqdm_class: type[base_tqdm] | None = None, headers: dict[str, str] | None = None, endpoint: str | None = None, dry_run: bool = False,) -> str | list[DryRunFileInfo]: """Download repo files.
Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order to keep their actual filename relative to that folder. You can also filter which files to download using `allow_patterns` and `ignore_patterns`.
If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir` to store some metadata related to the downloaded files. While this mechanism is not as robust as the main cache-system, it's optimized for regularly pulling the latest version of a repository.
An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly configured. It is also not possible to filter which files to download when cloning a repository using git.
Args: repo_id (`str`): A user or an organization name and a repo name separated by a `/`. repo_type (`str`, *optional*): Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo, `None` or `"model"` if downloading from a model. Default is `None`. revision (`str`, *optional*): An optional Git revision id which can be a branch name, a tag, or a commit hash. cache_dir (`str`, `Path`, *optional*): Path to the folder where cached files are stored. local_dir (`str` or `Path`, *optional*): If provided, the downloaded files will be placed under this directory. library_name (`str`, *optional*): The name of the library to which the object corresponds. library_version (`str`, *optional*): The version of the library. user_agent (`str`, `dict`, *optional*): The user-agent info in the form of a dictionary or a string. etag_timeout (`float`, *optional*, defaults to `10`): When fetching ETag, how many seconds to wait for the server to send data before giving up which is passed to `httpx.request`. force_download (`bool`, *optional*, defaults to `False`): Whether the file should be downloaded even if it already exists in the local cache. token (`str`, `bool`, *optional*): A token to be used for the download. - If `True`, the token is read from the HuggingFace config folder. - If a string, it's used as the authentication token. headers (`dict`, *optional*): Additional headers to include in the request. Those headers take precedence over the others. local_files_only (`bool`, *optional*, defaults to `False`): If `True`, avoid downloading the file and return the path to the local cached file if it exists. allow_patterns (`list[str]` or `str`, *optional*): If provided, only files matching at least one pattern are downloaded. ignore_patterns (`list[str]` or `str`, *optional*): If provided, files matching any of the patterns are not downloaded. max_workers (`int`, *optional*): Number of concurrent threads to download files (1 thread = 1 file download). Defaults to 8. tqdm_class (`tqdm`, *optional*): If provided, overwrites the default behavior for the progress bar. Passed argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. Note that the `tqdm_class` is not passed to each individual download. Defaults to the custom HF progress bar that can be disabled by setting `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. dry_run (`bool`, *optional*, defaults to `False`): If `True`, perform a dry run without actually downloading the files. Returns a list of [`DryRunFileInfo`] objects containing information about what would be downloaded.
Returns: `str` or list of [`DryRunFileInfo`]: - If `dry_run=False`: Local snapshot path. - If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information.
Raises: [`~utils.RepositoryNotFoundError`] If the repository to download from cannot be found. This may be because it doesn't exist, or because it is set to `private` and you do not have access. [`~utils.RevisionNotFoundError`] If the revision to download from cannot be found. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) If `token=True` and the token cannot be found. [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if ETag cannot be determined. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) if some parameter value is invalid. """ if cache_dir is None: cache_dir = constants.HF_HUB_CACHE if revision is None: revision = constants.DEFAULT_REVISION if isinstance(cache_dir, Path): cache_dir = str(cache_dir)
if repo_type is None: repo_type = "model" if repo_type not in constants.REPO_TYPES_WITH_KERNEL: raise ValueError( f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}" )
storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
api = HfApi( library_name=library_name, library_version=library_version, user_agent=user_agent, endpoint=endpoint, headers=headers, token=token, )
repo_info: ModelInfo | DatasetInfo | SpaceInfo | KernelInfo | None = None api_call_error: Exception | None = None if not local_files_only: # try/except logic to handle different errors => taken from `hf_hub_download` try: # if we have internet connection we want to list files to download repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision) except httpx.ProxyError: # Actually raise on proxy error raise except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled) as error: # Internet connection is down # => will try to use local files only api_call_error = error pass except RevisionNotFoundError: # The repo was found but the revision doesn't exist on the Hub (never existed or got deleted) raise except HfHubHTTPError as error: # Multiple reasons for an http error: # - Repository is private and invalid/missing token sent # - Repository is gated and invalid/missing token sent # - Hub is down (error 500 or 504) # => let's switch to 'local_files_only=True' to check if the files are already cached. # (if it's not the case, the error will be re-raised) api_call_error = error pass
# At this stage, if `repo_info` is None it means either: # - internet connection is down # - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True) # - repo is private/gated and invalid/missing token sent # - Hub is down # => let's look if we can find the appropriate folder in the cache: # - if the specified revision is a commit hash, look inside "snapshots". # - f the specified revision is a branch or tag, look inside "refs". # => if local_dir is not None, we will return the path to the local folder if it exists. if repo_info is None: if dry_run: raise DryRunError( "Dry run cannot be performed as the repository cannot be accessed. Please check your internet connection or authentication token." ) from api_call_error
# Try to get which commit hash corresponds to the specified revision commit_hash = None if REGEX_COMMIT_HASH.match(revision): commit_hash = revision else: ref_path = os.path.join(storage_folder, "refs", revision) if os.path.exists(ref_path): # retrieve commit_hash from refs file with open(ref_path) as f: commit_hash = f.read()
# Try to locate snapshot folder for this commit hash if commit_hash is not None and local_dir is None: snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash) if os.path.exists(snapshot_folder): # Snapshot folder exists => let's return it # (but we can't check if all the files are actually there) return snapshot_folder
# If local_dir is not None, return it if it exists and is not empty if local_dir is not None: local_dir = Path(local_dir) if local_dir.is_dir() and any(local_dir.iterdir()): logger.warning( f"Returning existing local_dir `{local_dir}` as remote repo cannot be accessed in `snapshot_download` ({api_call_error})." ) return str(local_dir.resolve()) # If we couldn't find the appropriate folder on disk, raise an error. if local_files_only: raise LocalEntryNotFoundError( "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and " "outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass " "'local_files_only=False' as input." ) elif isinstance(api_call_error, OfflineModeIsEnabled): raise LocalEntryNotFoundError( "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and " "outgoing traffic has been disabled. To enable repo look-ups and downloads online, set " "'HF_HUB_OFFLINE=0' as environment variable." ) from api_call_error elif isinstance(api_call_error, (RepositoryNotFoundError, GatedRepoError)) or ( isinstance(api_call_error, HfHubHTTPError) and api_call_error.response.status_code == 401 ): # Repo not found, gated, or specific authentication error => let's raise the actual error raise api_call_error else: # Otherwise: most likely a connection issue or Hub downtime => let's warn the user raise LocalEntryNotFoundError( f"Got: {api_call_error.__class__.__name__}: {api_call_error}" "\nAn error happened while trying to locate the files on the Hub and we cannot find the appropriate" " snapshot folder for the specified revision on the local disk. Please check your internet connection" " and try again." ) from api_call_error
# At this stage, internet connection is up and running # => let's download the files! assert repo_info.sha is not None, "Repo info returned from server must have a revision sha."
# Corner case: on very large repos, the siblings list in `repo_info` might not contain all files. # In that case, we need to use the `list_repo_tree` method to prevent caching issues. # Note: kernel repos don't expose siblings in their info response, so we always fall back to `list_repo_tree`. siblings = getattr(repo_info, "siblings", None) repo_files: Iterable[str] = [f.rfilename for f in siblings] if siblings is not None else [] unreliable_nb_files = siblings is None or len(siblings) == 0 or len(siblings) > LARGE_REPO_THRESHOLD if unreliable_nb_files: logger.info( "Number of files in the repo is unreliable. Using `list_repo_tree` to ensure all files are listed." ) repo_files = ( f.rfilename for f in api.list_repo_tree(repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type) if isinstance(f, RepoFile) )
filtered_repo_files: Iterable[str] = filter_repo_objects( items=repo_files, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, )
if not unreliable_nb_files: filtered_repo_files = list(filtered_repo_files) tqdm_desc = f"Fetching {len(filtered_repo_files)} files" else: tqdm_desc = "Fetching ... files" if dry_run: tqdm_desc = "[dry-run] " + tqdm_desc
commit_hash = repo_info.sha snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash) # if passed revision is not identical to commit_hash # then revision has to be a branch name or tag name. # In that case store a ref. if revision != commit_hash: ref_path = os.path.join(storage_folder, "refs", revision) try: os.makedirs(os.path.dirname(ref_path), exist_ok=True) with open(ref_path, "w") as f: f.write(commit_hash) except OSError as e: logger.warning(f"Ignored error while writing commit hash to {ref_path}: {e}.")
results: list[str | DryRunFileInfo] = []
# User can use its own tqdm class or the default one from `huggingface_hub.utils` tqdm_class = tqdm_class or hf_tqdm
# Create a progress bar for the bytes downloaded # This progress bar is shared across threads/files and gets updated each time we fetch # metadata for a file. bytes_progress = _create_progress_bar( cls=tqdm_class, log_level=logger.getEffectiveLevel(), name="huggingface_hub.snapshot_download", desc="Downloading (incomplete total...)", total=0, initial=0, unit="B", unit_scale=True, )
class _AggregatedTqdm: """Fake tqdm object to aggregate progress into the parent `bytes_progress` bar.
In practice the `_AggregatedTqdm` object won't be displayed, it's just used to update the `bytes_progress` bar from each thread/file download. """
def __init__(self, *args, **kwargs): # Adjust the total of the parent progress bar total = kwargs.pop("total", None) if total is not None: bytes_progress.total += total bytes_progress.refresh()
# Adjust initial of the parent progress bar initial = kwargs.pop("initial", 0) if initial: bytes_progress.update(initial)
def __enter__(self): return self
def __exit__(self, exc_type, exc_value, traceback): pass
def update(self, n: int | float | None = 1) -> None: bytes_progress.update(n)
# we pass the commit_hash to hf_hub_download # so no network call happens if we already # have the file locally. def _inner_hf_hub_download(repo_file: str) -> None: results.append( hf_hub_download( # type: ignore repo_id, filename=repo_file, repo_type=repo_type, revision=commit_hash, endpoint=endpoint, cache_dir=cache_dir, local_dir=local_dir, library_name=library_name, library_version=library_version, user_agent=user_agent, etag_timeout=etag_timeout, force_download=force_download, token=token, headers=headers, tqdm_class=_AggregatedTqdm, # type: ignore dry_run=dry_run, ) )
thread_map( _inner_hf_hub_download, filtered_repo_files, desc=tqdm_desc, max_workers=max_workers, tqdm_class=tqdm_class, )
bytes_progress.set_description("Download complete")
if dry_run: assert all(isinstance(r, DryRunFileInfo) for r in results) return results # type: ignore
if local_dir is not None: return str(os.path.realpath(local_dir)) return snapshot_folder123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251# Copyright 2019-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.from dataclasses import dataclassfrom datetime import datetimefrom enum import Enumfrom typing import Literal
from huggingface_hub.utils import parse_datetime
class SpaceStage(str, Enum): """ Enumeration of possible stage of a Space on the Hub.
Value can be compared to a string: ```py assert SpaceStage.BUILDING == "BUILDING" ```
Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url). """
# Copied from moon-landing > server > repo_types > SpaceInfo.ts (private repo) NO_APP_FILE = "NO_APP_FILE" CONFIG_ERROR = "CONFIG_ERROR" BUILDING = "BUILDING" BUILD_ERROR = "BUILD_ERROR" RUNNING = "RUNNING" RUNNING_BUILDING = "RUNNING_BUILDING" RUNTIME_ERROR = "RUNTIME_ERROR" DELETING = "DELETING" STOPPED = "STOPPED" PAUSED = "PAUSED" APP_STARTING = "APP_STARTING" RUNNING_APP_STARTING = "RUNNING_APP_STARTING"
class SpaceHardware(str, Enum): """ Enumeration of hardwares available to run your Space on the Hub.
Value can be compared to a string: ```py assert SpaceHardware.CPU_BASIC == "cpu-basic" ```
Taken from https://github.com/huggingface-internal/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts (private url). """
# CPU CPU_BASIC = "cpu-basic" CPU_UPGRADE = "cpu-upgrade" CPU_PERFORMANCE = "cpu-performance" CPU_XL = "cpu-xl" SPRX8 = "sprx8"
# ZeroGPU ZERO_A10G = "zero-a10g"
# GPU T4_SMALL = "t4-small" T4_MEDIUM = "t4-medium" L4X1 = "l4x1" L4X4 = "l4x4" L40SX1 = "l40sx1" L40SX4 = "l40sx4" L40SX8 = "l40sx8" A10G_SMALL = "a10g-small" A10G_LARGE = "a10g-large" A10G_LARGEX2 = "a10g-largex2" A10G_LARGEX4 = "a10g-largex4" A100_LARGE = "a100-large" A100X4 = "a100x4" A100X8 = "a100x8" H200 = "h200" H200X2 = "h200x2" H200X4 = "h200x4" H200X8 = "h200x8"
# Neuron INF2X6 = "inf2x6"
class SpaceStorage(str, Enum): """ Enumeration of persistent storage available for your Space on the Hub.
Value can be compared to a string: ```py assert SpaceStorage.SMALL == "small" ```
Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url). """
SMALL = "small" MEDIUM = "medium" LARGE = "large"
@dataclassclass Volume: """ Describes a volume to mount in a Space or Job container.
Args: type (`str`): Type of volume: `"bucket"`, `"model"`, `"dataset"`, or `"space"`. source (`str`): Source identifier, e.g. `"username/my-bucket"` or `"username/my-model"`. mount_path (`str`): Mount path inside the container, e.g. `"/data"`. Must start with `/`. revision (`str` or `None`): Git revision (only for repos, defaults to `"main"`). read_only (`bool` or `None`): Read-only mount. Forced `True` for repos, defaults to `False` for buckets. path (`str` or `None`): Subfolder prefix inside the bucket/repo to mount, e.g. `"path/to/dir"`. """
type: Literal["bucket", "model", "dataset", "space"] source: str mount_path: str revision: str | None = None read_only: bool | None = None path: str | None = None
def __init__(self, **kwargs) -> None: self.type = kwargs.get("type", "model") self.source = kwargs["source"] mount_path = kwargs.get("mountPath") self.mount_path = mount_path if mount_path is not None else kwargs["mount_path"] self.revision = kwargs.get("revision") read_only = kwargs.get("readOnly") self.read_only = read_only if read_only is not None else kwargs.get("read_only") self.path = kwargs.get("path")
def to_dict(self) -> dict: """Serialize to the JSON payload expected by the Hub API.""" data: dict = { "type": self.type, "source": self.source, "mountPath": self.mount_path, } if self.revision is not None: data["revision"] = self.revision if self.read_only is not None: data["readOnly"] = self.read_only if self.path is not None: data["path"] = self.path return data
@dataclassclass SpaceHotReloading: status: Literal["created", "canceled"] replica_statuses: list[tuple[str, str]] # See _hot_reloading_types.ApiCreateReloadResponse.res.status raw: dict
def __init__(self, data: dict) -> None: self.status = data["status"] self.replica_statuses = data["replicaStatuses"] self.raw = data
@dataclassclass SpaceRuntime: """ Contains information about the current runtime of a Space.
Args: stage (`str`): Current stage of the space. Example: RUNNING. hardware (`str` or `None`): Current hardware of the space. Example: "cpu-basic". Can be `None` if Space is `BUILDING` for the first time. requested_hardware (`str` or `None`): Requested hardware. Can be different from `hardware` especially if the request has just been made. Example: "t4-medium". Can be `None` if no hardware has been requested yet. sleep_time (`int` or `None`): Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48 hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time. volumes (`list[Volume]` or `None`): List of volumes mounted in the Space. Each volume is a [`Volume`] object describing its type, source, mount path, and optional settings. `None` if no volumes are attached. raw (`dict`): Raw response from the server. Contains more information about the Space runtime like number of replicas, number of cpu, memory size,... """
stage: SpaceStage hardware: SpaceHardware | None requested_hardware: SpaceHardware | None sleep_time: int | None storage: SpaceStorage | None hot_reloading: SpaceHotReloading | None volumes: list[Volume] | None raw: dict
def __init__(self, data: dict) -> None: self.stage = data["stage"] self.hardware = data.get("hardware", {}).get("current") self.requested_hardware = data.get("hardware", {}).get("requested") self.sleep_time = data.get("gcTimeout") self.storage = data.get("storage") self.hot_reloading = SpaceHotReloading(raw_hr) if (raw_hr := data.get("hotReloading")) is not None else None raw_volumes = data.get("volumes") self.volumes = [Volume(**v) for v in raw_volumes] if raw_volumes is not None else None self.raw = data
@dataclassclass SpaceVariable: """ Contains information about the current variables of a Space.
Args: key (`str`): Variable key. Example: `"MODEL_REPO_ID"` value (`str`): Variable value. Example: `"the_model_repo_id"`. description (`str` or None): Description of the variable. Example: `"Model Repo ID of the implemented model"`. updatedAt (`datetime` or None): datetime of the last update of the variable (if the variable has been updated at least once). """
key: str value: str description: str | None updated_at: datetime | None
def __init__(self, key: str, values: dict) -> None: self.key = key self.value = values["value"] self.description = values.get("description") updated_at = values.get("updatedAt") self.updated_at = parse_datetime(updated_at) if updated_at is not None else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189# Copyright 2023 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains a logger to push training logs to the Hub, using Tensorboard."""
from pathlib import Path
from ._commit_scheduler import CommitSchedulerfrom .errors import EntryNotFoundErrorfrom .repocard import ModelCardfrom .utils import experimental
# Depending on user's setup, SummaryWriter can come either from 'tensorboardX'# or from 'torch.utils.tensorboard'. Both are compatible so let's try to load# from either of them.try: from tensorboardX import SummaryWriter as _RuntimeSummaryWriter
is_summary_writer_available = Trueexcept ImportError: try: from torch.utils.tensorboard import SummaryWriter as _RuntimeSummaryWriter
is_summary_writer_available = True except ImportError: # Dummy class to avoid failing at import. Will raise on instance creation. class _DummySummaryWriter: pass
_RuntimeSummaryWriter = _DummySummaryWriter # type: ignore[assignment] is_summary_writer_available = False
class HFSummaryWriter(_RuntimeSummaryWriter): """ Wrapper around the tensorboard's `SummaryWriter` to push training logs to the Hub.
Data is logged locally and then pushed to the Hub asynchronously. Pushing data to the Hub is done in a separate thread to avoid blocking the training script. In particular, if the upload fails for any reason (e.g. a connection issue), the main script will not be interrupted. Data is automatically pushed to the Hub every `commit_every` minutes (default to every 5 minutes).
> [!WARNING] > `HFSummaryWriter` is experimental. Its API is subject to change in the future without prior notice.
Args: repo_id (`str`): The id of the repo to which the logs will be pushed. logdir (`str`, *optional*): The directory where the logs will be written. If not specified, a local directory will be created by the underlying `SummaryWriter` object. commit_every (`int` or `float`, *optional*): The frequency (in minutes) at which the logs will be pushed to the Hub. Defaults to 5 minutes. squash_history (`bool`, *optional*): Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is useful to avoid degraded performances on the repo when it grows too large. repo_type (`str`, *optional*): The type of the repo to which the logs will be pushed. Defaults to "model". repo_revision (`str`, *optional*): The revision of the repo to which the logs will be pushed. Defaults to "main". repo_private (`bool`, *optional*): Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. path_in_repo (`str`, *optional*): The path to the folder in the repo where the logs will be pushed. Defaults to "tensorboard/". repo_allow_patterns (`list[str]` or `str`, *optional*): A list of patterns to include in the upload. Defaults to `"*.tfevents.*"`. Check out the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details. repo_ignore_patterns (`list[str]` or `str`, *optional*): A list of patterns to exclude in the upload. Check out the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details. token (`str`, *optional*): Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more details kwargs: Additional keyword arguments passed to `SummaryWriter`.
Examples: ```diff # Taken from https://pytorch.org/docs/stable/tensorboard.html - from torch.utils.tensorboard import SummaryWriter + from huggingface_hub import HFSummaryWriter
import numpy as np
- writer = SummaryWriter() + writer = HFSummaryWriter(repo_id="username/my-trained-model")
for n_iter in range(100): writer.add_scalar('Loss/train', np.random.random(), n_iter) writer.add_scalar('Loss/test', np.random.random(), n_iter) writer.add_scalar('Accuracy/train', np.random.random(), n_iter) writer.add_scalar('Accuracy/test', np.random.random(), n_iter) ```
```py >>> from huggingface_hub import HFSummaryWriter
# Logs are automatically pushed every 15 minutes (5 by default) + when exiting the context manager >>> with HFSummaryWriter(repo_id="test_hf_logger", commit_every=15) as logger: ... logger.add_scalar("a", 1) ... logger.add_scalar("b", 2) ``` """
@experimental def __new__(cls, *args, **kwargs) -> "HFSummaryWriter": if not is_summary_writer_available: raise ImportError( "You must have `tensorboard` installed to use `HFSummaryWriter`. Please run `pip install --upgrade" " tensorboardX` first." ) return super().__new__(cls)
def __init__( self, repo_id: str, *, logdir: str | None = None, commit_every: int | float = 5, squash_history: bool = False, repo_type: str | None = None, repo_revision: str | None = None, repo_private: bool | None = None, path_in_repo: str | None = "tensorboard", repo_allow_patterns: list[str] | str | None = "*.tfevents.*", repo_ignore_patterns: list[str] | str | None = None, token: str | None = None, **kwargs, ): # Initialize SummaryWriter super().__init__(logdir=logdir, **kwargs)
# Check logdir has been correctly initialized and fail early otherwise. In practice, SummaryWriter takes care of it. if not isinstance(self.logdir, str): raise ValueError(f"`self.logdir` must be a string. Got '{self.logdir}' of type {type(self.logdir)}.")
# Append logdir name to `path_in_repo` if path_in_repo is None or path_in_repo == "": path_in_repo = Path(self.logdir).name else: path_in_repo = path_in_repo.strip("/") + "/" + Path(self.logdir).name
# Initialize scheduler self.scheduler = CommitScheduler( folder_path=self.logdir, path_in_repo=path_in_repo, repo_id=repo_id, repo_type=repo_type, revision=repo_revision, private=repo_private, token=token, allow_patterns=repo_allow_patterns, ignore_patterns=repo_ignore_patterns, every=commit_every, squash_history=squash_history, )
# Exposing some high-level info at root level self.repo_id = self.scheduler.repo_id self.repo_type = self.scheduler.repo_type self.repo_revision = self.scheduler.revision
# Add `hf-summary-writer` tag to the model card metadata try: card = ModelCard.load(repo_id_or_path=self.repo_id, repo_type=self.repo_type) except EntryNotFoundError: card = ModelCard("") tags = card.data.get("tags", []) if "hf-summary-writer" not in tags: tags.append("hf-summary-writer") card.data["tags"] = tags card.push_to_hub(repo_id=self.repo_id, repo_type=self.repo_type)
def __exit__(self, exc_type, exc_val, exc_tb): """Push to hub in a non-blocking way when exiting the logger's context manager.""" super().__exit__(exc_type, exc_val, exc_tb) future = self.scheduler.trigger() future.result()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766# Copyright 2024-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import enumimport loggingimport osimport queueimport shutilimport sysimport threadingimport timeimport tracebackfrom datetime import datetimefrom pathlib import Pathfrom threading import Lockfrom typing import TYPE_CHECKING, Anyfrom urllib.parse import quote
from ._commit_api import CommitOperationAdd, UploadInfo, _fetch_upload_modesfrom ._local_folder import LocalUploadFileMetadata, LocalUploadFilePaths, get_local_upload_paths, read_upload_metadatafrom .constants import DEFAULT_REVISION, REPO_TYPESfrom .utils import DEFAULT_IGNORE_PATTERNS, _format_size, filter_repo_objects, tqdmfrom .utils._runtime import is_xet_availablefrom .utils.sha import sha_fileobj
if TYPE_CHECKING: from .hf_api import HfApi
logger = logging.getLogger(__name__)
WAITING_TIME_IF_NO_TASKS = 10 # secondsMAX_NB_FILES_FETCH_UPLOAD_MODE = 100COMMIT_SIZE_SCALE: list[int] = [20, 50, 75, 100, 125, 200, 250, 400, 600, 1000]
UPLOAD_BATCH_SIZE_XET = 256 # Max 256 files per upload batch for XET-enabled reposUPLOAD_BATCH_SIZE_LFS = 1 # Otherwise, batches of 1 for regular LFS upload
# Repository limits (from https://huggingface.co/docs/hub/repositories-recommendations)MAX_FILES_PER_REPO = 100_000 # Recommended maximum number of files per repositoryMAX_FILES_PER_FOLDER = 10_000 # Recommended maximum number of files per folderMAX_FILE_SIZE_GB = 200 # Recommended maximum for individual file size (split larger files)RECOMMENDED_FILE_SIZE_GB = 20 # Recommended maximum for individual file size
def _validate_upload_limits(paths_list: list[LocalUploadFilePaths]) -> None: """ Validate upload against repository limits and warn about potential issues.
Args: paths_list: List of file paths to be uploaded
Warns about: - Too many files in the repository (>100k) - Too many entries (files or subdirectories) in a single folder (>10k) - Files exceeding size limits (>20GB recommended, >200GB maximum) """ logger.info("Running validation checks on files to upload...")
# Check 1: Total file count if len(paths_list) > MAX_FILES_PER_REPO: logger.warning( f"You are about to upload {len(paths_list):,} files. " f"This exceeds the recommended limit of {MAX_FILES_PER_REPO:,} files per repository.\n" f"Consider:\n" f" - Splitting your data into multiple repositories\n" f" - Using fewer, larger files (e.g., parquet files)\n" f" - See: https://huggingface.co/docs/hub/repositories-recommendations" )
# Check 2: Files and subdirectories per folder # Track immediate children (files and subdirs) for each folder from collections import defaultdict
entries_per_folder: dict[str, Any] = defaultdict(lambda: {"files": 0, "subdirs": set()})
for paths in paths_list: path = Path(paths.path_in_repo) parts = path.parts
# Count this file in its immediate parent directory parent = str(path.parent) if str(path.parent) != "." else "." entries_per_folder[parent]["files"] += 1
# Track immediate subdirectories for each parent folder # Walk through the path components to track parent-child relationships for i, child in enumerate(parts[:-1]): parent = "." if i == 0 else "/".join(parts[:i]) entries_per_folder[parent]["subdirs"].add(child)
# Check limits for each folder for folder, data in entries_per_folder.items(): file_count = data["files"] subdir_count = len(data["subdirs"]) total_entries = file_count + subdir_count
if total_entries > MAX_FILES_PER_FOLDER: folder_display = "root" if folder == "." else folder logger.warning( f"Folder '{folder_display}' contains {total_entries:,} entries " f"({file_count:,} files and {subdir_count:,} subdirectories). " f"This exceeds the recommended {MAX_FILES_PER_FOLDER:,} entries per folder.\n" "Consider reorganising into sub-folders." )
# Check 3: File sizes large_files = [] very_large_files = []
for paths in paths_list: size = paths.file_path.stat().st_size size_gb = size / 1_000_000_000 # Use decimal GB as per Hub limits
if size_gb > MAX_FILE_SIZE_GB: very_large_files.append((paths.path_in_repo, size_gb)) elif size_gb > RECOMMENDED_FILE_SIZE_GB: large_files.append((paths.path_in_repo, size_gb))
# Warn about very large files (>200GB) if very_large_files: files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in very_large_files[:5]) more_str = f"\n ... and {len(very_large_files) - 5} more files" if len(very_large_files) > 5 else "" logger.warning( f"Found {len(very_large_files)} files exceeding the {MAX_FILE_SIZE_GB}GB recommended maximum:\n" f" - {files_str}{more_str}\n" f"Consider splitting these files into smaller chunks." )
# Warn about large files (>20GB) if large_files: files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in large_files[:5]) more_str = f"\n ... and {len(large_files) - 5} more files" if len(large_files) > 5 else "" logger.warning( f"Found {len(large_files)} files larger than {RECOMMENDED_FILE_SIZE_GB}GB (recommended limit):\n" f" - {files_str}{more_str}\n" f"Large files may slow down loading and processing." )
logger.info("Validation checks complete.")
def upload_large_folder_internal( api: "HfApi", repo_id: str, folder_path: str | Path, *, repo_type: str, # Repo type is required! revision: str | None = None, private: bool | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, num_workers: int | None = None, print_report: bool = True, print_report_every: int = 60,): """Upload a large folder to the Hub in the most resilient way possible.
See [`HfApi.upload_large_folder`] for the full documentation. """ # 1. Check args and setup if repo_type is None: raise ValueError( "For large uploads, `repo_type` is explicitly required. Please set it to `model`, `dataset` or `space`." " If you are using the CLI, pass it as `--repo-type=model`." ) if repo_type not in REPO_TYPES: raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") if revision is None: revision = DEFAULT_REVISION
folder_path = Path(folder_path).expanduser().resolve() if not folder_path.is_dir(): raise ValueError(f"Provided path: '{folder_path}' is not a directory")
if ignore_patterns is None: ignore_patterns = [] elif isinstance(ignore_patterns, str): ignore_patterns = [ignore_patterns] ignore_patterns += DEFAULT_IGNORE_PATTERNS
if num_workers is None: nb_cores = os.cpu_count() or 1 num_workers = max(nb_cores // 2, 1) # Use at most half of cpu cores
# 2. Create repo if missing repo_url = api.create_repo(repo_id=repo_id, repo_type=repo_type, private=private, exist_ok=True) logger.info(f"Repo created: {repo_url}") repo_id = repo_url.repo_id
# Warn on too many commits try: commits = api.list_repo_commits(repo_id=repo_id, repo_type=repo_type, revision=revision) commit_count = len(commits) if commit_count > 500: logger.warning( f"\n{'=' * 80}\n" f"WARNING: This repository has {commit_count} commits.\n" f"Repositories with a large number of commits can experience performance issues.\n" f"\n" f"Consider squashing your commit history using `super_squash_history()`.\n" "To do so, you need to stop this process, run the snippet below and restart the upload command." f" from huggingface_hub import super_squash_history\n" f" super_squash_history(repo_id='{repo_id}', repo_type='{repo_type}')\n" f"\n" f"Note: This is a non-revertible operation. See the documentation for more details:\n" f"https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_api#huggingface_hub.HfApi.super_squash_history\n" f"{'=' * 80}\n" ) except Exception as e: # Don't fail the upload if we can't check commit count logger.debug(f"Could not check commit count: {e}")
# 2.1 Check if xet is enabled to set batch file upload size upload_batch_size = UPLOAD_BATCH_SIZE_XET if is_xet_available() else UPLOAD_BATCH_SIZE_LFS
# 3. List files to upload filtered_paths_list = filter_repo_objects( (path.relative_to(folder_path).as_posix() for path in folder_path.glob("**/*") if path.is_file()), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, ) paths_list = [get_local_upload_paths(folder_path, relpath) for relpath in filtered_paths_list] logger.info(f"Found {len(paths_list)} candidate files to upload")
# Validate upload against repository limits _validate_upload_limits(paths_list)
logger.info("Starting upload...")
# Read metadata for each file items = [ (paths, read_upload_metadata(folder_path, paths.path_in_repo)) for paths in tqdm(paths_list, desc="Recovering from metadata files") ]
# 4. Start workers status = LargeUploadStatus(items, upload_batch_size) threads = [ threading.Thread( target=_worker_job, kwargs={ "status": status, "api": api, "repo_id": repo_id, "repo_type": repo_type, "revision": revision, }, ) for _ in range(num_workers) ]
for thread in threads: thread.start()
# 5. Print regular reports if print_report: print("\n\n" + status.current_report()) last_report_ts = time.time() while True: time.sleep(1) if time.time() - last_report_ts >= print_report_every: if print_report: _print_overwrite(status.current_report()) last_report_ts = time.time() if status.is_done(): logger.info("Is done: exiting main loop") break
for thread in threads: thread.join()
logger.info(status.current_report()) logger.info("Upload is complete!")
##################### Logic to manage workers and synchronize tasks####################
class WorkerJob(enum.Enum): SHA256 = enum.auto() GET_UPLOAD_MODE = enum.auto() PREUPLOAD_LFS = enum.auto() COMMIT = enum.auto() WAIT = enum.auto() # if no tasks are available but we don't want to exit
JOB_ITEM_T = tuple[LocalUploadFilePaths, LocalUploadFileMetadata]
class LargeUploadStatus: """Contains information, queues and tasks for a large upload process."""
def __init__(self, items: list[JOB_ITEM_T], upload_batch_size: int = 1): self.items = items self.queue_sha256: "queue.Queue[JOB_ITEM_T]" = queue.Queue() self.queue_get_upload_mode: "queue.Queue[JOB_ITEM_T]" = queue.Queue() self.queue_preupload_lfs: "queue.Queue[JOB_ITEM_T]" = queue.Queue() self.queue_commit: "queue.Queue[JOB_ITEM_T]" = queue.Queue() self.lock = Lock()
self.nb_workers_sha256: int = 0 self.nb_workers_get_upload_mode: int = 0 self.nb_workers_preupload_lfs: int = 0 self.upload_batch_size: int = upload_batch_size self.nb_workers_commit: int = 0 self.nb_workers_waiting: int = 0 self.last_commit_attempt: float | None = None
self._started_at = datetime.now() self._chunk_idx: int = 1 self._chunk_lock: Lock = Lock()
# Setup queues for item in self.items: paths, metadata = item if metadata.sha256 is None: self.queue_sha256.put(item) elif metadata.upload_mode is None: self.queue_get_upload_mode.put(item) elif metadata.upload_mode == "lfs" and not metadata.is_uploaded: self.queue_preupload_lfs.put(item) elif not metadata.is_committed: self.queue_commit.put(item) else: logger.debug(f"Skipping file {paths.path_in_repo} (already uploaded and committed)")
def target_chunk(self) -> int: with self._chunk_lock: return COMMIT_SIZE_SCALE[self._chunk_idx]
def update_chunk(self, success: bool, nb_items: int, duration: float) -> None: with self._chunk_lock: if not success: logger.warning(f"Failed to commit {nb_items} files at once. Will retry with less files in next batch.") self._chunk_idx -= 1 elif nb_items >= COMMIT_SIZE_SCALE[self._chunk_idx] and duration < 40: logger.info(f"Successfully committed {nb_items} at once. Increasing the limit for next batch.") self._chunk_idx += 1
self._chunk_idx = max(0, min(self._chunk_idx, len(COMMIT_SIZE_SCALE) - 1))
def current_report(self) -> str: """Generate a report of the current status of the large upload.""" nb_hashed = 0 size_hashed = 0 nb_preuploaded = 0 nb_lfs = 0 nb_lfs_unsure = 0 size_preuploaded = 0 nb_committed = 0 size_committed = 0 total_size = 0 ignored_files = 0 total_files = 0
with self.lock: for _, metadata in self.items: if metadata.should_ignore: ignored_files += 1 continue total_size += metadata.size total_files += 1 if metadata.sha256 is not None: nb_hashed += 1 size_hashed += metadata.size if metadata.upload_mode == "lfs": nb_lfs += 1 if metadata.upload_mode is None: nb_lfs_unsure += 1 if metadata.is_uploaded: nb_preuploaded += 1 size_preuploaded += metadata.size if metadata.is_committed: nb_committed += 1 size_committed += metadata.size total_size_str = _format_size(total_size)
now = datetime.now() now_str = now.strftime("%Y-%m-%d %H:%M:%S") elapsed = now - self._started_at elapsed_str = str(elapsed).split(".")[0] # remove milliseconds
message = "\n" + "-" * 10 message += f" {now_str} ({elapsed_str}) " message += "-" * 10 + "\n"
message += "Files: " message += f"hashed {nb_hashed}/{total_files} ({_format_size(size_hashed)}/{total_size_str}) | " message += f"pre-uploaded: {nb_preuploaded}/{nb_lfs} ({_format_size(size_preuploaded)}/{total_size_str})" if nb_lfs_unsure > 0: message += f" (+{nb_lfs_unsure} unsure)" message += f" | committed: {nb_committed}/{total_files} ({_format_size(size_committed)}/{total_size_str})" message += f" | ignored: {ignored_files}\n"
message += "Workers: " message += f"hashing: {self.nb_workers_sha256} | " message += f"get upload mode: {self.nb_workers_get_upload_mode} | " message += f"pre-uploading: {self.nb_workers_preupload_lfs} | " message += f"committing: {self.nb_workers_commit} | " message += f"waiting: {self.nb_workers_waiting}\n" message += "-" * 51
return message
def is_done(self) -> bool: with self.lock: return all(metadata.is_committed or metadata.should_ignore for _, metadata in self.items)
def _worker_job( status: LargeUploadStatus, api: "HfApi", repo_id: str, repo_type: str, revision: str,): """ Main process for a worker. The worker will perform tasks based on the priority list until all files are uploaded and committed. If no tasks are available, the worker will wait for 10 seconds before checking again.
If a task fails for any reason, the item(s) are put back in the queue for another worker to pick up.
Read `upload_large_folder` docstring for more information on how tasks are prioritized. """ while True: next_job: tuple[WorkerJob, list[JOB_ITEM_T]] | None = None
# Determine next task next_job = _determine_next_job(status) if next_job is None: return job, items = next_job
# Perform task match job: case WorkerJob.SHA256: item = items[0] # single item try: _compute_sha256(item) status.queue_get_upload_mode.put(item) except KeyboardInterrupt: raise except Exception as e: logger.error(f"Failed to compute sha256: {e}") traceback.format_exc() status.queue_sha256.put(item)
with status.lock: status.nb_workers_sha256 -= 1
case WorkerJob.GET_UPLOAD_MODE: try: _get_upload_mode(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision) except KeyboardInterrupt: raise except Exception as e: logger.error(f"Failed to get upload mode: {e}") traceback.format_exc()
# Items are either: # - dropped (if should_ignore) # - put in LFS queue (if LFS) # - put in commit queue (if regular) # - or put back (if error occurred). for item in items: _, metadata = item if metadata.should_ignore: continue match metadata.upload_mode: case "lfs": status.queue_preupload_lfs.put(item) case "regular": status.queue_commit.put(item) case _: status.queue_get_upload_mode.put(item)
with status.lock: status.nb_workers_get_upload_mode -= 1
case WorkerJob.PREUPLOAD_LFS: try: _preupload_lfs(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision) for item in items: status.queue_commit.put(item) except KeyboardInterrupt: raise except Exception as e: logger.error(f"Failed to preupload LFS: {e}") traceback.format_exc() for item in items: status.queue_preupload_lfs.put(item)
with status.lock: status.nb_workers_preupload_lfs -= 1
case WorkerJob.COMMIT: start_ts = time.time() success = True try: _commit(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision) except KeyboardInterrupt: raise except Exception as e: logger.error(f"Failed to commit: {e}") traceback.format_exc() for item in items: status.queue_commit.put(item) success = False duration = time.time() - start_ts status.update_chunk(success, len(items), duration) with status.lock: status.last_commit_attempt = time.time() status.nb_workers_commit -= 1
case WorkerJob.WAIT: time.sleep(WAITING_TIME_IF_NO_TASKS) with status.lock: status.nb_workers_waiting -= 1
def _determine_next_job(status: LargeUploadStatus) -> tuple[WorkerJob, list[JOB_ITEM_T]] | None: with status.lock: # 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file) if ( status.nb_workers_commit == 0 and status.queue_commit.qsize() > 0 and status.last_commit_attempt is not None and time.time() - status.last_commit_attempt > 5 * 60 ): status.nb_workers_commit += 1 logger.debug("Job: commit (more than 5 minutes since last commit attempt)") return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
# 2. Commit if at least 100 files are ready to commit elif status.nb_workers_commit == 0 and status.queue_commit.qsize() >= 150: status.nb_workers_commit += 1 logger.debug("Job: commit (>100 files ready)") return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
# 3. Get upload mode if at least 100 files elif status.queue_get_upload_mode.qsize() >= MAX_NB_FILES_FETCH_UPLOAD_MODE: status.nb_workers_get_upload_mode += 1 logger.debug(f"Job: get upload mode (>{MAX_NB_FILES_FETCH_UPLOAD_MODE} files ready)") return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
# 4. Preupload LFS file if at least `status.upload_batch_size` files and no worker is preuploading LFS elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size and status.nb_workers_preupload_lfs == 0: status.nb_workers_preupload_lfs += 1 logger.debug("Job: preupload LFS (no other worker preuploading LFS)") return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
# 5. Compute sha256 if at least 1 file and no worker is computing sha256 elif status.queue_sha256.qsize() > 0 and status.nb_workers_sha256 == 0: status.nb_workers_sha256 += 1 logger.debug("Job: sha256 (no other worker computing sha256)") return (WorkerJob.SHA256, _get_one(status.queue_sha256))
# 6. Get upload mode if at least 1 file and no worker is getting upload mode elif status.queue_get_upload_mode.qsize() > 0 and status.nb_workers_get_upload_mode == 0: status.nb_workers_get_upload_mode += 1 logger.debug("Job: get upload mode (no other worker getting upload mode)") return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
# 7. Preupload LFS file if at least `status.upload_batch_size` files elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size: status.nb_workers_preupload_lfs += 1 logger.debug("Job: preupload LFS") return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
# 8. Compute sha256 if at least 1 file elif status.queue_sha256.qsize() > 0: status.nb_workers_sha256 += 1 logger.debug("Job: sha256") return (WorkerJob.SHA256, _get_one(status.queue_sha256))
# 9. Get upload mode if at least 1 file elif status.queue_get_upload_mode.qsize() > 0: status.nb_workers_get_upload_mode += 1 logger.debug("Job: get upload mode") return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
# 10. Preupload LFS file if at least 1 file elif status.queue_preupload_lfs.qsize() > 0: status.nb_workers_preupload_lfs += 1 logger.debug("Job: preupload LFS") return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
# 11. Commit if at least 1 file and 1 min since last commit attempt elif ( status.nb_workers_commit == 0 and status.queue_commit.qsize() > 0 and status.last_commit_attempt is not None and time.time() - status.last_commit_attempt > 1 * 60 ): status.nb_workers_commit += 1 logger.debug("Job: commit (1 min since last commit attempt)") return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
# 12. Commit if at least 1 file all other queues are empty and all workers are waiting # e.g. when it's the last commit elif ( status.nb_workers_commit == 0 and status.queue_commit.qsize() > 0 and status.queue_sha256.qsize() == 0 and status.queue_get_upload_mode.qsize() == 0 and status.queue_preupload_lfs.qsize() == 0 and status.nb_workers_sha256 == 0 and status.nb_workers_get_upload_mode == 0 and status.nb_workers_preupload_lfs == 0 ): status.nb_workers_commit += 1 logger.debug("Job: commit") return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
# 13. If all queues are empty, exit elif all(metadata.is_committed or metadata.should_ignore for _, metadata in status.items): logger.info("All files have been processed! Exiting worker.") return None
# 14. If no task is available, wait else: status.nb_workers_waiting += 1 logger.debug(f"No task available, waiting... ({WAITING_TIME_IF_NO_TASKS}s)") return (WorkerJob.WAIT, [])
##################### Atomic jobs (sha256, get_upload_mode, preupload_lfs, commit)####################
def _compute_sha256(item: JOB_ITEM_T) -> None: """Compute sha256 of a file and save it in metadata.""" paths, metadata = item if metadata.sha256 is None: with paths.file_path.open("rb") as f: metadata.sha256 = sha_fileobj(f).hex() metadata.save(paths)
def _get_upload_mode(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None: """Get upload mode for each file and update metadata.
Also receive info if the file should be ignored. """ additions = [_build_hacky_operation(item) for item in items] _fetch_upload_modes( additions=additions, repo_type=repo_type, repo_id=repo_id, headers=api._build_hf_headers(), revision=quote(revision, safe=""), endpoint=api.endpoint, ) for item, addition in zip(items, additions): paths, metadata = item metadata.upload_mode = addition._upload_mode metadata.should_ignore = addition._should_ignore metadata.remote_oid = addition._remote_oid metadata.save(paths)
def _preupload_lfs(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None: """Preupload LFS files and update metadata.""" additions = [_build_hacky_operation(item) for item in items] api.preupload_lfs_files( repo_id=repo_id, repo_type=repo_type, revision=revision, additions=additions, )
for paths, metadata in items: metadata.is_uploaded = True metadata.save(paths)
def _commit(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None: """Commit files to the repo.""" additions = [_build_hacky_operation(item) for item in items] api.create_commit( repo_id=repo_id, repo_type=repo_type, revision=revision, operations=additions, commit_message="Add files using upload-large-folder tool", ) for paths, metadata in items: metadata.is_committed = True metadata.save(paths)
##################### Hacks with CommitOperationAdd to bypass checks/sha256 calculation####################
class HackyCommitOperationAdd(CommitOperationAdd): def __post_init__(self) -> None: if isinstance(self.path_or_fileobj, Path): self.path_or_fileobj = str(self.path_or_fileobj)
def _build_hacky_operation(item: JOB_ITEM_T) -> HackyCommitOperationAdd: paths, metadata = item operation = HackyCommitOperationAdd(path_in_repo=paths.path_in_repo, path_or_fileobj=paths.file_path) with paths.file_path.open("rb") as file: sample = file.peek(512)[:512] if metadata.sha256 is None: raise ValueError("sha256 must have been computed by now!") operation.upload_info = UploadInfo(sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample) operation._upload_mode = metadata.upload_mode # type: ignore operation._should_ignore = metadata.should_ignore operation._remote_oid = metadata.remote_oid return operation
##################### Misc helpers####################
def _get_one(queue: "queue.Queue[JOB_ITEM_T]") -> list[JOB_ITEM_T]: return [queue.get()]
def _get_n(queue: "queue.Queue[JOB_ITEM_T]", n: int) -> list[JOB_ITEM_T]: return [queue.get() for _ in range(min(queue.qsize(), n))]
def _print_overwrite(report: str) -> None: """Print a report, overwriting the previous lines.
Since tqdm in using `sys.stderr` to (re-)write progress bars, we need to use `sys.stdout` to print the report.
Note: works well only if no other process is writing to `sys.stdout`! """ report += "\n" # Get terminal width terminal_width = shutil.get_terminal_size().columns
# Count number of lines that should be cleared nb_lines = sum(len(line) // terminal_width + 1 for line in report.splitlines())
# Clear previous lines based on the number of lines in the report for _ in range(nb_lines): sys.stdout.write("\r\033[K") # Clear line sys.stdout.write("\033[F") # Move cursor up one line
# Print the new report, filling remaining space with whitespace sys.stdout.write(report) sys.stdout.write(" " * (terminal_width - len(report.splitlines()[-1]))) sys.stdout.flush()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136# Copyright 2023-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains data structures to parse the webhooks payload."""
from typing import Literal
from .utils import is_pydantic_available
if is_pydantic_available(): from pydantic import BaseModelelse: # Define a dummy BaseModel to avoid import errors when pydantic is not installed # Import error will be raised when trying to use the class
class BaseModel: # type: ignore [no-redef] def __init__(self, *args, **kwargs) -> None: raise ImportError( "You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that" " should be installed separately. Please run `pip install --upgrade pydantic` and retry." )
# This is an adaptation of the ReportV3 interface implemented in moon-landing. V0, V1 and V2 have been ignored as they# are not in used anymore. To keep in sync when format is updated in# https://github.com/huggingface/moon-landing/blob/main/server/lib/HFWebhooks.ts (internal link).
WebhookEvent_T = Literal[ "create", "delete", "move", "update",]RepoChangeEvent_T = Literal[ "add", "move", "remove", "update",]RepoType_T = Literal[ "dataset", "model", "space",]DiscussionStatus_T = Literal[ "closed", "draft", "open", "merged",]SupportedWebhookVersion = Literal[3]
class ObjectId(BaseModel): id: str
class WebhookPayloadUrl(BaseModel): web: str api: str | None = None
class WebhookPayloadMovedTo(BaseModel): name: str owner: ObjectId
class WebhookPayloadWebhook(ObjectId): version: SupportedWebhookVersion
class WebhookPayloadEvent(BaseModel): action: WebhookEvent_T scope: str
class WebhookPayloadDiscussionChanges(BaseModel): base: str mergeCommitId: str | None = None
class WebhookPayloadComment(ObjectId): author: ObjectId hidden: bool content: str | None = None url: WebhookPayloadUrl
class WebhookPayloadDiscussion(ObjectId): num: int author: ObjectId url: WebhookPayloadUrl title: str isPullRequest: bool status: DiscussionStatus_T changes: WebhookPayloadDiscussionChanges | None = None pinned: bool | None = None
class WebhookPayloadRepo(ObjectId): owner: ObjectId head_sha: str | None = None name: str private: bool subdomain: str | None = None tags: list[str] | None = None type: Literal["dataset", "model", "space"] url: WebhookPayloadUrl
class WebhookPayloadUpdatedRef(BaseModel): ref: str oldSha: str | None = None newSha: str | None = None
class WebhookPayload(BaseModel): event: WebhookPayloadEvent repo: WebhookPayloadRepo discussion: WebhookPayloadDiscussion | None = None comment: WebhookPayloadComment | None = None webhook: WebhookPayloadWebhook movedTo: WebhookPayloadMovedTo | None = None updatedRefs: list[WebhookPayloadUpdatedRef] | None = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376# Copyright 2023-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains `WebhooksServer` and `webhook_endpoint` to create a webhook server easily."""
import atexitimport inspectimport osfrom collections.abc import Callablefrom functools import wrapsfrom typing import TYPE_CHECKING, Any, Optional
from .utils import experimental, is_fastapi_available, is_gradio_available
if TYPE_CHECKING: import gradio as gr from fastapi import Request
if is_fastapi_available(): from fastapi import FastAPI, Request from fastapi.responses import JSONResponseelse: # Will fail at runtime if FastAPI is not available FastAPI = Request = JSONResponse = None # type: ignore
_global_app: Optional["WebhooksServer"] = None_is_local = os.environ.get("SPACE_ID") is None
@experimentalclass WebhooksServer: """ The [`WebhooksServer`] class lets you create an instance of a Gradio app that can receive Huggingface webhooks. These webhooks can be registered using the [`~WebhooksServer.add_webhook`] decorator. Webhook endpoints are added to the app as a POST endpoint to the FastAPI router. Once all the webhooks are registered, the `launch` method has to be called to start the app.
It is recommended to accept [`WebhookPayload`] as the first argument of the webhook function. It is a Pydantic model that contains all the information about the webhook event. The data will be parsed automatically for you.
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your WebhooksServer and deploy it on a Space.
> [!WARNING] > `WebhooksServer` is experimental. Its API is subject to change in the future.
> [!WARNING] > You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`).
Args: ui (`gradio.Blocks`, optional): A Gradio UI instance to be used as the Space landing page. If `None`, a UI displaying instructions about the configured webhooks is created. webhook_secret (`str`, optional): A secret key to verify incoming webhook requests. You can set this value to any secret you want as long as you also configure it in your [webhooks settings panel](https://huggingface.co/settings/webhooks). You can also set this value as the `WEBHOOK_SECRET` environment variable. If no secret is provided, the webhook endpoints are opened without any security.
Example:
```python import gradio as gr from huggingface_hub import WebhooksServer, WebhookPayload
with gr.Blocks() as ui: ...
app = WebhooksServer(ui=ui, webhook_secret="my_secret_key")
@app.add_webhook("/say_hello") async def hello(payload: WebhookPayload): return {"message": "hello"}
app.launch() ``` """
def __new__(cls, *args, **kwargs) -> "WebhooksServer": if not is_gradio_available(): raise ImportError( "You must have `gradio` installed to use `WebhooksServer`. Please run `pip install --upgrade gradio`" " first." ) if not is_fastapi_available(): raise ImportError( "You must have `fastapi` installed to use `WebhooksServer`. Please run `pip install --upgrade fastapi`" " first." ) return super().__new__(cls)
def __init__( self, ui: Optional["gr.Blocks"] = None, webhook_secret: str | None = None, ) -> None: self._ui = ui
self.webhook_secret = webhook_secret or os.getenv("WEBHOOK_SECRET") self.registered_webhooks: dict[str, Callable] = {} _warn_on_empty_secret(self.webhook_secret)
def add_webhook(self, path: str | None = None) -> Callable: """ Decorator to add a webhook to the [`WebhooksServer`] server.
Args: path (`str`, optional): The URL path to register the webhook function. If not provided, the function name will be used as the path. In any case, all webhooks are registered under `/webhooks`.
Raises: ValueError: If the provided path is already registered as a webhook.
Example: ```python from huggingface_hub import WebhooksServer, WebhookPayload
app = WebhooksServer()
@app.add_webhook async def trigger_training(payload: WebhookPayload): if payload.repo.type == "dataset" and payload.event.action == "update": # Trigger a training job if a dataset is updated ...
app.launch() ``` """ # Usage: directly as decorator. Example: `@app.add_webhook` if callable(path): # If path is a function, it means it was used as a decorator without arguments return self.add_webhook()(path)
# Usage: provide a path. Example: `@app.add_webhook(...)` @wraps(FastAPI.post) def _inner_post(*args, **kwargs): func = args[0] abs_path = f"/webhooks/{(path or func.__name__).strip('/')}" if abs_path in self.registered_webhooks: raise ValueError(f"Webhook {abs_path} already exists.") self.registered_webhooks[abs_path] = func
return _inner_post
def launch(self, prevent_thread_lock: bool = False, **launch_kwargs: Any) -> None: """Launch the Gradio app and register webhooks to the underlying FastAPI server.
Input parameters are forwarded to Gradio when launching the app. """ ui = self._ui or self._get_default_ui()
# Start Gradio App # - as non-blocking so that webhooks can be added afterwards # - as shared if launch locally (to debug webhooks) launch_kwargs.setdefault("share", _is_local) self.fastapi_app, _, _ = ui.launch(prevent_thread_lock=True, **launch_kwargs)
# Register webhooks to FastAPI app for path, func in self.registered_webhooks.items(): # Add secret check if required if self.webhook_secret is not None: func = _wrap_webhook_to_check_secret(func, webhook_secret=self.webhook_secret)
# Add route to FastAPI app self.fastapi_app.post(path)(func)
# Print instructions and block main thread space_host = os.environ.get("SPACE_HOST") url = "https://" + space_host if space_host is not None else (ui.share_url or ui.local_url) if url is None: raise ValueError("Cannot find the URL of the app. Please provide a valid `ui` or update `gradio` version.") url = url.strip("/") message = "\nWebhooks are correctly setup and ready to use:" message += "\n" + "\n".join(f" - POST {url}{webhook}" for webhook in self.registered_webhooks) message += "\nGo to https://huggingface.co/settings/webhooks to setup your webhooks." print(message)
if not prevent_thread_lock: ui.block_thread()
def _get_default_ui(self) -> "gr.Blocks": """Default UI if not provided (lists webhooks and provides basic instructions).""" import gradio as gr
with gr.Blocks() as ui: gr.Markdown("# This is an app to process 🤗 Webhooks") gr.Markdown( "Webhooks are a foundation for MLOps-related features. They allow you to listen for new changes on" " specific repos or to all repos belonging to particular set of users/organizations (not just your" " repos, but any repo). Check out this [guide](https://huggingface.co/docs/hub/webhooks) to get to" " know more about webhooks on the Huggingface Hub." ) gr.Markdown( f"{len(self.registered_webhooks)} webhook(s) are registered:" + "\n\n" + "\n ".join( f"- [{webhook_path}]({_get_webhook_doc_url(webhook.__name__, webhook_path)})" for webhook_path, webhook in self.registered_webhooks.items() ) ) gr.Markdown( "Go to https://huggingface.co/settings/webhooks to setup your webhooks." + "\nYou app is running locally. Please look at the logs to check the full URL you need to set." if _is_local else ( "\nThis app is running on a Space. You can find the corresponding URL in the options menu" " (top-right) > 'Embed the Space'. The URL looks like 'https://{username}-{repo_name}.hf.space'." ) ) return ui
@experimentaldef webhook_endpoint(path: str | None = None) -> Callable: """Decorator to start a [`WebhooksServer`] and register the decorated function as a webhook endpoint.
This is a helper to get started quickly. If you need more flexibility (custom landing page or webhook secret), you can use [`WebhooksServer`] directly. You can register multiple webhook endpoints (to the same server) by using this decorator multiple times.
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your server and deploy it on a Space.
> [!WARNING] > `webhook_endpoint` is experimental. Its API is subject to change in the future.
> [!WARNING] > You must have `gradio` installed to use `webhook_endpoint` (`pip install --upgrade gradio`).
Args: path (`str`, optional): The URL path to register the webhook function. If not provided, the function name will be used as the path. In any case, all webhooks are registered under `/webhooks`.
Examples: The default usage is to register a function as a webhook endpoint. The function name will be used as the path. The server will be started automatically at exit (i.e. at the end of the script).
```python from huggingface_hub import webhook_endpoint, WebhookPayload
@webhook_endpoint async def trigger_training(payload: WebhookPayload): if payload.repo.type == "dataset" and payload.event.action == "update": # Trigger a training job if a dataset is updated ...
# Server is automatically started at the end of the script. ```
Advanced usage: register a function as a webhook endpoint and start the server manually. This is useful if you are running it in a notebook.
```python from huggingface_hub import webhook_endpoint, WebhookPayload
@webhook_endpoint async def trigger_training(payload: WebhookPayload): if payload.repo.type == "dataset" and payload.event.action == "update": # Trigger a training job if a dataset is updated ...
# Start the server manually trigger_training.launch() ``` """ if callable(path): # If path is a function, it means it was used as a decorator without arguments return webhook_endpoint()(path)
@wraps(WebhooksServer.add_webhook) def _inner(func: Callable) -> Callable: app = _get_global_app() app.add_webhook(path)(func) if len(app.registered_webhooks) == 1: # Register `app.launch` to run at exit (only once) atexit.register(app.launch)
@wraps(app.launch) def _launch_now(): # Run the app directly (without waiting atexit) atexit.unregister(app.launch) app.launch()
func.launch = _launch_now # type: ignore return func
return _inner
def _get_global_app() -> WebhooksServer: global _global_app if _global_app is None: _global_app = WebhooksServer() return _global_app
def _warn_on_empty_secret(webhook_secret: str | None) -> None: if webhook_secret is None: print("Webhook secret is not defined. This means your webhook endpoints will be open to everyone.") print( "To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization: " "\n\t`app = WebhooksServer(webhook_secret='my_secret', ...)`" ) print( "For more details about webhook secrets, please refer to" " https://huggingface.co/docs/hub/webhooks#webhook-secret." ) else: print("Webhook secret is correctly defined.")
def _get_webhook_doc_url(webhook_name: str, webhook_path: str) -> str: """Returns the anchor to a given webhook in the docs (experimental)""" return "/docs#/default/" + webhook_name + webhook_path.replace("/", "_") + "_post"
def _wrap_webhook_to_check_secret(func: Callable, webhook_secret: str) -> Callable: """Wraps a webhook function to check the webhook secret before calling the function.
This is a hacky way to add the `request` parameter to the function signature. Since FastAPI based itself on route parameters to inject the values to the function, we need to hack the function signature to retrieve the `Request` object (and hence the headers). A far cleaner solution would be to use a middleware. However, since `fastapi==0.90.1`, a middleware cannot be added once the app has started. And since the FastAPI app is started by Gradio internals (and not by us), we cannot add a middleware.
This method is called only when a secret has been defined by the user. If a request is sent without the "x-webhook-secret", the function will return a 401 error (unauthorized). If the header is sent but is incorrect, the function will return a 403 error (forbidden).
Inspired by https://stackoverflow.com/a/33112180. """ initial_sig = inspect.signature(func)
@wraps(func) async def _protected_func(request: Request, **kwargs): request_secret = request.headers.get("x-webhook-secret") if request_secret is None: return JSONResponse({"error": "x-webhook-secret header not set."}, status_code=401) if request_secret != webhook_secret: return JSONResponse({"error": "Invalid webhook secret."}, status_code=403)
# Inject `request` in kwargs if required if "request" in initial_sig.parameters: kwargs["request"] = request
# Handle both sync and async routes if inspect.iscoroutinefunction(func): return await func(**kwargs) else: return func(**kwargs)
# Update signature to include request if "request" not in initial_sig.parameters: _protected_func.__signature__ = initial_sig.replace( # type: ignore parameters=( inspect.Parameter(name="request", kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request), ) + tuple(initial_sig.parameters.values()) )
# Return protected route return _protected_func123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165# Copyright 2020 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to authenticate to the Hugging Face Hub and interact with your repositories.
Usage: # login and save token locally. hf auth login --token=hf_*** --add-to-git-credential
# switch between tokens hf auth switch
# list all tokens hf auth list
# logout from all tokens hf auth logout
# check which account you are logged in as hf auth whoami"""
from typing import Annotated
import typer
from huggingface_hub.constants import ENDPOINTfrom huggingface_hub.hf_api import whoami
from .._login import auth_list, auth_switch, login, logoutfrom ..utils import get_stored_tokens, get_token, loggingfrom ._cli_utils import FormatWithAutoOpt, OutputFormatWithAuto, TokenOpt, typer_factoryfrom ._output import out
logger = logging.get_logger(__name__)
auth_cli = typer_factory(help="Manage authentication (login, logout, etc.).")
@auth_cli.command( "login", examples=[ "hf auth login", "hf auth login --token $HF_TOKEN", "hf auth login --token $HF_TOKEN --add-to-git-credential", "hf auth login --force", ],)def auth_login( token: TokenOpt = None, add_to_git_credential: Annotated[ bool, typer.Option( help="Save to git credential helper. Useful only if you plan to run git commands directly.", ), ] = False, force: Annotated[ bool, typer.Option( help="Force re-login even if already logged in.", ), ] = False,) -> None: """Login using a token from huggingface.co/settings/tokens.""" login(token=token, add_to_git_credential=add_to_git_credential, skip_if_logged_in=not force)
@auth_cli.command( "logout", examples=["hf auth logout", "hf auth logout --token-name my-token"],)def auth_logout( token_name: Annotated[ str | None, typer.Option(help="Name of token to logout"), ] = None,) -> None: """Logout from a specific token.""" logout(token_name=token_name)
def _select_token_name() -> str | None: token_names = list(get_stored_tokens().keys())
if not token_names: logger.error("No stored tokens found. Please login first.") return None
print("Available stored tokens:") for i, token_name in enumerate(token_names, 1): print(f"{i}. {token_name}") while True: try: choice = input("Enter the number of the token to switch to (or 'q' to quit): ") if choice.lower() == "q": return None index = int(choice) - 1 if 0 <= index < len(token_names): return token_names[index] else: print("Invalid selection. Please try again.") except ValueError: print("Invalid input. Please enter a number or 'q' to quit.")
@auth_cli.command( "switch", examples=["hf auth switch", "hf auth switch --token-name my-token"],)def auth_switch_cmd( token_name: Annotated[ str | None, typer.Option( help="Name of the token to switch to", ), ] = None, add_to_git_credential: Annotated[ bool, typer.Option( help="Save to git credential helper. Useful only if you plan to run git commands directly.", ), ] = False,) -> None: """Switch between access tokens.""" if token_name is None: token_name = _select_token_name() if token_name is None: print("No token name provided. Aborting.") raise typer.Exit() auth_switch(token_name, add_to_git_credential=add_to_git_credential)
@auth_cli.command("list | ls", examples=["hf auth list"])def auth_list_cmd() -> None: """List all stored access tokens.""" auth_list()
@auth_cli.command("whoami", examples=["hf auth whoami", "hf auth whoami --format json"])def auth_whoami( format: FormatWithAutoOpt = OutputFormatWithAuto.auto,) -> None: """Find out which huggingface.co account you are logged in as."""
token = get_token() if token is None: out.error("Not logged in") raise typer.Exit(code=1)
info = whoami(token) orgs = ",".join(org["name"] for org in info["orgs"]) or None endpoint = ENDPOINT if ENDPOINT != "https://huggingface.co" else None out.result("Logged in", user=info["name"], orgs=orgs, endpoint=endpoint)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082# Copyright 2025-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with buckets via the CLI."""
import jsonimport osimport sysfrom datetime import datetimefrom typing import Annotated
import typer
from huggingface_hub import loggingfrom huggingface_hub._buckets import ( BUCKET_PREFIX, BucketFile, BucketFolder, FilterMatcher, _is_bucket_path, _parse_bucket_path, _split_bucket_id_and_prefix,)from huggingface_hub.utils import ( SoftTemporaryDirectory, StatusLine, are_progress_bars_disabled, disable_progress_bars, enable_progress_bars,)
from ._cli_utils import ( FormatOpt, OutputFormat, QuietOpt, TokenOpt, api_object_to_dict, get_hf_api, print_list_output, typer_factory,)
logger = logging.get_logger(__name__)
buckets_cli = typer_factory(help="Commands to interact with buckets.")
def _is_hf_handle(path: str) -> bool: return path.startswith("hf://")
def _parse_bucket_argument(argument: str) -> tuple[str, str]: """Parse a bucket argument accepting both 'namespace/name(/prefix)' and 'hf://buckets/namespace/name(/prefix)'.
Returns: tuple: (bucket_id, prefix) where bucket_id is "namespace/bucket_name" and prefix may be empty string. """ if argument.startswith(BUCKET_PREFIX): return _parse_bucket_path(argument) try: return _split_bucket_id_and_prefix(argument) except ValueError: raise ValueError( f"Invalid bucket argument: {argument}. Must be in format namespace/bucket_name" f" or {BUCKET_PREFIX}namespace/bucket_name" )
def _format_size(size: int | float, human_readable: bool = False) -> str: """Format a size in bytes.""" if not human_readable: return str(size)
for unit in ["B", "KB", "MB", "GB", "TB"]: if size < 1000: if unit == "B": return f"{size} {unit}" return f"{size:.1f} {unit}" size /= 1000 return f"{size:.1f} PB"
def _format_mtime(mtime: datetime | None, human_readable: bool = False) -> str: """Format mtime datetime to a readable date string.""" if mtime is None: return "" if human_readable: return mtime.strftime("%b %d %H:%M") return mtime.strftime("%Y-%m-%d %H:%M:%S")
def _build_tree( items: list[BucketFile | BucketFolder], human_readable: bool = False, quiet: bool = False,) -> list[str]: """Build a tree representation of files and directories.
Produces ASCII tree with size and date columns before the tree connector. When quiet=True, only the tree structure is shown (no size/date).
Args: items: List of BucketFile/BucketFolder items human_readable: Whether to show human-readable sizes and short dates quiet: If True, show only the tree structure without sizes/dates
Returns: List of formatted tree lines """ # Build a nested structure tree: dict = {}
for item in items: parts = item.path.split("/") current = tree for part in parts[:-1]: if part not in current: current[part] = {"__children__": {}} current = current[part]["__children__"]
final_part = parts[-1] if isinstance(item, BucketFolder): if final_part not in current: current[final_part] = {"__children__": {}} else: current[final_part] = {"__item__": item}
# Compute prefix width for alignment (size + date columns) prefix_width = 0 max_size_width = 0 max_date_width = 0 if not quiet: for item in items: if isinstance(item, BucketFile): size_str = _format_size(item.size, human_readable) max_size_width = max(max_size_width, len(size_str)) date_str = _format_mtime(item.mtime, human_readable) max_date_width = max(max_date_width, len(date_str)) if max_size_width > 0: prefix_width = max_size_width + 2 + max_date_width
# Render tree lines: list[str] = [] _render_tree( tree, lines, "", prefix_width=prefix_width, max_size_width=max_size_width, human_readable=human_readable, ) return lines
def _render_tree( node: dict, lines: list[str], indent: str, prefix_width: int = 0, max_size_width: int = 0, human_readable: bool = False,) -> None: """Recursively render a tree structure with size+date prefix.""" items = sorted(node.items()) for i, (name, value) in enumerate(items): is_last = i == len(items) - 1 connector = "└── " if is_last else "├── "
is_dir = "__children__" in value children = value.get("__children__", {})
if prefix_width > 0: if is_dir: prefix = " " * prefix_width else: item = value.get("__item__") if item is not None: size_str = _format_size(item.size, human_readable) date_str = _format_mtime(item.mtime, human_readable) prefix = f"{size_str:>{max_size_width}} {date_str}" else: prefix = " " * prefix_width lines.append(f"{prefix} {indent}{connector}{name}{'/' if is_dir else ''}") else: lines.append(f"{indent}{connector}{name}{'/' if is_dir else ''}")
if children: child_indent = indent + (" " if is_last else "│ ") _render_tree( children, lines, child_indent, prefix_width=prefix_width, max_size_width=max_size_width, human_readable=human_readable, )
@buckets_cli.command( name="create", examples=[ "hf buckets create my-bucket", "hf buckets create user/my-bucket", "hf buckets create hf://buckets/user/my-bucket", "hf buckets create user/my-bucket --private", "hf buckets create user/my-bucket --exist-ok", ],)def create( bucket_id: Annotated[ str, typer.Argument( help="Bucket ID: bucket_name, namespace/bucket_name, or hf://buckets/namespace/bucket_name", ), ], private: Annotated[ bool, typer.Option( "--private", help="Create a private bucket.", ), ] = False, exist_ok: Annotated[ bool, typer.Option( "--exist-ok", help="Do not raise an error if the bucket already exists.", ), ] = False, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """Create a new bucket.""" api = get_hf_api(token=token)
if bucket_id.startswith(BUCKET_PREFIX): try: parsed_id, prefix = _parse_bucket_argument(bucket_id) except ValueError as e: raise typer.BadParameter(str(e)) if prefix: raise typer.BadParameter( f"Cannot specify a prefix for bucket creation: {bucket_id}." f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name." ) bucket_id = parsed_id
bucket_url = api.create_bucket( bucket_id, private=private if private else None, exist_ok=exist_ok, ) if quiet: print(bucket_url.handle) else: print(f"Bucket created: {bucket_url.url} (handle: {bucket_url.handle})")
def _is_bucket_id(argument: str) -> bool: """Check if argument is a bucket ID (namespace/name) vs just a namespace.""" if argument.startswith(BUCKET_PREFIX): path = argument[len(BUCKET_PREFIX) :] else: path = argument return "/" in path
@buckets_cli.command( name="list | ls", examples=[ "hf buckets list", "hf buckets list huggingface", "hf buckets list user/my-bucket", "hf buckets list user/my-bucket -R", "hf buckets list user/my-bucket -h", "hf buckets list user/my-bucket --tree", "hf buckets list user/my-bucket --tree -h", "hf buckets list hf://buckets/user/my-bucket", "hf buckets list user/my-bucket/sub -R", ],)def list_cmd( argument: Annotated[ str | None, typer.Argument( help=( "Namespace (user or org) to list buckets, or bucket ID" " (namespace/bucket_name(/prefix) or hf://buckets/...) to list files." ), ), ] = None, human_readable: Annotated[ bool, typer.Option( "--human-readable", "-h", help="Show sizes in human readable format.", ), ] = False, as_tree: Annotated[ bool, typer.Option( "--tree", help="List files in tree format (only for listing files).", ), ] = False, recursive: Annotated[ bool, typer.Option( "--recursive", "-R", help="List files recursively (only for listing files).", ), ] = False, format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """List buckets or files in a bucket.
When called with no argument or a namespace, lists buckets. When called with a bucket ID (namespace/bucket_name), lists files in the bucket. """ # Determine mode: listing buckets or listing files is_file_mode = argument is not None and _is_bucket_id(argument)
if is_file_mode: _list_files( argument=argument, # type: ignore human_readable=human_readable, as_tree=as_tree, recursive=recursive, format=format, quiet=quiet, token=token, ) else: _list_buckets( namespace=argument, human_readable=human_readable, as_tree=as_tree, recursive=recursive, format=format, quiet=quiet, token=token, )
def _list_buckets( namespace: str | None, human_readable: bool, as_tree: bool, recursive: bool, format: OutputFormat, quiet: bool, token: str | None,) -> None: """List buckets in a namespace.""" # Validate incompatible flags if as_tree: raise typer.BadParameter("Cannot use --tree when listing buckets.") if recursive: raise typer.BadParameter("Cannot use --recursive when listing buckets.")
# Handle hf://buckets/namespace format if namespace is not None and namespace.startswith(BUCKET_PREFIX): namespace = namespace[len(BUCKET_PREFIX) :] # Strip trailing slash if any namespace = namespace.rstrip("/")
api = get_hf_api(token=token) results = [api_object_to_dict(bucket) for bucket in api.list_buckets(namespace=namespace)]
if not results: if not quiet and format != OutputFormat.json: resolved_namespace = namespace if namespace is not None else api.whoami()["name"] print(f"No buckets found under namespace '{resolved_namespace}'.") return
headers = ["id", "private", "size", "total_files", "created_at"]
def row_fn(item: dict) -> list[str]: from ._cli_utils import _format_cell
return [ _format_cell(item.get("id")), _format_cell(item.get("private")), _format_size(item.get("size", 0), human_readable=human_readable), _format_cell(item.get("total_files")), _format_cell(item.get("created_at")), ]
alignments = {"size": "right", "total_files": "right"} print_list_output(results, format=format, quiet=quiet, headers=headers, row_fn=row_fn, alignments=alignments)
def _list_files( argument: str, human_readable: bool, as_tree: bool, recursive: bool, format: OutputFormat, quiet: bool, token: str | None,) -> None: """List files in a bucket.""" # Validate incompatible flags if as_tree and format == OutputFormat.json: raise typer.BadParameter("Cannot use --tree with --format json.")
api = get_hf_api(token=token)
try: bucket_id, prefix = _parse_bucket_argument(argument) except ValueError as e: raise typer.BadParameter(str(e))
# Fetch items from the bucket items = list( api.list_bucket_tree( bucket_id, prefix=prefix or None, recursive=recursive, ) )
if not items: print("(empty)") return
has_directories = any(isinstance(item, BucketFolder) for item in items)
if format == OutputFormat.json: results = [api_object_to_dict(item) for item in items] print(json.dumps(results, indent=2)) elif as_tree: # Tree format with size+date prefix, or quiet for structure only tree_lines = _build_tree(items, human_readable=human_readable, quiet=quiet) for line in tree_lines: print(line) elif quiet: for item in items: if isinstance(item, BucketFolder): print(f"{item.path}/") else: print(item.path) else: # Flat table format for item in items: if isinstance(item, BucketFolder): mtime_str = _format_mtime(item.uploaded_at, human_readable) print(f"{'':>12} {mtime_str:>19} {item.path}/") else: size_str = _format_size(item.size, human_readable) mtime_str = _format_mtime(item.mtime, human_readable) print(f"{size_str:>12} {mtime_str:>19} {item.path}")
if not recursive and has_directories: StatusLine().done("Use -R to list files recursively.")
@buckets_cli.command( name="info", examples=[ "hf buckets info user/my-bucket", "hf buckets info hf://buckets/user/my-bucket", ],)def info( bucket_id: Annotated[ str, typer.Argument( help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name", ), ], quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """Get info about a bucket.""" api = get_hf_api(token=token)
try: parsed_id, _ = _parse_bucket_argument(bucket_id) except ValueError as e: raise typer.BadParameter(str(e))
bucket = api.bucket_info(parsed_id) if quiet: print(bucket.id) else: print(json.dumps(api_object_to_dict(bucket), indent=2))
@buckets_cli.command( name="delete", examples=[ "hf buckets delete user/my-bucket", "hf buckets delete hf://buckets/user/my-bucket", "hf buckets delete user/my-bucket --yes", "hf buckets delete user/my-bucket --missing-ok", ],)def delete( bucket_id: Annotated[ str, typer.Argument( help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name", ), ], yes: Annotated[ bool, typer.Option( "--yes", "-y", help="Skip confirmation prompt.", ), ] = False, missing_ok: Annotated[ bool, typer.Option( "--missing-ok", help="Do not raise an error if the bucket does not exist.", ), ] = False, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """Delete a bucket.
This deletes the entire bucket and all its contents. Use `hf buckets rm` to remove individual files. """ if bucket_id.startswith(BUCKET_PREFIX): try: parsed_id, prefix = _parse_bucket_argument(bucket_id) except ValueError as e: raise typer.BadParameter(str(e)) if prefix: raise typer.BadParameter( f"Cannot specify a prefix for bucket deletion: {bucket_id}." f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name." ) bucket_id = parsed_id elif "/" not in bucket_id: raise typer.BadParameter( f"Invalid bucket ID: {bucket_id}." f" Must be in format namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name." )
if not yes: confirm = typer.confirm(f"Are you sure you want to delete bucket '{bucket_id}'?") if not confirm: print("Aborted.") raise typer.Abort()
api = get_hf_api(token=token) api.delete_bucket(bucket_id, missing_ok=missing_ok) if quiet: print(bucket_id) else: print(f"Bucket deleted: {bucket_id}")
@buckets_cli.command( name="remove | rm", examples=[ "hf buckets remove user/my-bucket/file.txt", "hf buckets rm hf://buckets/user/my-bucket/file.txt", "hf buckets rm user/my-bucket/logs/ --recursive", 'hf buckets rm user/my-bucket --recursive --include "*.tmp"', "hf buckets rm user/my-bucket/data/ --recursive --dry-run", ],)def remove( argument: Annotated[ str, typer.Argument( help=( "Bucket path: namespace/bucket_name/path or hf://buckets/namespace/bucket_name/path." " With --recursive, namespace/bucket_name is also accepted to target all files." ), ), ], recursive: Annotated[ bool, typer.Option( "--recursive", "-R", help="Remove files recursively under the given prefix.", ), ] = False, yes: Annotated[ bool, typer.Option( "--yes", "-y", help="Skip confirmation prompt.", ), ] = False, dry_run: Annotated[ bool, typer.Option( "--dry-run", help="Preview what would be deleted without actually deleting.", ), ] = False, include: Annotated[ list[str] | None, typer.Option( help="Include only files matching pattern (can specify multiple). Requires --recursive.", ), ] = None, exclude: Annotated[ list[str] | None, typer.Option( help="Exclude files matching pattern (can specify multiple). Requires --recursive.", ), ] = None, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """Remove files from a bucket.
To delete an entire bucket, use `hf buckets delete` instead. """ try: bucket_id, prefix = _parse_bucket_argument(argument) except ValueError as e: raise typer.BadParameter(str(e))
if prefix == "" and not recursive: raise typer.BadParameter( f"No file path specified. To remove files, provide a path" f" (e.g. '{bucket_id}/FILE') or use --recursive to remove all files." f" To delete the entire bucket, use `hf buckets delete {bucket_id}`." )
if (include or exclude) and not recursive: raise typer.BadParameter("--include and --exclude require --recursive.")
api = get_hf_api(token=token)
if recursive: status = StatusLine(enabled=not quiet) status.update("Listing files from remote")
all_files: list[BucketFile] = [] for item in api.list_bucket_tree( bucket_id, prefix=prefix.rstrip("/") or None, recursive=True, ): if isinstance(item, BucketFile): all_files.append(item) status.update(f"Listing files from remote ({len(all_files)} files)") status.done(f"Listing files from remote ({len(all_files)} files)")
if include or exclude: matcher = FilterMatcher(include_patterns=include, exclude_patterns=exclude) matched_files = [f for f in all_files if matcher.matches(f.path)] else: matched_files = all_files
file_paths = [f.path for f in matched_files] total_size = sum(f.size for f in matched_files) size_str = _format_size(total_size, human_readable=True)
if not file_paths: if not quiet: print("No files to remove.") return
count_label = f"{len(file_paths)} file(s) totaling {size_str}"
if not yes and not dry_run: if not quiet: for path in file_paths: print(f" {path}") confirm = typer.confirm(f"Remove {count_label} from '{bucket_id}'?") if not confirm: print("Aborted.") raise typer.Abort()
if dry_run: for path in file_paths: print(f"delete: {BUCKET_PREFIX}{bucket_id}/{path}") print(f"(dry run) {count_label} would be removed.") return
api.batch_bucket_files(bucket_id, delete=file_paths) if quiet: for path in file_paths: print(path) else: for path in file_paths: print(f"delete: {BUCKET_PREFIX}{bucket_id}/{path}") print(f"Removed {count_label} from '{bucket_id}'.")
else: file_path = prefix.rstrip("/") if not file_path: raise typer.BadParameter("File path cannot be empty.")
if dry_run: print(f"delete: {BUCKET_PREFIX}{bucket_id}/{file_path}") print("(dry run) 1 file would be removed.") return
if not yes: confirm = typer.confirm(f"Remove '{file_path}' from '{bucket_id}'?") if not confirm: print("Aborted.") raise typer.Abort()
api.batch_bucket_files(bucket_id, delete=[file_path]) if quiet: print(file_path) else: print(f"delete: {BUCKET_PREFIX}{bucket_id}/{file_path}")
@buckets_cli.command( name="move", examples=[ "hf buckets move user/old-bucket user/new-bucket", "hf buckets move user/my-bucket my-org/my-bucket", "hf buckets move hf://buckets/user/old-bucket hf://buckets/user/new-bucket", ],)def move( from_id: Annotated[ str, typer.Argument( help="Source bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name", ), ], to_id: Annotated[ str, typer.Argument( help="Destination bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name", ), ], token: TokenOpt = None,) -> None: """Move (rename) a bucket to a new name or namespace.""" # Parse from_id parsed_from_id, from_prefix = _parse_bucket_argument(from_id) if from_prefix: raise typer.BadParameter( f"Cannot specify a prefix for bucket move: {from_id}." f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name." )
# Parse to_id parsed_to_id, to_prefix = _parse_bucket_argument(to_id) if to_prefix: raise typer.BadParameter( f"Cannot specify a prefix for bucket move: {to_id}." f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name." )
api = get_hf_api(token=token) api.move_bucket(from_id=parsed_from_id, to_id=parsed_to_id) print(f"Bucket moved: {parsed_from_id} -> {parsed_to_id}")
# =============================================================================# Sync command# =============================================================================
@buckets_cli.command( name="sync", examples=[ "hf buckets sync ./data hf://buckets/user/my-bucket", "hf buckets sync hf://buckets/user/my-bucket ./data", "hf buckets sync ./data hf://buckets/user/my-bucket --delete", 'hf buckets sync hf://buckets/user/my-bucket ./data --include "*.safetensors" --exclude "*.tmp"', "hf buckets sync ./data hf://buckets/user/my-bucket --plan sync-plan.jsonl", "hf buckets sync --apply sync-plan.jsonl", "hf buckets sync ./data hf://buckets/user/my-bucket --dry-run", "hf buckets sync ./data hf://buckets/user/my-bucket --dry-run | jq .", ],)def sync( source: Annotated[ str | None, typer.Argument( help="Source path: local directory or hf://buckets/namespace/bucket_name(/prefix)", ), ] = None, dest: Annotated[ str | None, typer.Argument( help="Destination path: local directory or hf://buckets/namespace/bucket_name(/prefix)", ), ] = None, delete: Annotated[ bool, typer.Option( help="Delete destination files not present in source.", ), ] = False, ignore_times: Annotated[ bool, typer.Option( "--ignore-times", help="Skip files only based on size, ignoring modification times.", ), ] = False, ignore_sizes: Annotated[ bool, typer.Option( "--ignore-sizes", help="Skip files only based on modification times, ignoring sizes.", ), ] = False, plan: Annotated[ str | None, typer.Option( help="Save sync plan to JSONL file for review instead of executing.", ), ] = None, apply: Annotated[ str | None, typer.Option( help="Apply a previously saved plan file.", ), ] = None, dry_run: Annotated[ bool, typer.Option( "--dry-run", help="Print sync plan to stdout as JSONL without executing.", ), ] = False, include: Annotated[ list[str] | None, typer.Option( help="Include files matching pattern (can specify multiple).", ), ] = None, exclude: Annotated[ list[str] | None, typer.Option( help="Exclude files matching pattern (can specify multiple).", ), ] = None, filter_from: Annotated[ str | None, typer.Option( help="Read include/exclude patterns from file.", ), ] = None, existing: Annotated[ bool, typer.Option( "--existing", help="Skip creating new files on receiver (only update existing files).", ), ] = False, ignore_existing: Annotated[ bool, typer.Option( "--ignore-existing", help="Skip updating files that exist on receiver (only create new files).", ), ] = False, verbose: Annotated[ bool, typer.Option( "--verbose", "-v", help="Show detailed logging with reasoning.", ), ] = False, quiet: Annotated[ bool, typer.Option( "--quiet", "-q", help="Minimal output.", ), ] = False, token: TokenOpt = None,) -> None: """Sync files between local directory and a bucket.""" api = get_hf_api(token=token) api.sync_bucket( source=source, dest=dest, delete=delete, ignore_times=ignore_times, ignore_sizes=ignore_sizes, existing=existing, ignore_existing=ignore_existing, include=include, exclude=exclude, filter_from=filter_from, plan=plan, apply=apply, dry_run=dry_run, verbose=verbose, quiet=quiet, )
# =============================================================================# Cp command# =============================================================================
@buckets_cli.command( name="cp", examples=[ "hf buckets cp hf://buckets/user/my-bucket/config.json", "hf buckets cp hf://buckets/user/my-bucket/config.json ./data/", "hf buckets cp hf://buckets/user/my-bucket/config.json my-config.json", "hf buckets cp hf://buckets/user/my-bucket/config.json -", "hf buckets cp my-config.json hf://buckets/user/my-bucket", "hf buckets cp my-config.json hf://buckets/user/my-bucket/logs/", "hf buckets cp my-config.json hf://buckets/user/my-bucket/remote-config.json", "hf buckets cp - hf://buckets/user/my-bucket/config.json", "hf buckets cp hf://buckets/user/my-bucket/logs/ hf://buckets/user/archive-bucket/logs/", "hf buckets cp hf://datasets/user/my-dataset/processed/ hf://buckets/user/my-bucket/dataset/processed/", ],)def cp( src: Annotated[str, typer.Argument(help="Source: local file, HF handle (hf://...), or - for stdin")], dst: Annotated[ str | None, typer.Argument(help="Destination: local path, HF handle (hf://...), or - for stdout") ] = None, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """Copy files to or from buckets.""" api = get_hf_api(token=token)
src_is_hf = _is_hf_handle(src) dst_is_hf = dst is not None and _is_hf_handle(dst) src_is_bucket = _is_bucket_path(src) dst_is_bucket = dst is not None and _is_bucket_path(dst) src_is_stdin = src == "-" dst_is_stdout = dst == "-"
# Remote to remote copy if src_is_hf and dst_is_hf: if quiet: disable_progress_bars() try: api.copy_files(src, dst) # type: ignore except ValueError as e: raise typer.BadParameter(str(e)) finally: if quiet: enable_progress_bars()
if not quiet: print(f"Copied: {src} -> {dst}") return
# Local to remote copy # --- Validation --- if not src_is_bucket and not dst_is_bucket and not src_is_stdin: if dst is None: raise typer.BadParameter("Missing destination. Provide a bucket path as DST.") raise typer.BadParameter("One of SRC or DST must be a bucket path (hf://buckets/...).")
if src_is_stdin and not dst_is_bucket: raise typer.BadParameter("Stdin upload requires a bucket destination.")
if src_is_stdin and dst_is_bucket: _, prefix = _parse_bucket_path(dst) # type: ignore if prefix == "" or prefix.endswith("/"): raise typer.BadParameter("Stdin upload requires a full destination path including filename.")
if dst_is_stdout and not src_is_bucket: raise typer.BadParameter("Cannot pipe to stdout for uploads.")
if not src_is_bucket and not src_is_stdin and os.path.isdir(src): raise typer.BadParameter("Source must be a file, not a directory. Use `hf buckets sync` for directories.")
# --- Determine direction and execute --- if src_is_bucket: # Download: remote -> local or stdout bucket_id, prefix = _parse_bucket_path(src) if prefix == "" or prefix.endswith("/"): raise typer.BadParameter("Source path must include a file name, not just a bucket or directory path.") filename = prefix.rsplit("/", 1)[-1]
if dst_is_stdout: # Download to stdout: always suppress progress bars to avoid polluting output # Only re-enable if they weren't already disabled by the caller pbar_was_disabled = are_progress_bars_disabled() if not pbar_was_disabled: disable_progress_bars() try: with SoftTemporaryDirectory() as tmp_dir: tmp_path = os.path.join(tmp_dir, filename) api.download_bucket_files(bucket_id, [(prefix, tmp_path)]) with open(tmp_path, "rb") as f: while chunk := f.read(32_000_000): # 32MB chunks sys.stdout.buffer.write(chunk) finally: if not pbar_was_disabled: enable_progress_bars() else: # Download to file if dst is None: local_path = filename elif os.path.isdir(dst) or dst.endswith(os.sep) or dst.endswith("/"): local_path = os.path.join(dst, filename) else: local_path = dst
# Ensure parent directory exists parent_dir = os.path.dirname(local_path) if parent_dir: os.makedirs(parent_dir, exist_ok=True)
if quiet: disable_progress_bars() try: api.download_bucket_files(bucket_id, [(prefix, local_path)]) finally: if quiet: enable_progress_bars()
if not quiet: print(f"Downloaded: {src} -> {local_path}")
elif src_is_stdin: # Upload from stdin bucket_id, remote_path = _parse_bucket_path(dst) # type: ignore data = sys.stdin.buffer.read()
if quiet: disable_progress_bars() try: api.batch_bucket_files(bucket_id, add=[(data, remote_path)]) finally: if quiet: enable_progress_bars()
if not quiet: print(f"Uploaded: stdin -> {dst}")
else: # Upload from file if not os.path.isfile(src): raise typer.BadParameter(f"Source file not found: {src}")
bucket_id, prefix = _parse_bucket_path(dst) # type: ignore
if prefix == "": remote_path = os.path.basename(src) elif prefix.endswith("/"): remote_path = prefix + os.path.basename(src) else: remote_path = prefix
if quiet: disable_progress_bars() try: api.batch_bucket_files(bucket_id, add=[(src, remote_path)]) finally: if quiet: enable_progress_bars()
if not quiet: print(f"Uploaded: {src} -> {BUCKET_PREFIX}{bucket_id}/{remote_path}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812# Copyright 2025-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains the 'hf cache' command group with cache management subcommands."""
import jsonimport reimport sysimport timefrom collections import defaultdictfrom collections.abc import Callable, Mappingfrom dataclasses import dataclassfrom enum import Enumfrom typing import Annotated, Any
import typer
from huggingface_hub.errors import CLIError
from ..utils import ( ANSI, CachedRepoInfo, CachedRevisionInfo, CacheNotFound, HFCacheInfo, _format_size, scan_cache_dir, tabulate,)from ..utils._parsing import parse_duration, parse_sizefrom ._cli_utils import ( OutputFormat, RepoIdArg, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api, typer_factory,)
cache_cli = typer_factory(help="Manage local cache directory.")
#### Cache helper utilities
@dataclass(frozen=True)class _DeletionResolution: revisions: frozenset[str] selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]] missing: tuple[str, ...]
_FILTER_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)\s*(?P<op>==|!=|>=|<=|>|<|=)\s*(?P<value>.+)$")_ALLOWED_OPERATORS = {"=", "!=", ">", "<", ">=", "<="}_FILTER_KEYS = {"accessed", "modified", "refs", "size", "type"}_SORT_KEYS = {"accessed", "modified", "name", "size"}_SORT_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)(?::(?P<order>asc|desc))?$")_SORT_DEFAULT_ORDER = { # Default ordering: accessed/modified/size are descending (newest/biggest first), name is ascending "accessed": "desc", "modified": "desc", "size": "desc", "name": "asc",}
# Dynamically generate SortOptions enum from _SORT_KEYS_sort_options_dict = {}for key in sorted(_SORT_KEYS): _sort_options_dict[key] = key _sort_options_dict[f"{key}_asc"] = f"{key}:asc" _sort_options_dict[f"{key}_desc"] = f"{key}:desc"
SortOptions = Enum("SortOptions", _sort_options_dict, type=str, module=__name__) # type: ignore
@dataclass(frozen=True)class CacheDeletionCounts: """Simple counters summarizing cache deletions for CLI messaging."""
repo_count: int partial_revision_count: int total_revision_count: int
CacheEntry = tuple[CachedRepoInfo, CachedRevisionInfo | None]RepoRefsMap = dict[CachedRepoInfo, frozenset[str]]
def summarize_deletions( selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]],) -> CacheDeletionCounts: """Summarize deletions across repositories.""" repo_count = 0 total_revisions = 0 revisions_in_full_repos = 0
for repo, revisions in selected_by_repo.items(): total_revisions += len(revisions) if len(revisions) == len(repo.revisions): repo_count += 1 revisions_in_full_repos += len(revisions)
partial_revision_count = total_revisions - revisions_in_full_repos return CacheDeletionCounts(repo_count, partial_revision_count, total_revisions)
def print_cache_selected_revisions(selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]]) -> None: """Pretty-print selected cache revisions during confirmation prompts.""" for repo in sorted(selected_by_repo.keys(), key=lambda repo: (repo.repo_type, repo.repo_id.lower())): repo_key = f"{repo.repo_type}/{repo.repo_id}" revisions = sorted(selected_by_repo[repo], key=lambda rev: rev.commit_hash) if len(revisions) == len(repo.revisions): print(f" - {repo_key} (entire repo)") continue
print(f" - {repo_key}:") for revision in revisions: refs = " ".join(sorted(revision.refs)) or "(detached)" print(f" {revision.commit_hash} [{refs}] {revision.size_on_disk_str}")
def build_cache_index( hf_cache_info: HFCacheInfo,) -> tuple[ dict[str, CachedRepoInfo], dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]],]: """Create lookup tables so CLI commands can resolve repo ids and revisions quickly.""" repo_lookup: dict[str, CachedRepoInfo] = {} revision_lookup: dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]] = {} for repo in hf_cache_info.repos: repo_key = repo.cache_id.lower() repo_lookup[repo_key] = repo for revision in repo.revisions: revision_lookup[revision.commit_hash.lower()] = (repo, revision) return repo_lookup, revision_lookup
def collect_cache_entries( hf_cache_info: HFCacheInfo, *, include_revisions: bool) -> tuple[list[CacheEntry], RepoRefsMap]: """Flatten cache metadata into rows consumed by `hf cache ls`.""" entries: list[CacheEntry] = [] repo_refs_map: RepoRefsMap = {} sorted_repos = sorted(hf_cache_info.repos, key=lambda repo: (repo.repo_type, repo.repo_id.lower())) for repo in sorted_repos: repo_refs_map[repo] = frozenset({ref for revision in repo.revisions for ref in revision.refs}) if include_revisions: for revision in sorted(repo.revisions, key=lambda rev: rev.commit_hash): entries.append((repo, revision)) else: entries.append((repo, None)) if include_revisions: entries.sort( key=lambda entry: ( entry[0].cache_id, entry[1].commit_hash if entry[1] is not None else "", ) ) else: entries.sort(key=lambda entry: entry[0].cache_id) return entries, repo_refs_map
def compile_cache_filter( expr: str, repo_refs_map: RepoRefsMap) -> Callable[[CachedRepoInfo, CachedRevisionInfo | None, float], bool]: """Convert a `hf cache ls` filter expression into the yes/no test we apply to each cache entry before displaying it.""" match = _FILTER_PATTERN.match(expr.strip()) if not match: raise ValueError(f"Invalid filter expression: '{expr}'.")
key = match.group("key").lower() op = match.group("op") value_raw = match.group("value").strip()
if op not in _ALLOWED_OPERATORS: raise ValueError(f"Unsupported operator '{op}' in filter '{expr}'. Must be one of {list(_ALLOWED_OPERATORS)}.")
if key not in _FILTER_KEYS: raise ValueError(f"Unsupported filter key '{key}' in '{expr}'. Must be one of {list(_FILTER_KEYS)}.") # at this point we know that key is in `_FILTER_KEYS` if key == "size": size_threshold = parse_size(value_raw) return lambda repo, revision, _: _compare_numeric( revision.size_on_disk if revision is not None else repo.size_on_disk, op, size_threshold, )
if key in {"modified", "accessed"}: seconds = parse_duration(value_raw.strip())
def _time_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, now: float) -> bool: timestamp = ( repo.last_accessed if key == "accessed" else revision.last_modified if revision is not None else repo.last_modified ) if timestamp is None: return False return _compare_numeric(now - timestamp, op, seconds)
return _time_filter
if key == "type": expected = value_raw.lower()
if op != "=": raise ValueError(f"Only '=' is supported for 'type' filters. Got '{op}'.")
def _type_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool: return repo.repo_type.lower() == expected
return _type_filter
else: # key == "refs" if op != "=": raise ValueError(f"Only '=' is supported for 'refs' filters. Got {op}.")
def _refs_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool: refs = revision.refs if revision is not None else repo_refs_map.get(repo, frozenset()) return value_raw.lower() in [ref.lower() for ref in refs]
return _refs_filter
def _build_cache_export_payload( entries: list[CacheEntry], *, include_revisions: bool, repo_refs_map: RepoRefsMap) -> list[dict[str, Any]]: """Normalize cache entries into serializable records for JSON/CSV exports.""" payload: list[dict[str, Any]] = [] for repo, revision in entries: if include_revisions: if revision is None: continue record: dict[str, Any] = { "repo_id": repo.repo_id, "repo_type": repo.repo_type, "revision": revision.commit_hash, "snapshot_path": str(revision.snapshot_path), "size_on_disk": revision.size_on_disk, "last_accessed": repo.last_accessed, "last_modified": revision.last_modified, "refs": sorted(revision.refs), } else: record = { "repo_id": repo.repo_id, "repo_type": repo.repo_type, "size_on_disk": repo.size_on_disk, "last_accessed": repo.last_accessed, "last_modified": repo.last_modified, "refs": sorted(repo_refs_map.get(repo, frozenset())), } payload.append(record) return payload
def print_cache_entries_table( entries: list[CacheEntry], *, include_revisions: bool, repo_refs_map: RepoRefsMap) -> None: """Render cache entries as a table and show a human-readable summary.""" if not entries: message = "No cached revisions found." if include_revisions else "No cached repositories found." print(message) return table_rows: list[list[str | int]] if include_revisions: headers = ["ID", "REVISION", "SIZE", "LAST_MODIFIED", "REFS"] table_rows = [ [ repo.cache_id, revision.commit_hash, revision.size_on_disk_str.rjust(8), revision.last_modified_str, " ".join(sorted(revision.refs)), ] for repo, revision in entries if revision is not None ] else: headers = ["ID", "SIZE", "LAST_ACCESSED", "LAST_MODIFIED", "REFS"] table_rows = [ [ repo.cache_id, repo.size_on_disk_str.rjust(8), repo.last_accessed_str or "", repo.last_modified_str, " ".join(sorted(repo_refs_map.get(repo, frozenset()))), ] for repo, _ in entries ]
print(tabulate(table_rows, headers=headers))
unique_repos = {repo for repo, _ in entries} repo_count = len(unique_repos) if include_revisions: revision_count = sum(1 for _, revision in entries if revision is not None) total_size = sum(revision.size_on_disk for _, revision in entries if revision is not None) else: revision_count = sum(len(repo.revisions) for repo in unique_repos) total_size = sum(repo.size_on_disk for repo in unique_repos)
summary = f"\nFound {repo_count} repo(s) for a total of {revision_count} revision(s) and {_format_size(total_size)} on disk." print(ANSI.bold(summary))
def print_cache_entries_json( entries: list[CacheEntry], *, include_revisions: bool, repo_refs_map: RepoRefsMap) -> None: """Dump cache entries as JSON for scripting or automation.""" payload = _build_cache_export_payload(entries, include_revisions=include_revisions, repo_refs_map=repo_refs_map) json.dump(payload, sys.stdout, indent=2) sys.stdout.write("\n")
def _compare_numeric(left: float | None, op: str, right: float) -> bool: """Evaluate numeric comparisons for filters.""" if left is None: return False
comparisons = { "=": left == right, "!=": left != right, ">": left > right, "<": left < right, ">=": left >= right, "<=": left <= right, }
if op not in comparisons: raise ValueError(f"Unsupported numeric comparison operator: {op}")
return comparisons[op]
def compile_cache_sort(sort_expr: str) -> tuple[Callable[[CacheEntry], tuple[Any, ...]], bool]: """Convert a `hf cache ls` sort expression into a key function for sorting entries.
Returns: A tuple of (key_function, reverse_flag) where reverse_flag indicates whether to sort in descending order (True) or ascending order (False). """ match = _SORT_PATTERN.match(sort_expr.strip().lower()) if not match: raise ValueError(f"Invalid sort expression: '{sort_expr}'. Expected format: 'key' or 'key:asc' or 'key:desc'.")
key = match.group("key").lower() explicit_order = match.group("order")
if key not in _SORT_KEYS: raise ValueError(f"Unsupported sort key '{key}' in '{sort_expr}'. Must be one of {list(_SORT_KEYS)}.")
# Use explicit order if provided, otherwise use default for the key order = explicit_order if explicit_order else _SORT_DEFAULT_ORDER[key] reverse = order == "desc"
def _sort_key(entry: CacheEntry) -> tuple[Any, ...]: repo, revision = entry
if key == "name": # Sort by cache_id (repo type/id) value: Any = repo.cache_id.lower() return (value,)
if key == "size": # Use revision size if available, otherwise repo size value = revision.size_on_disk if revision is not None else repo.size_on_disk return (value,)
if key == "accessed": # For revisions, accessed is not available per-revision, use repo's last_accessed # For repos, use repo's last_accessed value = repo.last_accessed if repo.last_accessed is not None else 0.0 return (value,)
if key == "modified": # Use revision's last_modified if available, otherwise repo's last_modified if revision is not None: value = revision.last_modified if revision.last_modified is not None else 0.0 else: value = repo.last_modified if repo.last_modified is not None else 0.0 return (value,)
# Should never reach here due to validation above raise ValueError(f"Unsupported sort key: {key}")
return _sort_key, reverse
def _resolve_deletion_targets(hf_cache_info: HFCacheInfo, targets: list[str]) -> _DeletionResolution: """Resolve the deletion targets into a deletion resolution.""" repo_lookup, revision_lookup = build_cache_index(hf_cache_info)
selected: dict[CachedRepoInfo, set[CachedRevisionInfo]] = defaultdict(set) revisions: set[str] = set() missing: list[str] = []
for raw_target in targets: target = raw_target.strip() if not target: continue lowered = target.lower()
if re.fullmatch(r"[0-9a-fA-F]{40}", lowered): match = revision_lookup.get(lowered) if match is None: missing.append(raw_target) continue repo, revision = match selected[repo].add(revision) revisions.add(revision.commit_hash) continue
matched_repo = repo_lookup.get(lowered) if matched_repo is None: missing.append(raw_target) continue
for revision in matched_repo.revisions: selected[matched_repo].add(revision) revisions.add(revision.commit_hash)
frozen_selected = {repo: frozenset(revs) for repo, revs in selected.items()} return _DeletionResolution( revisions=frozenset(revisions), selected=frozen_selected, missing=tuple(missing), )
#### Cache CLI commands
@cache_cli.command( "list | ls", examples=[ "hf cache ls", "hf cache ls --revisions", 'hf cache ls --filter "size>1GB" --limit 20', "hf cache ls --format json", ],)def ls( cache_dir: Annotated[ str | None, typer.Option( help="Cache directory to scan (defaults to Hugging Face cache).", ), ] = None, revisions: Annotated[ bool, typer.Option( help="Include revisions in the output instead of aggregated repositories.", ), ] = False, filter: Annotated[ list[str] | None, typer.Option( "-f", "--filter", help="Filter entries (e.g. 'size>1GB', 'type=model', 'accessed>7d'). Can be used multiple times.", ), ] = None, format: Annotated[ OutputFormat, typer.Option( help="Output format.", ), ] = OutputFormat.table, quiet: Annotated[ bool, typer.Option( "-q", "--quiet", help="Print only IDs (repo IDs or revision hashes).", ), ] = False, sort: Annotated[ SortOptions | None, typer.Option( help="Sort entries by key. Supported keys: 'accessed', 'modified', 'name', 'size'. " "Append ':asc' or ':desc' to explicitly set the order (e.g., 'modified:asc'). " "Defaults: 'accessed', 'modified', 'size' default to 'desc' (newest/biggest first); " "'name' defaults to 'asc' (alphabetical).", ), ] = None, limit: Annotated[ int | None, typer.Option( help="Limit the number of results returned. Returns only the top N entries after sorting.", ), ] = None,) -> None: """List cached repositories or revisions.""" try: hf_cache_info = scan_cache_dir(cache_dir) except CacheNotFound as exc: raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
filters = filter or []
entries, repo_refs_map = collect_cache_entries(hf_cache_info, include_revisions=revisions) try: filter_fns = [compile_cache_filter(expr, repo_refs_map) for expr in filters] except ValueError as exc: raise typer.BadParameter(str(exc)) from exc
now = time.time() for fn in filter_fns: entries = [entry for entry in entries if fn(entry[0], entry[1], now)]
# Apply sorting if requested if sort: try: sort_key_fn, reverse = compile_cache_sort(sort.value) entries.sort(key=sort_key_fn, reverse=reverse) except ValueError as exc: raise typer.BadParameter(str(exc)) from exc
# Apply limit if requested if limit is not None: if limit < 0: raise typer.BadParameter(f"Limit must be a positive integer, got {limit}.") entries = entries[:limit]
if quiet: for repo, revision in entries: print(revision.commit_hash if revision is not None else repo.cache_id) return
formatters = { OutputFormat.table: print_cache_entries_table, OutputFormat.json: print_cache_entries_json, } return formatters[format](entries, include_revisions=revisions, repo_refs_map=repo_refs_map)
@cache_cli.command( examples=[ "hf cache rm model/gpt2", "hf cache rm <revision_hash>", "hf cache rm model/gpt2 --dry-run", "hf cache rm model/gpt2 --yes", ],)def rm( targets: Annotated[ list[str], typer.Argument( help="One or more repo IDs (e.g. model/bert-base-uncased) or revision hashes to delete.", ), ], cache_dir: Annotated[ str | None, typer.Option( help="Cache directory to scan (defaults to Hugging Face cache).", ), ] = None, yes: Annotated[ bool, typer.Option( "-y", "--yes", help="Skip confirmation prompt.", ), ] = False, dry_run: Annotated[ bool, typer.Option( help="Preview deletions without removing anything.", ), ] = False,) -> None: """Remove cached repositories or revisions.""" try: hf_cache_info = scan_cache_dir(cache_dir) except CacheNotFound as exc: raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
resolution = _resolve_deletion_targets(hf_cache_info, targets)
if resolution.missing: print("Could not find the following targets in the cache:") for entry in resolution.missing: print(f" - {entry}")
if len(resolution.revisions) == 0: print("Nothing to delete.") raise typer.Exit(code=0)
strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions)) counts = summarize_deletions(resolution.selected)
summary_parts: list[str] = [] if counts.repo_count: summary_parts.append(f"{counts.repo_count} repo(s)") if counts.partial_revision_count: summary_parts.append(f"{counts.partial_revision_count} revision(s)") if not summary_parts: summary_parts.append(f"{counts.total_revision_count} revision(s)")
summary_text = " and ".join(summary_parts) print(f"About to delete {summary_text} totalling {strategy.expected_freed_size_str}.") print_cache_selected_revisions(resolution.selected)
if dry_run: print("Dry run: no files were deleted.") return
if not yes and not typer.confirm("Proceed with deletion?", default=False): print("Deletion cancelled.") return
strategy.execute() counts = summarize_deletions(resolution.selected) print( f"Deleted {counts.repo_count} repo(s) and {counts.total_revision_count} revision(s); freed {strategy.expected_freed_size_str}." )
@cache_cli.command(examples=["hf cache prune", "hf cache prune --dry-run"])def prune( cache_dir: Annotated[ str | None, typer.Option( help="Cache directory to scan (defaults to Hugging Face cache).", ), ] = None, yes: Annotated[ bool, typer.Option( "-y", "--yes", help="Skip confirmation prompt.", ), ] = False, dry_run: Annotated[ bool, typer.Option( help="Preview deletions without removing anything.", ), ] = False,) -> None: """Remove detached revisions from the cache.""" try: hf_cache_info = scan_cache_dir(cache_dir) except CacheNotFound as exc: raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]] = {} revisions: set[str] = set() for repo in hf_cache_info.repos: detached = frozenset(revision for revision in repo.revisions if len(revision.refs) == 0) if not detached: continue selected[repo] = detached revisions.update(revision.commit_hash for revision in detached)
if len(revisions) == 0: print("No unreferenced revisions found. Nothing to prune.") return
resolution = _DeletionResolution( revisions=frozenset(revisions), selected=selected, missing=(), ) strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions)) counts = summarize_deletions(selected)
print( f"About to delete {counts.total_revision_count} unreferenced revision(s) ({strategy.expected_freed_size_str} total)." ) print_cache_selected_revisions(selected)
if dry_run: print("Dry run: no files were deleted.") return
if not yes and not typer.confirm("Proceed?"): print("Pruning cancelled.") return
strategy.execute() print(f"Deleted {counts.total_revision_count} unreferenced revision(s); freed {strategy.expected_freed_size_str}.")
@cache_cli.command( examples=[ "hf cache verify gpt2", "hf cache verify gpt2 --revision refs/pr/1", "hf cache verify my-dataset --repo-type dataset", ],)def verify( repo_id: RepoIdArg, repo_type: RepoTypeOpt = RepoTypeOpt.model, revision: RevisionOpt = None, cache_dir: Annotated[ str | None, typer.Option( help="Cache directory to use when verifying files from cache (defaults to Hugging Face cache).", ), ] = None, local_dir: Annotated[ str | None, typer.Option( help="If set, verify files under this directory instead of the cache.", ), ] = None, fail_on_missing_files: Annotated[ bool, typer.Option( "--fail-on-missing-files", help="Fail if some files exist on the remote but are missing locally.", ), ] = False, fail_on_extra_files: Annotated[ bool, typer.Option( "--fail-on-extra-files", help="Fail if some files exist locally but are not present on the remote revision.", ), ] = False, token: TokenOpt = None,) -> None: """Verify checksums for a single repo revision from cache or a local directory.
Examples: - Verify main revision in cache: `hf cache verify gpt2` - Verify specific revision: `hf cache verify gpt2 --revision refs/pr/1` - Verify dataset: `hf cache verify karpathy/fineweb-edu-100b-shuffle --repo-type dataset` - Verify local dir: `hf cache verify deepseek-ai/DeepSeek-OCR --local-dir /path/to/repo` """
if local_dir is not None and cache_dir is not None: print("Cannot pass both --local-dir and --cache-dir. Use one or the other.") raise typer.Exit(code=2)
api = get_hf_api(token=token)
result = api.verify_repo_checksums( repo_id=repo_id, repo_type=repo_type.value if hasattr(repo_type, "value") else str(repo_type), revision=revision, local_dir=local_dir, cache_dir=cache_dir, token=token, )
exit_code = 0
has_mismatches = bool(result.mismatches) if has_mismatches: print("❌ Checksum verification failed for the following file(s):") for m in result.mismatches: print(f" - {m['path']}: expected {m['expected']} ({m['algorithm']}), got {m['actual']}") exit_code = 1
if result.missing_paths: if fail_on_missing_files: print("Missing files (present remotely, absent locally):") for p in result.missing_paths: print(f" - {p}") exit_code = 1 else: warning = ( f"{len(result.missing_paths)} remote file(s) are missing locally. " "Use --fail-on-missing-files for details." ) print(f"⚠️ {warning}")
if result.extra_paths: if fail_on_extra_files: print("Extra files (present locally, absent remotely):") for p in result.extra_paths: print(f" - {p}") exit_code = 1 else: warning = ( f"{len(result.extra_paths)} local file(s) do not exist on the remote repo. " "Use --fail-on-extra-files for details." ) print(f"⚠️ {warning}")
verified_location = result.verified_path
if exit_code != 0: print(f"❌ Verification failed for '{repo_id}' ({repo_type.value}) in {verified_location}.") print(f" Revision: {result.revision}") raise typer.Exit(code=exit_code)
print(f"✅ Verified {result.checked_count} file(s) for '{repo_id}' ({repo_type.value}) in {verified_location}") print(" All checksums match.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with collections on the Hugging Face Hub.
Usage: # list collections on the Hub hf collections ls
# list collections for a specific user hf collections ls --owner username
# get info about a collection hf collections info username/collection-slug
# create a new collection hf collections create "My Collection" --description "A collection of models"
# add an item to a collection hf collections add-item username/collection-slug username/model-name model
# delete a collection hf collections delete username/collection-slug"""
import enumimport jsonfrom typing import Annotated, get_args
import typer
from huggingface_hub.hf_api import CollectionItemType_T, CollectionSort_T
from ._cli_utils import ( FormatOpt, LimitOpt, OutputFormat, QuietOpt, TokenOpt, api_object_to_dict, get_hf_api, print_list_output, typer_factory,)
# Build enums dynamically from Literal types to avoid duplication_COLLECTION_ITEM_TYPES = get_args(CollectionItemType_T)CollectionItemType = enum.Enum("CollectionItemType", {t: t for t in _COLLECTION_ITEM_TYPES}, type=str) # type: ignore[misc]
_COLLECTION_SORT_OPTIONS = get_args(CollectionSort_T)CollectionSort = enum.Enum("CollectionSort", {s: s for s in _COLLECTION_SORT_OPTIONS}, type=str) # type: ignore[misc]
collections_cli = typer_factory(help="Interact with collections on the Hub.")
@collections_cli.command( "list | ls", examples=[ "hf collections ls", "hf collections ls --owner nvidia", "hf collections ls --item models/teknium/OpenHermes-2.5-Mistral-7B --limit 10", ],)def collections_ls( owner: Annotated[ str | None, typer.Option(help="Filter by owner username or organization."), ] = None, item: Annotated[ str | None, typer.Option( help='Filter collections containing a specific item (e.g., "models/gpt2", "datasets/squad", "papers/2311.12983").' ), ] = None, sort: Annotated[ CollectionSort | None, typer.Option(help="Sort results by last modified, trending, or upvotes."), ] = None, limit: LimitOpt = 10, format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """List collections on the Hub.""" api = get_hf_api(token=token) sort_key = sort.value if sort else None results = [ api_object_to_dict(collection) for collection in api.list_collections( owner=owner, item=item, sort=sort_key, # type: ignore[arg-type] limit=limit, ) ] print_list_output(results, format=format, quiet=quiet)
@collections_cli.command( "info", examples=[ "hf collections info username/my-collection-slug", ],)def collections_info( collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")], token: TokenOpt = None,) -> None: """Get info about a collection on the Hub. Output is in JSON format.""" api = get_hf_api(token=token) collection = api.get_collection(collection_slug) print(json.dumps(api_object_to_dict(collection), indent=2))
@collections_cli.command( "create", examples=[ 'hf collections create "My Models"', 'hf collections create "My Models" --description "A collection of my favorite models" --private', 'hf collections create "Org Collection" --namespace my-org', ],)def collections_create( title: Annotated[str, typer.Argument(help="The title of the collection.")], namespace: Annotated[ str | None, typer.Option(help="The namespace (username or organization). Defaults to the authenticated user."), ] = None, description: Annotated[ str | None, typer.Option(help="A description for the collection."), ] = None, private: Annotated[ bool, typer.Option(help="Create a private collection."), ] = False, exists_ok: Annotated[ bool, typer.Option(help="Do not raise an error if the collection already exists."), ] = False, token: TokenOpt = None,) -> None: """Create a new collection on the Hub.""" api = get_hf_api(token=token) collection = api.create_collection( title=title, namespace=namespace, description=description, private=private, exists_ok=exists_ok, ) print(f"Collection created: {collection.url}") print(json.dumps(api_object_to_dict(collection), indent=2))
@collections_cli.command( "update", examples=[ 'hf collections update username/my-collection --title "New Title"', 'hf collections update username/my-collection --description "Updated description"', "hf collections update username/my-collection --private --theme green", ],)def collections_update( collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")], title: Annotated[ str | None, typer.Option(help="The new title for the collection."), ] = None, description: Annotated[ str | None, typer.Option(help="The new description for the collection."), ] = None, position: Annotated[ int | None, typer.Option(help="The new position of the collection in the owner's list."), ] = None, private: Annotated[ bool | None, typer.Option(help="Whether the collection should be private."), ] = None, theme: Annotated[ str | None, typer.Option(help="The theme color for the collection (e.g., 'green', 'blue')."), ] = None, token: TokenOpt = None,) -> None: """Update a collection's metadata on the Hub.""" api = get_hf_api(token=token) collection = api.update_collection_metadata( collection_slug=collection_slug, title=title, description=description, position=position, private=private, theme=theme, ) print(f"Collection updated: {collection.url}") print(json.dumps(api_object_to_dict(collection), indent=2))
@collections_cli.command( "delete", examples=[ "hf collections delete username/my-collection", "hf collections delete username/my-collection --missing-ok", ],)def collections_delete( collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")], missing_ok: Annotated[ bool, typer.Option(help="Do not raise an error if the collection doesn't exist."), ] = False, token: TokenOpt = None,) -> None: """Delete a collection from the Hub.""" api = get_hf_api(token=token) api.delete_collection(collection_slug, missing_ok=missing_ok) print(f"Collection deleted: {collection_slug}")
@collections_cli.command( "add-item", examples=[ "hf collections add-item username/my-collection moonshotai/kimi-k2 model", 'hf collections add-item username/my-collection Qwen/DeepPlanning dataset --note "Useful dataset"', "hf collections add-item username/my-collection Tongyi-MAI/Z-Image space", ],)def collections_add_item( collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")], item_id: Annotated[ str, typer.Argument(help="The ID of the item to add (repo_id for repos, paper ID for papers).") ], item_type: Annotated[ CollectionItemType, typer.Argument(help="The type of item (model, dataset, space, paper, collection, or bucket)."), ], note: Annotated[ str | None, typer.Option(help="A note to attach to the item (max 500 characters)."), ] = None, exists_ok: Annotated[ bool, typer.Option(help="Do not raise an error if the item is already in the collection."), ] = False, token: TokenOpt = None,) -> None: """Add an item to a collection.""" api = get_hf_api(token=token) collection = api.add_collection_item( collection_slug=collection_slug, item_id=item_id, item_type=item_type.value, # type: ignore[arg-type] note=note, exists_ok=exists_ok, ) print(f"Item added to collection: {collection_slug}") print(json.dumps(api_object_to_dict(collection), indent=2))
@collections_cli.command( "update-item", examples=[ 'hf collections update-item username/my-collection ITEM_OBJECT_ID --note "Updated note"', "hf collections update-item username/my-collection ITEM_OBJECT_ID --position 0", ],)def collections_update_item( collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")], item_object_id: Annotated[ str, typer.Argument(help="The ID of the item in the collection (from 'item_object_id' field, not the repo_id)."), ], note: Annotated[ str | None, typer.Option(help="A new note for the item (max 500 characters)."), ] = None, position: Annotated[ int | None, typer.Option(help="The new position of the item in the collection."), ] = None, token: TokenOpt = None,) -> None: """Update an item in a collection.""" api = get_hf_api(token=token) api.update_collection_item( collection_slug=collection_slug, item_object_id=item_object_id, note=note, position=position, ) print(f"Item updated in collection: {collection_slug}")
@collections_cli.command("delete-item")def collections_delete_item( collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")], item_object_id: Annotated[ str, typer.Argument( help="The ID of the item in the collection (retrieved from `item_object_id` field returned by 'hf collections info'." ), ], missing_ok: Annotated[ bool, typer.Option(help="Do not raise an error if the item doesn't exist."), ] = False, token: TokenOpt = None,) -> None: """Delete an item from a collection.""" api = get_hf_api(token=token) api.delete_collection_item( collection_slug=collection_slug, item_object_id=item_object_id, missing_ok=missing_ok, ) print(f"Item deleted from collection: {collection_slug}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with datasets on the Hugging Face Hub.
Usage: # list datasets on the Hub hf datasets ls
# list datasets with a search query hf datasets ls --search "code"
# get info about a dataset hf datasets info HuggingFaceFW/fineweb"""
import enumfrom typing import Annotated, get_args
import typer
from huggingface_hub._dataset_viewer import execute_raw_sql_queryfrom huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundErrorfrom huggingface_hub.hf_api import DatasetSort_T, ExpandDatasetProperty_T
from ._cli_utils import ( AuthorOpt, FilterOpt, FormatWithAutoOpt, LimitOpt, RevisionOpt, SearchOpt, TokenOpt, api_object_to_dict, get_hf_api, make_expand_properties_parser, typer_factory,)from ._output import OutputFormatWithAuto, out
_EXPAND_PROPERTIES = sorted(get_args(ExpandDatasetProperty_T))_SORT_OPTIONS = get_args(DatasetSort_T)DatasetSortEnum = enum.Enum("DatasetSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
ExpandOpt = Annotated[ str | None, typer.Option( help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=downloads,likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.", callback=make_expand_properties_parser(_EXPAND_PROPERTIES), ),]
datasets_cli = typer_factory(help="Interact with datasets on the Hub.")
@datasets_cli.command( "list | ls", examples=[ "hf datasets ls", "hf datasets ls --sort downloads --limit 10", 'hf datasets ls --search "code"', ],)def datasets_ls( search: SearchOpt = None, author: AuthorOpt = None, filter: FilterOpt = None, sort: Annotated[ DatasetSortEnum | None, typer.Option(help="Sort results."), ] = None, limit: LimitOpt = 10, expand: ExpandOpt = None, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """List datasets on the Hub.""" api = get_hf_api(token=token) sort_key = sort.value if sort else None results = [ api_object_to_dict(dataset_info) for dataset_info in api.list_datasets( filter=filter, author=author, search=search, sort=sort_key, limit=limit, expand=expand, # type: ignore ) ] out.table(results)
@datasets_cli.command( "info", examples=[ "hf datasets info HuggingFaceFW/fineweb", "hf datasets info my-dataset --expand downloads,likes,tags", ],)def datasets_info( dataset_id: Annotated[str, typer.Argument(help="The dataset ID (e.g. `username/repo-name`).")], revision: RevisionOpt = None, expand: ExpandOpt = None, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """Get info about a dataset on the Hub.""" api = get_hf_api(token=token) try: info = api.dataset_info(repo_id=dataset_id, revision=revision, expand=expand) # type: ignore except RepositoryNotFoundError as e: raise CLIError(f"Dataset '{dataset_id}' not found.") from e except RevisionNotFoundError as e: raise CLIError(f"Revision '{revision}' not found on '{dataset_id}'.") from e out.dict(info)
@datasets_cli.command( "parquet", examples=[ "hf datasets parquet cfahlgren1/hub-stats", "hf datasets parquet cfahlgren1/hub-stats --subset models", "hf datasets parquet cfahlgren1/hub-stats --split train", "hf datasets parquet cfahlgren1/hub-stats --format json", ],)def datasets_parquet( dataset_id: Annotated[str, typer.Argument(help="The dataset ID (e.g. `username/repo-name`).")], subset: Annotated[str | None, typer.Option("--subset", help="Filter parquet entries by subset/config.")] = None, split: Annotated[str | None, typer.Option(help="Filter parquet entries by split.")] = None, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """List parquet file URLs available for a dataset.""" api = get_hf_api(token=token) entries = api.list_dataset_parquet_files(repo_id=dataset_id, config=subset) filtered = [entry for entry in entries if split is None or entry.split == split] results = [ {"subset": entry.config, "split": entry.split, "url": entry.url, "size": entry.size} for entry in filtered ] out.table(results, headers=["subset", "split", "url", "size"], id_key="url")
@datasets_cli.command( "sql", examples=[ "hf datasets sql \"SELECT COUNT(*) AS rows FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet')\"", "hf datasets sql \"SELECT * FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet') LIMIT 5\" --format json", ],)def datasets_sql( sql: Annotated[str, typer.Argument(help="Raw SQL query to execute.")], format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """Execute a raw SQL query with DuckDB against dataset parquet URLs.""" try: result = execute_raw_sql_query(sql_query=sql, token=token) except ImportError as e: raise CLIError(str(e)) from e out.table(result)1234567891011121314151617181920212223242526272829303132333435"""Deprecated `huggingface-cli` entry point. Warns and exits."""
import shutilimport sys
from ._output import out
def main() -> None: out.warning("`huggingface-cli` is deprecated and no longer works. Use `hf` instead.\n")
if shutil.which("hf"): from huggingface_hub.cli._cli_utils import check_cli_update
check_cli_update("huggingface_hub") out.hint("`hf` is already installed! Use it directly.\n") else: out.hint( "Install `hf`:\n" " Standalone (recommended): curl -LsSf https://hf.co/cli/install.sh | bash\n" " Using Homebrew: brew install hf\n" " Using pip: pip install huggingface_hub\n", )
out.hint( "Examples:\n" " hf auth login\n" " hf download unsloth/gemma-4-31B-it-GGUF\n" " hf upload my-cool-model . .\n" ' hf models ls --search "gemma"\n' " hf repos ls --format json\n" " hf jobs run python:3.12 python -c 'print(\"Hello!\")'\n" " hf --help\n", ) sys.exit(1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with discussions and pull requests on the Hugging Face Hub."""
import enumimport jsonimport sysfrom pathlib import Pathfrom typing import Annotated
import typer
from huggingface_hub import constantsfrom huggingface_hub.community import DiscussionComment, DiscussionWithDetailsfrom huggingface_hub.utils import ANSI
from ._cli_utils import ( AuthorOpt, FormatOpt, LimitOpt, OutputFormat, QuietOpt, RepoIdArg, RepoType, RepoTypeOpt, TokenOpt, _format_cell, api_object_to_dict, get_hf_api, print_list_output, typer_factory,)
class DiscussionStatus(str, enum.Enum): open = "open" closed = "closed" merged = "merged" draft = "draft" all = "all"
class DiscussionKind(str, enum.Enum): all = "all" discussion = "discussion" pull_request = "pull_request"
class InfoFormat(str, enum.Enum): """Output format for the info command."""
text = "text" json = "json"
# "merged" and "draft" are valid Discussion statuses but the Hub API filter# (DiscussionStatusFilter) only accepts "all", "open", "closed". When the user# asks for merged/draft we fetch with api_status=None (i.e. all) and filter# client-side._CLIENT_SIDE_STATUSES = {"merged", "draft"}
DiscussionNumArg = Annotated[ int, typer.Argument( help="The discussion or pull request number.", min=1, ),]
def _format_status(status: str) -> str: match status: case "open": return ANSI.green("open") case "closed": return ANSI.red("closed") case "merged": return ANSI.blue("merged") case "draft": return ANSI.yellow("draft") case _: return status
def _read_body(body: str | None, body_file: Path | None) -> str | None: """Resolve body text from --body or --body-file (supports '-' for stdin).""" if body is not None and body_file is not None: raise typer.BadParameter("Cannot use both --body and --body-file.") if body_file is not None: if str(body_file) == "-": return sys.stdin.read() return body_file.read_text(encoding="utf-8") return body
def _print_discussion_info(details: DiscussionWithDetails, show_comments: bool = False) -> None: kind = "Pull Request" if details.is_pull_request else "Discussion"
print(f"{ANSI.bold(details.title)} {ANSI.gray(f'#{details.num}')}") parts = [_format_status(details.status), details.author, details.created_at.strftime("%Y-%m-%d %H:%M")] if details.is_pull_request and details.target_branch: parts.append(f"into {ANSI.bold(details.target_branch)}") print(f"{kind}: {' · '.join(parts)}")
if details.is_pull_request and details.conflicting_files: if details.conflicting_files is True: print(ANSI.yellow("Has conflicting files")) else: print(ANSI.yellow(f"Conflicting files: {', '.join(details.conflicting_files)}"))
body = None comments = [] for event in details.events: if isinstance(event, DiscussionComment) and not event.hidden: if body is None: body = event else: comments.append(event)
if body and body.content.strip(): print() print(body.content.strip())
if show_comments and comments: print() print(ANSI.gray("─" * 60)) for comment in comments: print() print(f"{ANSI.bold(comment.author)} · {comment.created_at.strftime('%Y-%m-%d %H:%M')}") print(comment.content.strip()) elif comments: print() print(ANSI.gray(f"{len(comments)} comment{'s' if len(comments) != 1 else ''} (use --comments to show)"))
print() print(f"View on Hub: {ANSI.blue(details.url)}")
discussions_cli = typer_factory(help="Manage discussions and pull requests on the Hub.")
@discussions_cli.command( "list | ls", examples=[ "hf discussions list username/my-model", "hf discussions list username/my-model --kind pull_request --status merged", "hf discussions list username/my-dataset --type dataset --status closed", "hf discussions list username/my-model --author alice --format json", ],)def discussion_list( repo_id: RepoIdArg, status: Annotated[ DiscussionStatus, typer.Option( "-s", "--status", help="Filter by status (open, closed, merged, draft, all).", ), ] = DiscussionStatus.open, kind: Annotated[ DiscussionKind, typer.Option( "-k", "--kind", help="Filter by kind (discussion, pull_request, all).", ), ] = DiscussionKind.all, author: AuthorOpt = None, limit: LimitOpt = 30, repo_type: RepoTypeOpt = RepoType.model, format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """List discussions and pull requests on a repo.""" api = get_hf_api(token=token)
api_status: constants.DiscussionStatusFilter | None if status == DiscussionStatus.open: api_status = "open" elif status == DiscussionStatus.closed: api_status = "closed" else: api_status = None
api_discussion_type: constants.DiscussionTypeFilter | None if kind == DiscussionKind.all: api_discussion_type = None else: api_discussion_type = kind.value # type: ignore[assignment]
discussions = [] for d in api.get_repo_discussions( repo_id=repo_id, author=author, discussion_type=api_discussion_type, discussion_status=api_status, repo_type=repo_type.value, ): if status.value in _CLIENT_SIDE_STATUSES and d.status != status.value: continue discussions.append(d) if len(discussions) >= limit: break
items = [api_object_to_dict(d) for d in discussions]
print_list_output( items, format=format, quiet=quiet, id_key="num", headers=["num", "title", "is_pull_request", "status", "author", "created_at"], row_fn=lambda item: [ f"#{item['num']}", _format_cell(item.get("title", ""), max_len=50), "PR" if item.get("is_pull_request") else "", _format_status(str(item.get("status", ""))), str(item.get("author", "")), _format_cell(item.get("created_at", "")), ], alignments={"num": "right"}, )
@discussions_cli.command( "info", examples=[ "hf discussions info username/my-model 5", "hf discussions info username/my-model 5 --comments", "hf discussions info username/my-model 5 --diff", "hf discussions info username/my-model 5 --format json", ],)def discussion_info( repo_id: RepoIdArg, num: DiscussionNumArg, comments: Annotated[ bool, typer.Option( "--comments", help="Show all comments.", ), ] = False, diff: Annotated[ bool, typer.Option( "--diff", help="Show the diff (for pull requests).", ), ] = False, no_color: Annotated[ bool, typer.Option( "--no-color", help="Disable colored output.", ), ] = False, repo_type: RepoTypeOpt = RepoType.model, format: Annotated[ InfoFormat, typer.Option( help="Output format (text or json).", ), ] = InfoFormat.text, token: TokenOpt = None,) -> None: """Get info about a discussion or pull request.""" import os
if no_color: os.environ["NO_COLOR"] = "1"
api = get_hf_api(token=token) details = api.get_discussion_details( repo_id=repo_id, discussion_num=num, repo_type=repo_type.value, )
if format == InfoFormat.json: result = api_object_to_dict(details) if not diff: result.pop("diff", None) print(json.dumps(result, indent=2)) return
_print_discussion_info(details, show_comments=comments)
if diff and details.diff: print() print(ANSI.gray("─" * 60)) print(details.diff)
@discussions_cli.command( "create", examples=[ 'hf discussions create username/my-model --title "Bug report"', 'hf discussions create username/my-model --title "Feature request" --body "Please add X"', 'hf discussions create username/my-model --title "Fix typo" --pull-request', 'hf discussions create username/my-dataset --type dataset --title "Data quality issue"', ],)def discussion_create( repo_id: RepoIdArg, title: Annotated[ str, typer.Option( "--title", help="The title of the discussion or pull request.", ), ], body: Annotated[ str | None, typer.Option( "--body", help="The description (supports Markdown).", ), ] = None, body_file: Annotated[ Path | None, typer.Option( "--body-file", help="Read the description from a file. Use '-' for stdin.", ), ] = None, pull_request: Annotated[ bool, typer.Option( "--pull-request", "--pr", help="Create a pull request instead of a discussion.", ), ] = False, repo_type: RepoTypeOpt = RepoType.model, token: TokenOpt = None,) -> None: """Create a new discussion or pull request on a repo.""" description = _read_body(body, body_file) api = get_hf_api(token=token) discussion = api.create_discussion( repo_id=repo_id, title=title, description=description, repo_type=repo_type.value, pull_request=pull_request, ) kind = "pull request" if pull_request else "discussion" print(f"Created {kind} {ANSI.bold(f'#{discussion.num}')} on {ANSI.bold(repo_id)}") if pull_request: print(f"Push changes to: {ANSI.bold(f'refs/pr/{discussion.num}')}") print(f"View on Hub: {ANSI.blue(discussion.url)}")
@discussions_cli.command( "comment", examples=[ 'hf discussions comment username/my-model 5 --body "Thanks for reporting!"', 'hf discussions comment username/my-model 5 --body "LGTM!"', ],)def discussion_comment( repo_id: RepoIdArg, num: DiscussionNumArg, body: Annotated[ str | None, typer.Option( "--body", help="The comment text (supports Markdown).", ), ] = None, body_file: Annotated[ Path | None, typer.Option( "--body-file", help="Read the comment from a file. Use '-' for stdin.", ), ] = None, repo_type: RepoTypeOpt = RepoType.model, token: TokenOpt = None,) -> None: """Comment on a discussion or pull request.""" comment = _read_body(body, body_file) if comment is None: raise typer.BadParameter("Either --body or --body-file is required.") api = get_hf_api(token=token) api.comment_discussion( repo_id=repo_id, discussion_num=num, comment=comment, repo_type=repo_type.value, ) print(f"Commented on #{num} in {ANSI.bold(repo_id)}")
@discussions_cli.command( "close", examples=[ "hf discussions close username/my-model 5", 'hf discussions close username/my-model 5 --comment "Closing as resolved."', ],)def discussion_close( repo_id: RepoIdArg, num: DiscussionNumArg, comment: Annotated[ str | None, typer.Option( "--comment", help="An optional comment to post when closing.", ), ] = None, yes: Annotated[ bool, typer.Option( "--yes", "-y", help="Skip confirmation prompt.", ), ] = False, repo_type: RepoTypeOpt = RepoType.model, token: TokenOpt = None,) -> None: """Close a discussion or pull request.""" if not yes: confirm = typer.confirm(f"Close #{num} on '{repo_id}'?") if not confirm: print("Aborted.") raise typer.Exit() api = get_hf_api(token=token) api.change_discussion_status( repo_id=repo_id, discussion_num=num, new_status="closed", comment=comment, repo_type=repo_type.value, ) print(f"Closed #{num} in {ANSI.bold(repo_id)}")
@discussions_cli.command( "reopen", examples=[ "hf discussions reopen username/my-model 5", 'hf discussions reopen username/my-model 5 --comment "Reopening for further investigation."', ],)def discussion_reopen( repo_id: RepoIdArg, num: DiscussionNumArg, comment: Annotated[ str | None, typer.Option( "--comment", help="An optional comment to post when reopening.", ), ] = None, yes: Annotated[ bool, typer.Option( "--yes", "-y", help="Skip confirmation prompt.", ), ] = False, repo_type: RepoTypeOpt = RepoType.model, token: TokenOpt = None,) -> None: """Reopen a closed discussion or pull request.""" if not yes: confirm = typer.confirm(f"Reopen #{num} on '{repo_id}'?") if not confirm: print("Aborted.") raise typer.Exit() api = get_hf_api(token=token) api.change_discussion_status( repo_id=repo_id, discussion_num=num, new_status="open", comment=comment, repo_type=repo_type.value, ) print(f"Reopened #{num} in {ANSI.bold(repo_id)}")
@discussions_cli.command( "rename", examples=[ 'hf discussions rename username/my-model 5 "Updated title"', ],)def discussion_rename( repo_id: RepoIdArg, num: DiscussionNumArg, new_title: Annotated[ str, typer.Argument( help="The new title.", ), ], repo_type: RepoTypeOpt = RepoType.model, token: TokenOpt = None,) -> None: """Rename a discussion or pull request.""" api = get_hf_api(token=token) api.rename_discussion( repo_id=repo_id, discussion_num=num, new_title=new_title, repo_type=repo_type.value, ) print(f"Renamed #{num} to {ANSI.bold(new_title)} in {ANSI.bold(repo_id)}")
@discussions_cli.command( "merge", examples=[ "hf discussions merge username/my-model 5", 'hf discussions merge username/my-model 5 --comment "Merging, thanks!"', ],)def discussion_merge( repo_id: RepoIdArg, num: DiscussionNumArg, comment: Annotated[ str | None, typer.Option( "--comment", help="An optional comment to post when merging.", ), ] = None, yes: Annotated[ bool, typer.Option( "--yes", "-y", help="Skip confirmation prompt.", ), ] = False, repo_type: RepoTypeOpt = RepoType.model, token: TokenOpt = None,) -> None: """Merge a pull request.""" if not yes: confirm = typer.confirm(f"Merge #{num} on '{repo_id}'?") if not confirm: print("Aborted.") raise typer.Exit() api = get_hf_api(token=token) api.merge_pull_request( repo_id=repo_id, discussion_num=num, comment=comment, repo_type=repo_type.value, ) print(f"Merged #{num} in {ANSI.bold(repo_id)}")
@discussions_cli.command( "diff", examples=[ "hf discussions diff username/my-model 5", ],)def discussion_diff( repo_id: RepoIdArg, num: DiscussionNumArg, repo_type: RepoTypeOpt = RepoType.model, token: TokenOpt = None,) -> None: """Show the diff of a pull request.""" api = get_hf_api(token=token) details = api.get_discussion_details( repo_id=repo_id, discussion_num=num, repo_type=repo_type.value, ) if details.diff: print(details.diff) else: print("No diff available.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224# Copyright 202-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains command to download files from the Hub with the CLI.
Usage: hf download --help
# Download file hf download gpt2 config.json
# Download entire repo hf download fffiloni/zeroscope --repo-type=space --revision=refs/pr/78
# Download repo with filters hf download gpt2 --include="*.safetensors"
# Download with token hf download Wauplin/private-model --token=hf_***
# Download quietly (no progress bar, no warnings, only the returned path) hf download gpt2 config.json --quiet
# Download to local dir hf download gpt2 --local-dir=./models/gpt2
# Download a subfolder hf download HuggingFaceM4/FineVision art/ --repo-type=dataset"""
import warningsfrom typing import Annotated
import typer
from huggingface_hub import loggingfrom huggingface_hub._snapshot_download import snapshot_downloadfrom huggingface_hub.errors import CLIErrorfrom huggingface_hub.file_download import DryRunFileInfo, hf_hub_downloadfrom huggingface_hub.utils import _format_size, disable_progress_bars, enable_progress_bars, tabulate
from ._cli_utils import RepoIdArg, RepoTypeOpt, RevisionOpt, TokenOpt
DOWNLOAD_EXAMPLES = [ "hf download meta-llama/Llama-3.2-1B-Instruct", "hf download meta-llama/Llama-3.2-1B-Instruct config.json tokenizer.json", 'hf download meta-llama/Llama-3.2-1B-Instruct --include "*.safetensors" --exclude "*.bin"', "hf download meta-llama/Llama-3.2-1B-Instruct --local-dir ./models/llama", "hf download HuggingFaceM4/FineVision art/ --repo-type dataset",]
logger = logging.get_logger(__name__)
def download( repo_id: RepoIdArg, filenames: Annotated[ list[str] | None, typer.Argument( help="Files to download (e.g. `config.json`, `data/metadata.jsonl`).", ), ] = None, repo_type: RepoTypeOpt = RepoTypeOpt.model, revision: RevisionOpt = None, include: Annotated[ list[str] | None, typer.Option( help="Glob patterns to include from files to download. eg: *.json", ), ] = None, exclude: Annotated[ list[str] | None, typer.Option( help="Glob patterns to exclude from files to download.", ), ] = None, cache_dir: Annotated[ str | None, typer.Option( help="Directory where to save files.", ), ] = None, local_dir: Annotated[ str | None, typer.Option( help="If set, the downloaded file will be placed under this directory. Check out https://huggingface.co/docs/huggingface_hub/guides/download#download-files-to-a-local-folder for more details.", ), ] = None, force_download: Annotated[ bool, typer.Option( help="If True, the files will be downloaded even if they are already cached.", ), ] = False, dry_run: Annotated[ bool, typer.Option( help="If True, perform a dry run without actually downloading the file.", ), ] = False, token: TokenOpt = None, quiet: Annotated[ bool, typer.Option( help="If True, progress bars are disabled and only the path to the download files is printed.", ), ] = False, max_workers: Annotated[ int, typer.Option( help="Maximum number of workers to use for downloading files. Default is 8.", ), ] = 8,) -> None: """Download files from the Hub."""
def run_download() -> str | DryRunFileInfo | list[DryRunFileInfo]: filenames_list = filenames if filenames is not None else []
# Separate subfolder patterns (ending with '/') from regular filenames # Subfolders like "art/" are converted to include patterns like "art/**" subfolders = [f for f in filenames_list if f.endswith("/")] subfolder_patterns = [f"{f.rstrip('/')}/**" for f in subfolders] regular_filenames = [f for f in filenames_list if not f.endswith("/")]
# Error if subfolder patterns are combined with --include/--exclude # Guide user to use --include instead of subfolder argument if len(subfolder_patterns) > 0: if include is not None and len(include) > 0: raise CLIError( f"Cannot combine subfolder argument ('{subfolders[0]}') with `--include`. " f'Please use `--include "{subfolders[0]}*"` instead.' ) if exclude is not None and len(exclude) > 0: raise CLIError( f"Cannot combine subfolder argument ('{subfolders[0]}') with `--exclude`. " f'Please use `--include "{subfolders[0]}*"` with `--exclude` instead.' )
# Warn user if patterns are ignored (only if regular filenames are provided) if len(regular_filenames) > 0: if include is not None and len(include) > 0: warnings.warn("Ignoring `--include` since filenames have being explicitly set.") if exclude is not None and len(exclude) > 0: warnings.warn("Ignoring `--exclude` since filenames have being explicitly set.")
# Single file to download (not a subfolder): use `hf_hub_download` if len(regular_filenames) == 1 and len(subfolder_patterns) == 0: return hf_hub_download( repo_id=repo_id, repo_type=repo_type.value, revision=revision, filename=regular_filenames[0], cache_dir=cache_dir, force_download=force_download, token=token, local_dir=local_dir, library_name="huggingface-cli", dry_run=dry_run, )
# Otherwise: use `snapshot_download` to ensure all files comes from same revision if len(regular_filenames) == 0 and len(subfolder_patterns) == 0: # No filenames provided: use include/exclude patterns allow_patterns = include ignore_patterns = exclude else: # Combine regular filenames and subfolder patterns as allow_patterns allow_patterns = regular_filenames + subfolder_patterns ignore_patterns = None
return snapshot_download( repo_id=repo_id, repo_type=repo_type.value, revision=revision, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, force_download=force_download, cache_dir=cache_dir, token=token, local_dir=local_dir, library_name="huggingface-cli", max_workers=max_workers, dry_run=dry_run, )
def _print_result(result: str | DryRunFileInfo | list[DryRunFileInfo]) -> None: if isinstance(result, str): print(result) return
# Print dry run info if isinstance(result, DryRunFileInfo): result = [result] print( f"[dry-run] Will download {len([r for r in result if r.will_download])} files (out of {len(result)}) totalling {_format_size(sum(r.file_size for r in result if r.will_download))}." ) columns = ["File", "Bytes to download"] items: list[list[str | int]] = [] for info in sorted(result, key=lambda x: x.filename): items.append([info.filename, _format_size(info.file_size) if info.will_download else "-"]) print(tabulate(items, headers=columns))
if quiet: disable_progress_bars() with warnings.catch_warnings(): warnings.simplefilter("ignore") _print_result(run_download()) enable_progress_bars() else: _print_result(run_download()) logging.set_verbosity_warning()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains helper utilities for hf CLI extensions."""
import errnoimport jsonimport osimport reimport shutilimport subprocessimport venvfrom dataclasses import asdict, dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Annotated, Literal
import typer
from huggingface_hub.errors import CLIError, CLIExtensionInstallErrorfrom huggingface_hub.utils import StatusLine, get_session, logging
from ._cli_utils import FormatOpt, OutputFormat, QuietOpt, print_list_output, typer_factory
DEFAULT_EXTENSION_OWNER = "huggingface"EXTENSIONS_ROOT = Path("~/.local/share/hf/extensions")MANIFEST_FILENAME = "manifest.json"EXTENSIONS_HELP = ( "Manage hf CLI extensions.\n\n" "Security Warning: extensions are third-party executables or Python packages. " "Install only from sources you trust.")extensions_cli = typer_factory(help=EXTENSIONS_HELP)_EXTENSIONS_DEFAULT_BRANCH = "main" # Fallback when the GitHub API is unreachable._EXTENSIONS_GITHUB_TOPIC = "hf-extension"_EXTENSIONS_DOWNLOAD_TIMEOUT = 10_EXTENSIONS_PIP_INSTALL_TIMEOUT = 300
logger = logging.get_logger(__name__)
@dataclassclass ExtensionManifest: owner: str repo: str repo_id: str short_name: str executable_name: str executable_path: str type: Literal["binary", "python"] installed_at: datetime source: str description: str | None = None
@classmethod def load(cls, path: Path) -> "ExtensionManifest": manifest_path = path / MANIFEST_FILENAME if not manifest_path.is_file(): raise CLIError(f"Manifest file not found at {manifest_path}. Your extension may be corrupted.") data = json.loads(manifest_path.read_text()) data["installed_at"] = datetime.fromisoformat(data["installed_at"]) return ExtensionManifest(**data)
def save(self, path: Path) -> None: manifest_path = path / MANIFEST_FILENAME manifest_path.parent.mkdir(parents=True, exist_ok=True) data = asdict(self) data["installed_at"] = self.installed_at.isoformat() manifest_path.write_text(json.dumps(data, indent=2, sort_keys=True))
@extensions_cli.command( "install", examples=[ "hf extensions install hf-claude", "hf extensions install hanouticelina/hf-claude", "hf extensions install alvarobartt/hf-mem", ],)def extension_install( ctx: typer.Context, repo_id: Annotated[ str, typer.Argument(help="GitHub extension repository in `[OWNER/]hf-<name>` format."), ], force: Annotated[bool, typer.Option("--force", help="Overwrite if already installed.")] = False,) -> None: """Install an extension from a public GitHub repository.
Security warning: this installs a third-party executable or Python package. Install only from sources you trust. """ owner, repo_name, short_name = _normalize_repo_id(repo_id) root_ctx = ctx.find_root() reserved_commands = set(getattr(root_ctx.command, "commands", {}).keys()) if short_name in reserved_commands: raise CLIError( f"Cannot install extension '{short_name}' because it conflicts with an existing `hf {short_name}` command." )
extension_dir = _get_extension_dir(short_name) extension_exists = extension_dir.exists() if extension_exists and not force: raise CLIError(f"Extension '{short_name}' is already installed. Use --force to overwrite.")
branch, description = _resolve_github_repo_info(owner=owner, repo_name=repo_name)
if extension_exists: shutil.rmtree(extension_dir)
manifest = _install_extension_from_github( owner=owner, repo_name=repo_name, short_name=short_name, extension_dir=extension_dir, branch=branch, description=description, ) ext_type = manifest.type.capitalize() print(f"{ext_type} extension installed successfully from {owner}/{repo_name}.") print(f"Run it with: hf {short_name}")
@extensions_cli.command( "exec", context_settings={"allow_extra_args": True, "allow_interspersed_args": False, "ignore_unknown_options": True}, examples=[ "hf extensions exec claude -- --help", "hf extensions exec claude --model zai-org/GLM-5", ],)def extension_exec( ctx: typer.Context, name: Annotated[ str, typer.Argument(help="Extension name (with or without `hf-` prefix)."), ],) -> None: """Execute an installed extension.""" short_name = _normalize_extension_name(name) executable_path = _resolve_installed_executable_path(short_name)
if not executable_path.is_file(): raise CLIError(f"Extension '{short_name}' is not installed.")
exit_code = _execute_extension_binary(executable_path=executable_path, args=list(ctx.args)) raise typer.Exit(code=exit_code)
@extensions_cli.command("list | ls", examples=["hf extensions list"])def extension_list(format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False) -> None: """List installed extension commands.""" rows = [ { "command": f"hf {manifest.short_name}", "source": str(manifest.repo_id), "type": str(manifest.type), "installed": manifest.installed_at.strftime("%Y-%m-%d"), "description": manifest.description, } for manifest in _list_installed_extensions() ] print_list_output(rows, format=format, quiet=quiet, id_key="command")
@extensions_cli.command("search", examples=["hf extensions search"])def extension_search(format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False) -> None: """Search extensions available on GitHub (tagged with 'hf-extension' topic).""" response = get_session().get( "https://api.github.com/search/repositories", params={"q": f"topic:{_EXTENSIONS_GITHUB_TOPIC}", "sort": "stars", "order": "desc", "per_page": 100}, follow_redirects=True, timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT, ) response.raise_for_status() data = response.json()
installed = {m.short_name for m in _list_installed_extensions()}
rows = [] for repo in data.get("items", []): repo_name = repo["name"] short_name = repo_name[3:] if repo_name.startswith("hf-") else repo_name rows.append( { "name": short_name, "repo": repo["full_name"], "stars": repo.get("stargazers_count", 0), "description": repo.get("description") or "", "installed": "yes" if short_name in installed else "", } )
print_list_output(rows, format=format, quiet=quiet, id_key="repo", alignments={"stars": "right"})
@extensions_cli.command("remove | rm", examples=["hf extensions remove claude"])def extension_remove( name: Annotated[ str, typer.Argument(help="Extension name to remove (with or without `hf-` prefix)."), ],) -> None: """Remove an installed extension.""" short_name = _normalize_extension_name(name) extension_dir = _get_extension_dir(short_name)
if not extension_dir.is_dir(): raise CLIError(f"Extension '{short_name}' is not installed.")
shutil.rmtree(extension_dir) print(f"Removed extension '{short_name}'.")
### HELPER FUNCTIONS
def _list_installed_extensions() -> list[ExtensionManifest]: """Return manifests for all validly-installed extensions, sorted by directory name.""" root_dir = EXTENSIONS_ROOT.expanduser() if not root_dir.is_dir(): return [] manifests = [] for extension_dir in sorted(root_dir.iterdir()): if not extension_dir.is_dir() or not extension_dir.name.startswith("hf-"): continue try: manifests.append(ExtensionManifest.load(extension_dir)) except Exception as e: logger.debug(f"Failed to load manifest for extension '{extension_dir.name}': {e}") continue return manifests
def list_installed_extensions_for_help() -> list[tuple[str, str]]: entries = [] for manifest in _list_installed_extensions(): tag = f"[extension {manifest.repo_id}]" help_text = f"{manifest.description} {tag}" if manifest.description is not None else tag entries.append((manifest.short_name, help_text)) return entries
def dispatch_unknown_top_level_extension(args: list[str], known_commands: set[str]) -> int | None: if not args: return None
command_name = args[0] if command_name.startswith("-"): return None all_known = {a.strip() for cmd in known_commands for a in cmd.split("|")} if command_name in all_known: return None
short_name = command_name[3:] if command_name.startswith("hf-") else command_name if not short_name: return None
executable_path: Path | None = None try: executable_path = _resolve_installed_executable_path(short_name) except Exception: executable_path = _auto_install_official_extension(short_name)
if executable_path is None or not executable_path.is_file(): return None
return _execute_extension_binary(executable_path=executable_path, args=list(args[1:]))
def _auto_install_official_extension(short_name: str) -> Path | None: """Try to auto-install huggingface/hf-<name>. Returns executable path or None.""" owner, repo_name = DEFAULT_EXTENSION_OWNER, f"hf-{short_name}" try: extension_dir = _get_extension_dir(short_name) except Exception: return None if extension_dir.exists(): return None try: response = get_session().get( f"https://api.github.com/repos/{owner}/{repo_name}", follow_redirects=True, timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT, ) if response.status_code == 404: return None response.raise_for_status() branch = response.json()["default_branch"] except Exception: return None if not typer.confirm(f"'{short_name}' is an official Hugging Face extension ({owner}/{repo_name}). Install it?"): return None try: manifest = _install_extension_from_github( owner=owner, repo_name=repo_name, short_name=short_name, extension_dir=extension_dir, branch=branch ) return Path(manifest.executable_path).expanduser() except Exception: shutil.rmtree(extension_dir, ignore_errors=True) return None
def _install_extension_from_github( *, owner: str, repo_name: str, short_name: str, extension_dir: Path, branch: str, description: str | None = None,) -> ExtensionManifest: """Fetch, install (binary or Python), and save manifest for a GitHub extension.""" try: binary = _fetch_remote_binary(owner=owner, repo_name=repo_name, branch=branch, short_name=short_name) except Exception: binary = None if binary is not None: manifest = _install_binary_extension( owner=owner, repo_name=repo_name, short_name=short_name, extension_dir=extension_dir, binary=binary ) else: manifest = _install_python_extension( owner=owner, repo_name=repo_name, short_name=short_name, extension_dir=extension_dir, branch=branch ) manifest.description = _try_fetch_remote_description( owner=owner, repo_name=repo_name, branch=branch, candidate_description=description ) manifest.save(extension_dir) return manifest
def _fetch_remote_binary(owner: str, repo_name: str, branch: str, short_name: str) -> bytes: executable_name = _get_executable_name(short_name) raw_url = f"https://raw.githubusercontent.com/{owner}/{repo_name}/refs/heads/{branch}/{executable_name}" response = get_session().get(raw_url, follow_redirects=True, timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT) response.raise_for_status() return response.content
def _install_binary_extension( *, owner: str, repo_name: str, short_name: str, extension_dir: Path, binary: bytes) -> ExtensionManifest: # Save extension binary executable_name = _get_executable_name(short_name) extension_dir.mkdir(parents=True, exist_ok=False) executable_path = extension_dir / executable_name executable_path.write_bytes(binary)
# Make it executable if os.name != "nt": os.chmod(executable_path, 0o755)
# Create manifest return ExtensionManifest( owner=owner, repo=repo_name, repo_id=f"{owner}/{repo_name}", short_name=short_name, executable_name=executable_name, executable_path=str(executable_path), type="binary", installed_at=datetime.now(timezone.utc), source=f"https://github.com/{owner}/{repo_name}", )
def _install_python_extension( *, owner: str, repo_name: str, short_name: str, extension_dir: Path, branch: str) -> ExtensionManifest: source_url = f"https://github.com/{owner}/{repo_name}/archive/refs/heads/{branch}.zip" venv_dir = extension_dir / "venv" installed = False
status = StatusLine() try: status.update(f"Creating virtual environment in {venv_dir}") if extension_dir.exists(): shutil.rmtree(extension_dir, ignore_errors=True) extension_dir.mkdir(parents=True, exist_ok=False)
uv_path = shutil.which("uv") venv_python = _get_venv_python_path(venv_dir) if uv_path: subprocess.run([uv_path, "venv", str(venv_dir)], check=True) status.done(f"Virtual environment created in {venv_dir}")
status.update(f"Installing package from {source_url}") subprocess.run( [uv_path, "pip", "install", "--python", str(venv_python), source_url], check=True, timeout=_EXTENSIONS_PIP_INSTALL_TIMEOUT, ) else: venv.EnvBuilder(with_pip=True).create(str(venv_dir)) status.done(f"Virtual environment created in {venv_dir}")
status.update(f"Installing package from {source_url}") subprocess.run( [ str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "--no-input", source_url, ], check=True, timeout=_EXTENSIONS_PIP_INSTALL_TIMEOUT, ) status.done(f"Package installed from {source_url}")
executable_name = _get_executable_name(short_name) venv_executable = _get_venv_extension_executable_path(venv_dir, short_name) if not venv_executable.is_file(): raise CLIError( f"Installed package from '{owner}/{repo_name}' does not expose the required console script " f"'{executable_name}'." )
manifest = ExtensionManifest( owner=owner, repo=repo_name, repo_id=f"{owner}/{repo_name}", short_name=short_name, executable_name=executable_name, executable_path=str(venv_executable.resolve()), type="python", installed_at=datetime.now(timezone.utc), source=f"https://github.com/{owner}/{repo_name}", ) installed = True return manifest except CLIError: raise except subprocess.TimeoutExpired as e: raise CLIExtensionInstallError( f"Pip install timed out after {_EXTENSIONS_PIP_INSTALL_TIMEOUT}s for '{owner}/{repo_name}'. " "See pip output above for details." ) from e except subprocess.CalledProcessError as e: raise CLIExtensionInstallError( f"Failed to install pip package from '{owner}/{repo_name}' (exit code {e.returncode}). " "See pip output above for details." ) from e except Exception as e: raise CLIExtensionInstallError(f"Failed to set up pip extension from '{owner}/{repo_name}': {e}") from e finally: if not installed: shutil.rmtree(extension_dir, ignore_errors=True)
def _try_fetch_remote_description( owner: str, repo_name: str, branch: str, candidate_description: str | None) -> str | None: """Try to fetch project description either from: - manifest.json - pyproject.toml
Only best effort, no error handling. """ # from manifest.json try: response = get_session().get( f"https://raw.githubusercontent.com/{owner}/{repo_name}/refs/heads/{branch}/{MANIFEST_FILENAME}", follow_redirects=True, ) response.raise_for_status() data = response.json() description = data.get("description") if isinstance(description, str): return description except Exception: pass
# from pyproject.toml try: response = get_session().get( f"https://raw.githubusercontent.com/{owner}/{repo_name}/refs/heads/{branch}/pyproject.toml", follow_redirects=True, ) response.raise_for_status()
# Weak parser but ok for "best effort" for line in response.text.splitlines(): line = line.strip() if line.startswith("description"): _, _, value = line.partition("=") return value.strip().strip("\"'") except Exception: pass
# fallback to value fetched from GH API directly return candidate_description
def _get_extensions_root() -> Path: root_dir = EXTENSIONS_ROOT.expanduser() root_dir.mkdir(parents=True, exist_ok=True) return root_dir
def _get_extension_dir(short_name: str) -> Path: safe_name = _validate_extension_short_name(short_name, original_input=short_name) root = _get_extensions_root().resolve() target = (root / f"hf-{safe_name}").resolve() if root not in target.parents: raise CLIError(f"Invalid extension name '{short_name}'.") return target
def _resolve_github_repo_info(owner: str, repo_name: str) -> tuple[str, str | None]: try: response = get_session().get( f"https://api.github.com/repos/{owner}/{repo_name}", follow_redirects=True, timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT, ) response.raise_for_status() data = response.json() return data["default_branch"], data.get("description") except Exception: return _EXTENSIONS_DEFAULT_BRANCH, None
def _get_executable_name(short_name: str) -> str: name = f"hf-{short_name}" if os.name == "nt": name += ".exe" return name
def _resolve_installed_executable_path(short_name: str) -> Path: extension_dir = _get_extension_dir(short_name) manifest = ExtensionManifest.load(extension_dir) return Path(manifest.executable_path).expanduser()
def _get_venv_python_path(venv_dir: Path) -> Path: if os.name == "nt": return venv_dir / "Scripts" / "python.exe" return venv_dir / "bin" / "python"
def _get_venv_extension_executable_path(venv_dir: Path, short_name: str) -> Path: executable_name = _get_executable_name(short_name) if os.name == "nt": return venv_dir / "Scripts" / executable_name return venv_dir / "bin" / executable_name
_ALLOWED_EXTENSION_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
def _validate_extension_short_name(short_name: str, *, original_input: str) -> str: name = short_name.strip() if not name: raise CLIError("Extension name cannot be empty.") if any(sep in name for sep in ("/", "\\")): raise CLIError(f"Invalid extension name '{original_input}'.") if ".." in name or ":" in name: raise CLIError(f"Invalid extension name '{original_input}'.") if not _ALLOWED_EXTENSION_NAME.fullmatch(name): raise CLIError( f"Invalid extension name '{original_input}'. Allowed characters: letters, digits, '.', '_' and '-'." ) return name
def _normalize_repo_id(repo_id: str) -> tuple[str, str, str]: if "://" in repo_id: raise CLIError("Only GitHub repositories in `[OWNER/]hf-<name>` format are supported.")
parts = repo_id.split("/") if len(parts) == 1: owner = DEFAULT_EXTENSION_OWNER repo_name = parts[0] elif len(parts) == 2 and all(parts): owner, repo_name = parts else: raise CLIError(f"Expected `[OWNER/]REPO` format, got '{repo_id}'.")
if not repo_name.startswith("hf-"): raise CLIError(f"Extension repository name must start with 'hf-', got '{repo_name}'.")
short_name = repo_name[3:] if not short_name: raise CLIError("Invalid extension repository name 'hf-'.") _validate_extension_short_name(short_name, original_input=repo_id)
return owner, repo_name, short_name
def _normalize_extension_name(name: str) -> str: candidate = name.strip() if not candidate: raise CLIError("Extension name cannot be empty.") normalized = candidate[3:] if candidate.startswith("hf-") else candidate return _validate_extension_short_name(normalized, original_input=name)
def _execute_extension_binary(executable_path: Path, args: list[str]) -> int: try: return subprocess.call([str(executable_path)] + args) except OSError as e: if os.name == "nt" or e.errno != errno.ENOEXEC: raise return subprocess.call(["sh", str(executable_path)] + args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127# Copyright 2020 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import sysimport tracebackfrom typing import Annotated
import typer
from huggingface_hub import __version__, constantsfrom huggingface_hub.cli._cli_utils import check_cli_update, fallback_typer_group_factory, typer_factoryfrom huggingface_hub.cli._errors import format_known_exceptionfrom huggingface_hub.cli.auth import auth_clifrom huggingface_hub.cli.buckets import buckets_cli, syncfrom huggingface_hub.cli.cache import cache_clifrom huggingface_hub.cli.collections import collections_clifrom huggingface_hub.cli.datasets import datasets_clifrom huggingface_hub.cli.discussions import discussions_clifrom huggingface_hub.cli.download import DOWNLOAD_EXAMPLES, downloadfrom huggingface_hub.cli.extensions import ( dispatch_unknown_top_level_extension, extensions_cli, list_installed_extensions_for_help,)from huggingface_hub.cli.inference_endpoints import ie_clifrom huggingface_hub.cli.jobs import jobs_clifrom huggingface_hub.cli.lfs import lfs_enable_largefiles, lfs_multipart_uploadfrom huggingface_hub.cli.models import models_clifrom huggingface_hub.cli.papers import papers_clifrom huggingface_hub.cli.repo_files import repo_files_clifrom huggingface_hub.cli.repos import repos_clifrom huggingface_hub.cli.skills import skills_clifrom huggingface_hub.cli.spaces import spaces_clifrom huggingface_hub.cli.system import env, versionfrom huggingface_hub.cli.upload import UPLOAD_EXAMPLES, uploadfrom huggingface_hub.cli.upload_large_folder import UPLOAD_LARGE_FOLDER_EXAMPLES, upload_large_folderfrom huggingface_hub.cli.webhooks import webhooks_clifrom huggingface_hub.utils import ANSI, logging
app = typer_factory( help="Hugging Face Hub CLI", cls=fallback_typer_group_factory( dispatch_unknown_top_level_extension, extra_commands_provider=list_installed_extensions_for_help, ),)
def _version_callback(value: bool) -> None: if value: print(__version__) raise typer.Exit()
@app.callback(invoke_without_command=True)def app_callback( version: Annotated[ bool | None, typer.Option("--version", callback=_version_callback, is_eager=True, hidden=True) ] = None,) -> None: pass
# top level single commands (defined in their respective files)app.command()(sync)app.command(examples=DOWNLOAD_EXAMPLES)(download)app.command(examples=UPLOAD_EXAMPLES)(upload)app.command(examples=UPLOAD_LARGE_FOLDER_EXAMPLES)(upload_large_folder)
app.command(topic="help")(env)app.command(topic="help")(version)
app.command(hidden=True)(lfs_enable_largefiles)app.command(hidden=True)(lfs_multipart_upload)
# command groupsapp.add_typer(auth_cli, name="auth")app.add_typer(buckets_cli, name="buckets")app.add_typer(cache_cli, name="cache")app.add_typer(collections_cli, name="collections")app.add_typer(datasets_cli, name="datasets")app.add_typer(discussions_cli, name="discussions")app.add_typer(jobs_cli, name="jobs")app.add_typer(models_cli, name="models")app.add_typer(papers_cli, name="papers")app.add_typer(repos_cli, name="repos | repo")app.add_typer(repo_files_cli, name="repo-files", hidden=True)app.add_typer(skills_cli, name="skills")app.add_typer(spaces_cli, name="spaces")app.add_typer(webhooks_cli, name="webhooks")app.add_typer(ie_cli, name="endpoints")app.add_typer(extensions_cli, name="extensions | ext")
def main(): if not constants.HF_DEBUG: logging.set_verbosity_info() check_cli_update("huggingface_hub")
try: app() except Exception as e: message = format_known_exception(e) if message: print(f"Error: {message}", file=sys.stderr) if constants.HF_DEBUG: traceback.print_exc() else: print(ANSI.gray("Set HF_DEBUG=1 as environment variable for full traceback.")) sys.exit(1) raise
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463"""CLI commands for Hugging Face Inference Endpoints."""
import jsonfrom typing import Annotated, Any
import typer
from huggingface_hub._inference_endpoints import InferenceEndpoint, InferenceEndpointScalingMetricfrom huggingface_hub.errors import HfHubHTTPError
from ._cli_utils import ( FormatOpt, OutputFormat, QuietOpt, TokenOpt, get_hf_api, print_list_output, typer_factory,)
ie_cli = typer_factory(help="Manage Hugging Face Inference Endpoints.")
catalog_app = typer_factory(help="Interact with the Inference Endpoints catalog.")
NameArg = Annotated[ str, typer.Argument(help="Endpoint name."),]NameOpt = Annotated[ str | None, typer.Option(help="Endpoint name."),]
NamespaceOpt = Annotated[ str | None, typer.Option( help="The namespace associated with the Inference Endpoint. Defaults to the current user's namespace.", ),]
def _print_endpoint(endpoint: InferenceEndpoint) -> None: typer.echo(json.dumps(endpoint.raw, indent=2, sort_keys=True))
@ie_cli.command("list | ls", examples=["hf endpoints ls", "hf endpoints ls --namespace my-org"])def ls( namespace: NamespaceOpt = None, format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """Lists all Inference Endpoints for the given namespace.""" api = get_hf_api(token=token) try: endpoints = api.list_inference_endpoints(namespace=namespace, token=token) except HfHubHTTPError as error: typer.echo(f"Listing failed: {error}") raise typer.Exit(code=error.response.status_code) from error
results = [endpoint.raw for endpoint in endpoints]
def row_fn(item: dict[str, Any]) -> list[str]: status = item.get("status", {}) model = item.get("model", {}) compute = item.get("compute", {}) provider = item.get("provider", {}) return [ str(item.get("name", "")), str(model.get("repository", "") if isinstance(model, dict) else ""), str(status.get("state", "") if isinstance(status, dict) else ""), str(model.get("task", "") if isinstance(model, dict) else ""), str(model.get("framework", "") if isinstance(model, dict) else ""), str(compute.get("instanceType", "") if isinstance(compute, dict) else ""), str(provider.get("vendor", "") if isinstance(provider, dict) else ""), str(provider.get("region", "") if isinstance(provider, dict) else ""), ]
print_list_output( items=results, format=format, quiet=quiet, id_key="name", headers=["NAME", "MODEL", "STATUS", "TASK", "FRAMEWORK", "INSTANCE", "VENDOR", "REGION"], row_fn=row_fn, )
@ie_cli.command(name="deploy", examples=["hf endpoints deploy my-endpoint --repo gpt2 --framework pytorch ..."])def deploy( name: NameArg, repo: Annotated[ str, typer.Option( help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').", ), ], framework: Annotated[ str, typer.Option( help="The machine learning framework used for the model (e.g. 'vllm').", ), ], accelerator: Annotated[ str, typer.Option( help="The hardware accelerator to be used for inference (e.g. 'cpu').", ), ], instance_size: Annotated[ str, typer.Option( help="The size or type of the instance to be used for hosting the model (e.g. 'x4').", ), ], instance_type: Annotated[ str, typer.Option( help="The cloud instance type where the Inference Endpoint will be deployed (e.g. 'intel-icl').", ), ], region: Annotated[ str, typer.Option( help="The cloud region in which the Inference Endpoint will be created (e.g. 'us-east-1').", ), ], vendor: Annotated[ str, typer.Option( help="The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. 'aws').", ), ], *, namespace: NamespaceOpt = None, task: Annotated[ str | None, typer.Option( help="The task on which to deploy the model (e.g. 'text-classification').", ), ] = None, token: TokenOpt = None, min_replica: Annotated[ int, typer.Option( help="The minimum number of replicas (instances) to keep running for the Inference Endpoint.", ), ] = 1, max_replica: Annotated[ int, typer.Option( help="The maximum number of replicas (instances) to scale to for the Inference Endpoint.", ), ] = 1, scale_to_zero_timeout: Annotated[ int | None, typer.Option( help="The duration in minutes before an inactive endpoint is scaled to zero.", ), ] = None, scaling_metric: Annotated[ InferenceEndpointScalingMetric | None, typer.Option( help="The metric reference for scaling.", ), ] = None, scaling_threshold: Annotated[ float | None, typer.Option( help="The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.", ), ] = None,) -> None: """Deploy an Inference Endpoint from a Hub repository.""" api = get_hf_api(token=token) endpoint = api.create_inference_endpoint( name=name, repository=repo, framework=framework, accelerator=accelerator, instance_size=instance_size, instance_type=instance_type, region=region, vendor=vendor, namespace=namespace, task=task, token=token, min_replica=min_replica, max_replica=max_replica, scaling_metric=scaling_metric, scaling_threshold=scaling_threshold, scale_to_zero_timeout=scale_to_zero_timeout, )
_print_endpoint(endpoint)
@catalog_app.command(name="deploy", examples=["hf endpoints catalog deploy --repo meta-llama/Llama-3.2-1B-Instruct"])def deploy_from_catalog( repo: Annotated[ str, typer.Option( help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').", ), ], name: NameOpt = None, accelerator: Annotated[ str | None, typer.Option( help="The hardware accelerator to be used for inference (e.g. 'cpu', 'gpu', 'neuron').", ), ] = None, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Deploy an Inference Endpoint from the Model Catalog.""" api = get_hf_api(token=token) try: endpoint = api.create_inference_endpoint_from_catalog( repo_id=repo, name=name, accelerator=accelerator, namespace=namespace, token=token, ) except HfHubHTTPError as error: typer.echo(f"Deployment failed: {error}") raise typer.Exit(code=error.response.status_code) from error
_print_endpoint(endpoint)
def list_catalog( token: TokenOpt = None,) -> None: """List available Catalog models.""" api = get_hf_api(token=token) try: models = api.list_inference_catalog(token=token) except HfHubHTTPError as error: typer.echo(f"Catalog fetch failed: {error}") raise typer.Exit(code=error.response.status_code) from error
typer.echo(json.dumps({"models": models}, indent=2, sort_keys=True))
catalog_app.command(name="list | ls", examples=["hf endpoints catalog ls"])(list_catalog)ie_cli.command(name="list-catalog", hidden=True)(list_catalog)
ie_cli.add_typer(catalog_app, name="catalog")
@ie_cli.command(examples=["hf endpoints describe my-endpoint"])def describe( name: NameArg, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Get information about an existing endpoint.""" api = get_hf_api(token=token) try: endpoint = api.get_inference_endpoint(name=name, namespace=namespace, token=token) except HfHubHTTPError as error: typer.echo(f"Fetch failed: {error}") raise typer.Exit(code=error.response.status_code) from error
_print_endpoint(endpoint)
@ie_cli.command(examples=["hf endpoints update my-endpoint --min-replica 2"])def update( name: NameArg, namespace: NamespaceOpt = None, repo: Annotated[ str | None, typer.Option( help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').", ), ] = None, accelerator: Annotated[ str | None, typer.Option( help="The hardware accelerator to be used for inference (e.g. 'cpu').", ), ] = None, instance_size: Annotated[ str | None, typer.Option( help="The size or type of the instance to be used for hosting the model (e.g. 'x4').", ), ] = None, instance_type: Annotated[ str | None, typer.Option( help="The cloud instance type where the Inference Endpoint will be deployed (e.g. 'intel-icl').", ), ] = None, framework: Annotated[ str | None, typer.Option( help="The machine learning framework used for the model (e.g. 'custom').", ), ] = None, revision: Annotated[ str | None, typer.Option( help="The specific model revision to deploy on the Inference Endpoint (e.g. '6c0e6080953db56375760c0471a8c5f2929baf11').", ), ] = None, task: Annotated[ str | None, typer.Option( help="The task on which to deploy the model (e.g. 'text-classification').", ), ] = None, min_replica: Annotated[ int | None, typer.Option( help="The minimum number of replicas (instances) to keep running for the Inference Endpoint.", ), ] = None, max_replica: Annotated[ int | None, typer.Option( help="The maximum number of replicas (instances) to scale to for the Inference Endpoint.", ), ] = None, scale_to_zero_timeout: Annotated[ int | None, typer.Option( help="The duration in minutes before an inactive endpoint is scaled to zero.", ), ] = None, scaling_metric: Annotated[ InferenceEndpointScalingMetric | None, typer.Option( help="The metric reference for scaling.", ), ] = None, scaling_threshold: Annotated[ float | None, typer.Option( help="The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.", ), ] = None, token: TokenOpt = None,) -> None: """Update an existing endpoint.""" api = get_hf_api(token=token) try: endpoint = api.update_inference_endpoint( name=name, namespace=namespace, repository=repo, framework=framework, revision=revision, task=task, accelerator=accelerator, instance_size=instance_size, instance_type=instance_type, min_replica=min_replica, max_replica=max_replica, scale_to_zero_timeout=scale_to_zero_timeout, scaling_metric=scaling_metric, scaling_threshold=scaling_threshold, token=token, ) except HfHubHTTPError as error: typer.echo(f"Update failed: {error}") raise typer.Exit(code=error.response.status_code) from error _print_endpoint(endpoint)
@ie_cli.command(examples=["hf endpoints delete my-endpoint"])def delete( name: NameArg, namespace: NamespaceOpt = None, yes: Annotated[ bool, typer.Option("--yes", help="Skip confirmation prompts."), ] = False, token: TokenOpt = None,) -> None: """Delete an Inference Endpoint permanently.""" if not yes: confirmation = typer.prompt(f"Delete endpoint '{name}'? Type the name to confirm.") if confirmation != name: typer.echo("Aborted.") raise typer.Exit(code=2)
api = get_hf_api(token=token) try: api.delete_inference_endpoint(name=name, namespace=namespace, token=token) except HfHubHTTPError as error: typer.echo(f"Delete failed: {error}") raise typer.Exit(code=error.response.status_code) from error
typer.echo(f"Deleted '{name}'.")
@ie_cli.command(examples=["hf endpoints pause my-endpoint"])def pause( name: NameArg, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Pause an Inference Endpoint.""" api = get_hf_api(token=token) try: endpoint = api.pause_inference_endpoint(name=name, namespace=namespace, token=token) except HfHubHTTPError as error: typer.echo(f"Pause failed: {error}") raise typer.Exit(code=error.response.status_code) from error
_print_endpoint(endpoint)
@ie_cli.command(examples=["hf endpoints resume my-endpoint"])def resume( name: NameArg, namespace: NamespaceOpt = None, fail_if_already_running: Annotated[ bool, typer.Option( "--fail-if-already-running", help="If `True`, the method will raise an error if the Inference Endpoint is already running.", ), ] = False, token: TokenOpt = None,) -> None: """Resume an Inference Endpoint.""" api = get_hf_api(token=token) try: endpoint = api.resume_inference_endpoint( name=name, namespace=namespace, token=token, running_ok=not fail_if_already_running, ) except HfHubHTTPError as error: typer.echo(f"Resume failed: {error}") raise typer.Exit(code=error.response.status_code) from error _print_endpoint(endpoint)
@ie_cli.command(examples=["hf endpoints scale-to-zero my-endpoint"])def scale_to_zero( name: NameArg, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Scale an Inference Endpoint to zero.""" api = get_hf_api(token=token) try: endpoint = api.scale_to_zero_inference_endpoint(name=name, namespace=namespace, token=token) except HfHubHTTPError as error: typer.echo(f"Scale To Zero failed: {error}") raise typer.Exit(code=error.response.status_code) from error
_print_endpoint(endpoint)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with jobs on the Hugging Face Hub.
Usage: # run a job hf jobs run <image> <command>
# List running or completed jobs hf jobs ps [-a] [-f key=value] [--format table|json|TEMPLATE] [-q]
# Print logs from a job (non-blocking) hf jobs logs <job-id>
# Stream logs from a job (blocking, like `docker logs -f`) hf jobs logs -f <job-id>
# Stream resources usage stats and metrics from a job hf jobs stats <job-id>
# Inspect detailed information about a job hf jobs inspect <job-id>
# Cancel a running job hf jobs cancel <job-id>
# List available hardware options hf jobs hardware
# Run a UV script hf jobs uv run <script>
# Schedule a job hf jobs scheduled run <schedule> <image> <command>
# List scheduled jobs hf jobs scheduled ps [-a] [-f key=value] [--format table|json] [-q]
# Inspect a scheduled job hf jobs scheduled inspect <scheduled_job_id>
# Suspend a scheduled job hf jobs scheduled suspend <scheduled_job_id>
# Resume a scheduled job hf jobs scheduled resume <scheduled_job_id>
# Delete a scheduled job hf jobs scheduled delete <scheduled_job_id>
"""
import jsonimport multiprocessingimport multiprocessing.poolimport shutilimport timefrom collections import dequefrom collections.abc import Callable, Iterablefrom dataclasses import asdictfrom fnmatch import fnmatchfrom queue import Empty, Queuefrom typing import Annotated, Any, TypeVar
import typer
from huggingface_hub import SpaceHardwarefrom huggingface_hub.errors import CLIError, HfHubHTTPErrorfrom huggingface_hub.utils import loggingfrom huggingface_hub.utils._cache_manager import _format_size
from ._cli_utils import ( EnvFileOpt, EnvOpt, OutputFormat, QuietOpt, SecretsFileOpt, SecretsOpt, TokenOpt, VolumesOpt, _format_cell, api_object_to_dict, get_hf_api, parse_env_map, parse_volumes, print_list_output, typer_factory,)
logger = logging.get_logger(__name__)
def _parse_namespace_from_job_id(job_id: str, namespace: str | None) -> tuple[str, str | None]: """Extract namespace from job_id if provided in 'namespace/job_id' format.
Allows users to pass job IDs copied from the Hub UI (e.g. 'username/job_id') instead of only bare job IDs. If the namespace is also provided explicitly via --namespace and conflicts, a CLIError is raised. """ if not job_id: raise CLIError("Job ID cannot be empty.")
if job_id.count("/") > 1: raise CLIError(f"Job ID must be in the form 'job_id' or 'namespace/job_id': '{job_id}'.")
if "/" not in job_id: return job_id, namespace
extracted_namespace, parsed_job_id = job_id.split("/", 1) if not extracted_namespace or not parsed_job_id: raise CLIError(f"Job ID must be in the form 'job_id' or 'namespace/job_id': '{job_id}'.")
if namespace is not None and namespace != extracted_namespace: raise CLIError( f"Conflicting namespace: got --namespace='{namespace}' but job ID implies namespace='{extracted_namespace}'" )
return parsed_job_id, extracted_namespace
SUGGESTED_FLAVORS = [item.value for item in SpaceHardware if item.value != "zero-a10g"]STATS_UPDATE_MIN_INTERVAL = 0.1 # we set a limit here since there is one update per second per job
# Common job-related optionsImageArg = Annotated[ str, typer.Argument( help="The Docker image to use.", ),]
ImageOpt = Annotated[ str | None, typer.Option( help="Use a custom Docker image with `uv` installed.", ),]
FlavorOpt = Annotated[ SpaceHardware | None, typer.Option( help="Flavor for the hardware, as in HF Spaces. Run 'hf jobs hardware' to list available flavors. Defaults to `cpu-basic`.", ),]
LabelsOpt = Annotated[ list[str] | None, typer.Option( "-l", "--label", help="Set labels. E.g. --label KEY=VALUE or --label LABEL", ),]
TimeoutOpt = Annotated[ str | None, typer.Option( help="Max duration: int/float with s (seconds, default), m (minutes), h (hours) or d (days).", ),]
DetachOpt = Annotated[ bool, typer.Option( "-d", "--detach", help="Run the Job in the background and print the Job ID.", ),]
NamespaceOpt = Annotated[ str | None, typer.Option( help="The namespace where the job will be running. Defaults to the current user's namespace.", ),]
WithOpt = Annotated[ list[str] | None, typer.Option( "--with", help="Run with the given packages installed", ),]
PythonOpt = Annotated[ str | None, typer.Option( "-p", "--python", help="The Python interpreter to use for the run environment", ),]
SuspendOpt = Annotated[ bool | None, typer.Option( help="Suspend (pause) the scheduled Job", ),]
ConcurrencyOpt = Annotated[ bool | None, typer.Option( help="Allow multiple instances of this Job to run concurrently", ),]
ScheduleArg = Annotated[ str, typer.Argument( help="One of annually, yearly, monthly, weekly, daily, hourly, or a CRON schedule expression.", ),]
ScriptArg = Annotated[ str, typer.Argument( help="UV script to run (local file or URL)", ),]
ScriptArgsArg = Annotated[ list[str] | None, typer.Argument( help="Arguments for the script", ),]
CommandArg = Annotated[ list[str], typer.Argument( help="The command to run.", ),]
JobIdArg = Annotated[ str, typer.Argument( help="Job ID (or 'namespace/job_id')", ),]
JobIdsArg = Annotated[ list[str] | None, typer.Argument( help="Job IDs (or 'namespace/job_id')", ),]
ScheduledJobIdArg = Annotated[ str, typer.Argument( help="Scheduled Job ID (or 'namespace/scheduled_job_id')", ),]
jobs_cli = typer_factory(help="Run and manage Jobs on the Hub.")
@jobs_cli.command( "run", context_settings={"ignore_unknown_options": True}, examples=[ "hf jobs run python:3.12 python -c 'print(\"Hello!\")'", "hf jobs run -e FOO=foo python:3.12 python script.py", "hf jobs run --secrets HF_TOKEN python:3.12 python script.py", "hf jobs run -v hf://gpt2:/data -v hf://buckets/org/b:/mnt python:3.12 python script.py", ],)def jobs_run( image: ImageArg, command: CommandArg, env: EnvOpt = None, secrets: SecretsOpt = None, label: LabelsOpt = None, volume: VolumesOpt = None, env_file: EnvFileOpt = None, secrets_file: SecretsFileOpt = None, flavor: FlavorOpt = None, timeout: TimeoutOpt = None, detach: DetachOpt = False, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Run a Job.""" env_map = parse_env_map(env, env_file) secrets_map = parse_env_map(secrets, secrets_file)
api = get_hf_api(token=token) job = api.run_job( image=image, command=command, env=env_map, secrets=secrets_map, labels=_parse_labels_map(label), volumes=parse_volumes(volume), flavor=flavor, timeout=timeout, namespace=namespace, ) # Always print the job ID to the user print(f"Job started with ID: {job.id}") print(f"View at: {job.url}")
if detach: return # Now let's stream the logs for log in api.fetch_job_logs(job_id=job.id, namespace=job.owner.name, follow=True): print(log)
@jobs_cli.command( "logs", examples=["hf jobs logs <job_id>", "hf jobs logs -f <job_id>", "hf jobs logs --tail 20 <job_id>"])def jobs_logs( job_id: JobIdArg, follow: Annotated[ bool, typer.Option( "-f", "--follow", help="Follow log output (stream until the job completes). Without this flag, only currently available logs are printed.", ), ] = False, tail: Annotated[ int | None, typer.Option( "-n", "--tail", help="Number of lines to show from the end of the logs.", ), ] = None, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Fetch the logs of a Job.
By default, prints currently available logs and exits (non-blocking). Use --follow/-f to stream logs in real-time until the job completes. """ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace) if follow and tail is not None: raise CLIError( "Cannot use --follow and --tail together. Use --follow to stream logs or --tail to show recent logs." )
api = get_hf_api(token=token) try: logs = api.fetch_job_logs(job_id=job_id, namespace=namespace, follow=follow) if tail is not None: logs = deque(logs, maxlen=tail) for log in logs: print(log) except HfHubHTTPError as e: status = e.response.status_code if e.response is not None else None if status == 404: raise CLIError("Job not found. Please check the job ID.") from e elif status == 403: raise CLIError("Access denied. You may not have permission to view this job.") from e else: raise CLIError(f"Failed to fetch job logs: {e}") from e
def _matches_filters(job_properties: dict[str, str], filters: list[tuple[str, str, str]]) -> bool: """Check if scheduled job matches all specified filters.""" for key, op_str, pattern in filters: value = job_properties.get(key) if value is None: if op_str == "!=": continue return False match = fnmatch(value.lower(), pattern.lower()) if (op_str == "=" and not match) or (op_str == "!=" and match): return False return True
def _print_output(rows: list[list[str | int]], headers: list[str], aliases: list[str], fmt: str | None) -> None: """Print output according to the chosen format.""" if fmt: # Use custom template if provided template = fmt for row in rows: line = template for i, field in enumerate(aliases): placeholder = f"{{{{.{field}}}}}" if placeholder in line: line = line.replace(placeholder, str(row[i])) print(line) else: # Default tabular format print(_tabulate(rows, headers=headers))
def _clear_line(n: int) -> None: LINE_UP = "\033[1A" LINE_CLEAR = "\x1b[2K" for i in range(n): print(LINE_UP, end=LINE_CLEAR)
def _get_jobs_stats_rows( job_id: str, metrics_stream: Iterable[dict[str, Any]], table_headers: list[str]) -> Iterable[tuple[bool, str, list[list[str | int]]]]: for metrics in metrics_stream: row = [ job_id, f"{metrics['cpu_usage_pct']}%", round(metrics["cpu_millicores"] / 1000.0, 1), f"{round(100 * metrics['memory_used_bytes'] / metrics['memory_total_bytes'], 2)}%", f"{_format_size(metrics['memory_used_bytes'])}B / {_format_size(metrics['memory_total_bytes'])}B", f"{_format_size(metrics['rx_bps'])}bps / {_format_size(metrics['tx_bps'])}bps", ] if metrics["gpus"] and isinstance(metrics["gpus"], dict): rows = [row] + [[""] * len(row)] * (len(metrics["gpus"]) - 1) for row, gpu_id in zip(rows, sorted(metrics["gpus"])): gpu = metrics["gpus"][gpu_id] row += [ f"{gpu['utilization']}%", f"{round(100 * gpu['memory_used_bytes'] / gpu['memory_total_bytes'], 2)}%", f"{_format_size(gpu['memory_used_bytes'])}B / {_format_size(gpu['memory_total_bytes'])}B", ] else: row += ["N/A"] * (len(table_headers) - len(row)) rows = [row] yield False, job_id, rows yield True, job_id, []
@jobs_cli.command("stats", examples=["hf jobs stats <job_id>"])def jobs_stats( job_ids: JobIdsArg = None, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Fetch the resource usage statistics and metrics of Jobs""" if job_ids is not None: parsed_ids = [] for job_id in job_ids: job_id, namespace = _parse_namespace_from_job_id(job_id, namespace) parsed_ids.append(job_id) job_ids = parsed_ids api = get_hf_api(token=token) if namespace is None: namespace = api.whoami()["name"] if job_ids is None: job_ids = [ job.id for job in api.list_jobs(namespace=namespace) if (job.status.stage if job.status else "UNKNOWN") in ("RUNNING", "UPDATING") ] if len(job_ids) == 0: print("No running jobs found") return table_headers = [ "JOB ID", "CPU %", "NUM CPU", "MEM %", "MEM USAGE", "NET I/O", "GPU UTIL %", "GPU MEM %", "GPU MEM USAGE", ] headers_aliases = [ "id", "cpu_usage_pct", "cpu_millicores", "memory_used_bytes_pct", "memory_used_bytes_and_total_bytes", "rx_bps_and_tx_bps", "gpu_utilization", "gpu_memory_used_bytes_pct", "gpu_memory_used_bytes_and_total_bytes", ] try: with multiprocessing.pool.ThreadPool(len(job_ids)) as pool: rows_per_job_id: dict[str, list[list[str | int]]] = {} for job_id in job_ids: row: list[str | int] = [job_id] row += ["-- / --" if ("/" in header or "USAGE" in header) else "--" for header in table_headers[1:]] rows_per_job_id[job_id] = [row] last_update_time = time.time() total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]] _print_output(total_rows, table_headers, headers_aliases, None)
kwargs_list = [ { "job_id": job_id, "metrics_stream": api.fetch_job_metrics(job_id=job_id, namespace=namespace), "table_headers": table_headers, } for job_id in job_ids ] for done, job_id, rows in iflatmap_unordered(pool, _get_jobs_stats_rows, kwargs_list=kwargs_list): if done: rows_per_job_id.pop(job_id, None) else: rows_per_job_id[job_id] = rows now = time.time() if now - last_update_time >= STATS_UPDATE_MIN_INTERVAL: _clear_line(2 + len(total_rows)) total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]] _print_output(total_rows, table_headers, headers_aliases, None) last_update_time = now except HfHubHTTPError as e: status = e.response.status_code if e.response is not None else None if status == 404: raise CLIError("Job not found. Please check the job ID.") from e elif status == 403: raise CLIError("Access denied. You may not have permission to view this job.") from e else: raise CLIError(f"Failed to fetch job stats: {e}") from e
@jobs_cli.command("ps", examples=["hf jobs ps", "hf jobs ps -a"])def jobs_ps( all: Annotated[ bool, typer.Option( "-a", "--all", help="Show all Jobs (default shows just running)", ), ] = False, namespace: NamespaceOpt = None, token: TokenOpt = None, filter: Annotated[ list[str] | None, typer.Option( "-f", "--filter", help="Filter output based on conditions provided (format: key=value)", ), ] = None, format: Annotated[ str | None, typer.Option(help="Output format: 'table' (default), 'json', or a Go template (e.g. '{{.id}}')"), ] = None, quiet: QuietOpt = False,) -> None: """List Jobs.""" api = get_hf_api(token=token) # Fetch jobs data jobs = api.list_jobs(namespace=namespace)
filters: list[tuple[str, str, str]] = [] labels_filters: list[tuple[str, str, str]] = [] for f in filter or []: if f.startswith("label!=") or f.startswith("label="): if f.startswith("label!="): label_part = f[len("label!=") :] if "=" in label_part: print( f"Warning: Ignoring invalid label filter format 'label!={label_part}'. Use label!=key format." ) continue label_key, op, label_value = label_part, "!=", "*" else: label_part = f[len("label=") :] if "=" in label_part: label_key, label_value = label_part.split("=", 1) else: label_key, label_value = label_part, "*" # Negate predicate in case of key!=value if label_key.endswith("!"): op = "!=" label_key = label_key[:-1] else: op = "=" labels_filters.append((label_key.lower(), op, label_value.lower())) elif "=" in f: key, value = f.split("=", 1) # Negate predicate in case of key!=value if key.endswith("!"): op = "!=" key = key[:-1] else: op = "=" filters.append((key.lower(), op, value.lower())) else: print(f"Warning: Ignoring invalid filter format '{f}'. Use key=value format.")
# Filter jobs (operating on JobInfo objects to preserve existing filter behavior) filtered_jobs = [] for job in jobs: status = job.status.stage if job.status else "UNKNOWN" if not all and status not in ("RUNNING", "UPDATING"): continue image_or_space = job.docker_image or "N/A" cmd = job.command or [] command_str = " ".join(cmd) if cmd else "N/A" props = {"id": job.id, "image": image_or_space, "status": status.lower(), "command": command_str} if not _matches_filters(props, filters): continue if not _matches_filters(job.labels or {}, labels_filters): continue filtered_jobs.append(job)
if not filtered_jobs: if not quiet and format != "json": filters_msg = f" matching filters: {', '.join([f'{k}{o}{v}' for k, o, v in filters])}" if filters else "" print(f"No jobs found{filters_msg}") elif format == "json": print("[]") return
headers = ["JOB ID", "IMAGE/SPACE", "COMMAND", "CREATED", "STATUS"] aliases = ["id", "image", "command", "created", "status"] items = [api_object_to_dict(job) for job in filtered_jobs]
def row_fn(item: dict[str, Any]) -> list[str]: status = item.get("status", {}) cmd = item.get("command") or [] command_str = " ".join(cmd) if cmd else "N/A" return [ str(item.get("id", "")), _format_cell(item.get("docker_image") or "N/A"), _format_cell(command_str), item["created_at"][:19].replace("T", " ") if item.get("created_at") else "N/A", str(status.get("stage", "UNKNOWN")), ]
# Custom template format if format and format not in ("table", "json"): _print_output([row_fn(item) for item in items], headers, aliases, format) # type: ignore else: output_format = OutputFormat.json if format == "json" else OutputFormat.table print_list_output( items=items, format=output_format, quiet=quiet, id_key="id", headers=headers, row_fn=row_fn, )
@jobs_cli.command("hardware", examples=["hf jobs hardware"])def jobs_hardware() -> None: """List available hardware options for Jobs""" api = get_hf_api() hardware_list = api.list_jobs_hardware() table_headers = ["NAME", "PRETTY NAME", "CPU", "RAM", "ACCELERATOR", "COST/MIN", "COST/HOUR"] headers_aliases = ["name", "prettyName", "cpu", "ram", "accelerator", "costMin", "costHour"] rows: list[list[str | int]] = []
for hw in hardware_list: accelerator_info = "N/A" if hw.accelerator: accelerator_info = f"{hw.accelerator.quantity}x {hw.accelerator.model} ({hw.accelerator.vram})" cost_min = f"${hw.unit_cost_usd:.4f}" if hw.unit_cost_usd is not None else "N/A" cost_hour = f"${hw.unit_cost_usd * 60:.2f}" if hw.unit_cost_usd is not None else "N/A" rows.append([hw.name, hw.pretty_name or "N/A", hw.cpu, hw.ram, accelerator_info, cost_min, cost_hour])
if not rows: print("No hardware options found") return _print_output(rows, table_headers, headers_aliases, None)
@jobs_cli.command("inspect", examples=["hf jobs inspect <job_id>"])def jobs_inspect( job_ids: Annotated[ list[str], typer.Argument( help="Job IDs to inspect (or 'namespace/job_id')", ), ], namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Display detailed information on one or more Jobs""" parsed_ids = [] for job_id in job_ids: job_id, namespace = _parse_namespace_from_job_id(job_id, namespace) parsed_ids.append(job_id) job_ids = parsed_ids api = get_hf_api(token=token) try: jobs = [api.inspect_job(job_id=job_id, namespace=namespace) for job_id in job_ids] print(json.dumps([asdict(job) for job in jobs], indent=4, default=str)) except HfHubHTTPError as e: status = e.response.status_code if e.response is not None else None if status == 404: raise CLIError("Job not found. Please check the job ID.") from e elif status == 403: raise CLIError("Access denied. You may not have permission to view this job.") from e else: raise CLIError(f"Failed to inspect job: {e}") from e
@jobs_cli.command("cancel", examples=["hf jobs cancel <job_id>"])def jobs_cancel( job_id: JobIdArg, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Cancel a Job""" job_id, namespace = _parse_namespace_from_job_id(job_id, namespace) api = get_hf_api(token=token) try: api.cancel_job(job_id=job_id, namespace=namespace) except HfHubHTTPError as e: status = e.response.status_code if e.response is not None else None if status == 404: raise CLIError("Job not found. Please check the job ID.") from e elif status == 403: raise CLIError("Access denied. You may not have permission to cancel this job.") from e else: raise CLIError(f"Failed to cancel job: {e}") from e
uv_app = typer_factory(help="Run UV scripts (Python with inline dependencies) on HF infrastructure.")jobs_cli.add_typer(uv_app, name="uv")
@uv_app.command( "run", context_settings={"ignore_unknown_options": True}, examples=[ "hf jobs uv run my_script.py", "hf jobs uv run ml_training.py --flavor a10g-small", "hf jobs uv run --with transformers train.py", "hf jobs uv run -v hf://gpt2:/data -v hf://buckets/org/b:/mnt script.py", ],)def jobs_uv_run( script: ScriptArg, script_args: ScriptArgsArg = None, image: ImageOpt = None, flavor: FlavorOpt = None, env: EnvOpt = None, secrets: SecretsOpt = None, label: LabelsOpt = None, volume: VolumesOpt = None, env_file: EnvFileOpt = None, secrets_file: SecretsFileOpt = None, timeout: TimeoutOpt = None, detach: DetachOpt = False, namespace: NamespaceOpt = None, token: TokenOpt = None, with_: WithOpt = None, python: PythonOpt = None,) -> None: """Run a UV script (local file or URL) on HF infrastructure""" env_map = parse_env_map(env, env_file) secrets_map = parse_env_map(secrets, secrets_file)
api = get_hf_api(token=token) job = api.run_uv_job( script=script, script_args=script_args or [], dependencies=with_, python=python, image=image, env=env_map, secrets=secrets_map, labels=_parse_labels_map(label), volumes=parse_volumes(volume), flavor=flavor, # type: ignore[arg-type,misc] timeout=timeout, namespace=namespace, ) # Always print the job ID to the user print(f"Job started with ID: {job.id}") print(f"View at: {job.url}") if detach: return # Now let's stream the logs for log in api.fetch_job_logs(job_id=job.id, namespace=job.owner.name, follow=True): print(log)
scheduled_app = typer_factory(help="Create and manage scheduled Jobs on the Hub.")jobs_cli.add_typer(scheduled_app, name="scheduled")
@scheduled_app.command( "run", context_settings={"ignore_unknown_options": True}, examples=['hf jobs scheduled run "0 0 * * *" python:3.12 python script.py'],)def scheduled_run( schedule: ScheduleArg, image: ImageArg, command: CommandArg, suspend: SuspendOpt = None, concurrency: ConcurrencyOpt = None, env: EnvOpt = None, secrets: SecretsOpt = None, label: LabelsOpt = None, volume: VolumesOpt = None, env_file: EnvFileOpt = None, secrets_file: SecretsFileOpt = None, flavor: FlavorOpt = None, timeout: TimeoutOpt = None, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Schedule a Job.""" env_map = parse_env_map(env, env_file) secrets_map = parse_env_map(secrets, secrets_file)
api = get_hf_api(token=token) scheduled_job = api.create_scheduled_job( image=image, command=command, schedule=schedule, suspend=suspend, concurrency=concurrency, env=env_map, secrets=secrets_map, labels=_parse_labels_map(label), volumes=parse_volumes(volume), flavor=flavor, timeout=timeout, namespace=namespace, ) print(f"Scheduled Job created with ID: {scheduled_job.id}")
@scheduled_app.command("ps", examples=["hf jobs scheduled ps"])def scheduled_ps( all: Annotated[ bool, typer.Option( "-a", "--all", help="Show all scheduled Jobs (default hides suspended)", ), ] = False, namespace: NamespaceOpt = None, token: TokenOpt = None, filter: Annotated[ list[str] | None, typer.Option( "-f", "--filter", help="Filter output based on conditions provided (format: key=value)", ), ] = None, format: Annotated[ str | None, typer.Option(help="Output format: 'table' (default), 'json', or a Go template (e.g. '{{.id}}')"), ] = None, quiet: QuietOpt = False,) -> None: """List scheduled Jobs""" api = get_hf_api(token=token) scheduled_jobs = api.list_scheduled_jobs(namespace=namespace) filters: list[tuple[str, str, str]] = [] for f in filter or []: if "=" in f: key, value = f.split("=", 1) # Negate predicate in case of key!=value if key.endswith("!"): op = "!=" key = key[:-1] else: op = "=" filters.append((key.lower(), op, value.lower())) else: print(f"Warning: Ignoring invalid filter format '{f}'. Use key=value format.")
# Filter scheduled jobs (operating on ScheduledJobInfo objects to preserve existing filter behavior) filtered_jobs = [] for scheduled_job in scheduled_jobs: suspend = scheduled_job.suspend or False if not all and suspend: continue image_or_space = scheduled_job.job_spec.docker_image or "N/A" cmd = scheduled_job.job_spec.command or [] command_str = " ".join(cmd) if cmd else "N/A" props = {"id": scheduled_job.id, "image": image_or_space, "suspend": str(suspend), "command": command_str} if not _matches_filters(props, filters): continue filtered_jobs.append(scheduled_job)
if not filtered_jobs: if not quiet and format != "json": filters_msg = f" matching filters: {', '.join([f'{k}{o}{v}' for k, o, v in filters])}" if filters else "" print(f"No scheduled jobs found{filters_msg}") elif format == "json": print("[]") return
headers = ["ID", "SCHEDULE", "IMAGE/SPACE", "COMMAND", "LAST RUN", "NEXT RUN", "SUSPEND"] aliases = ["id", "schedule", "image", "command", "last", "next", "suspend"] items = [api_object_to_dict(sj) for sj in filtered_jobs]
def row_fn(item: dict[str, Any]) -> list[str]: job_spec = item.get("job_spec", {}) status = item.get("status", {}) last_job = status.get("last_job") cmd = job_spec.get("command") or [] last_job_at = "N/A" if last_job and last_job.get("at"): last_job_at = last_job["at"][:19].replace("T", " ") next_run = "N/A" if status.get("next_job_run_at"): next_run = status["next_job_run_at"][:19].replace("T", " ") command_str = " ".join(cmd) if cmd else "N/A" return [ str(item.get("id", "")), str(item.get("schedule") or "N/A"), _format_cell(job_spec.get("docker_image") or "N/A"), _format_cell(command_str), last_job_at, next_run, str(item.get("suspend", False)), ]
# Custom template format (e.g. --format '{{.id}} {{.schedule}}') if format and format not in ("table", "json"): _print_output([row_fn(item) for item in items], headers, aliases, format) # type: ignore else: output_format = OutputFormat.json if format == "json" else OutputFormat.table print_list_output( items=items, format=output_format, quiet=quiet, id_key="id", headers=headers, row_fn=row_fn, )
@scheduled_app.command("inspect", examples=["hf jobs scheduled inspect <id>"])def scheduled_inspect( scheduled_job_ids: Annotated[ list[str], typer.Argument( help="Scheduled Job IDs to inspect (or 'namespace/scheduled_job_id')", ), ], namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Display detailed information on one or more scheduled Jobs""" parsed_ids = [] for job_id in scheduled_job_ids: job_id, namespace = _parse_namespace_from_job_id(job_id, namespace) parsed_ids.append(job_id) scheduled_job_ids = parsed_ids api = get_hf_api(token=token) scheduled_jobs = [ api.inspect_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace) for scheduled_job_id in scheduled_job_ids ] print(json.dumps([asdict(scheduled_job) for scheduled_job in scheduled_jobs], indent=4, default=str))
@scheduled_app.command("delete", examples=["hf jobs scheduled delete <id>"])def scheduled_delete( scheduled_job_id: ScheduledJobIdArg, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Delete a scheduled Job.""" scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace) api = get_hf_api(token=token) api.delete_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
@scheduled_app.command("suspend", examples=["hf jobs scheduled suspend <id>"])def scheduled_suspend( scheduled_job_id: ScheduledJobIdArg, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Suspend (pause) a scheduled Job.""" scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace) api = get_hf_api(token=token) api.suspend_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
@scheduled_app.command("resume", examples=["hf jobs scheduled resume <id>"])def scheduled_resume( scheduled_job_id: ScheduledJobIdArg, namespace: NamespaceOpt = None, token: TokenOpt = None,) -> None: """Resume (unpause) a scheduled Job.""" scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace) api = get_hf_api(token=token) api.resume_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
scheduled_uv_app = typer_factory(help="Schedule UV scripts on HF infrastructure.")scheduled_app.add_typer(scheduled_uv_app, name="uv")
@scheduled_uv_app.command( "run", context_settings={"ignore_unknown_options": True}, examples=[ 'hf jobs scheduled uv run "0 0 * * *" script.py', 'hf jobs scheduled uv run "0 0 * * *" script.py --with pandas', ],)def scheduled_uv_run( schedule: ScheduleArg, script: ScriptArg, script_args: ScriptArgsArg = None, suspend: SuspendOpt = None, concurrency: ConcurrencyOpt = None, image: ImageOpt = None, flavor: FlavorOpt = None, env: EnvOpt = None, secrets: SecretsOpt = None, label: LabelsOpt = None, volume: VolumesOpt = None, env_file: EnvFileOpt = None, secrets_file: SecretsFileOpt = None, timeout: TimeoutOpt = None, namespace: NamespaceOpt = None, token: TokenOpt = None, with_: WithOpt = None, python: PythonOpt = None,) -> None: """Run a UV script (local file or URL) on HF infrastructure""" env_map = parse_env_map(env, env_file) secrets_map = parse_env_map(secrets, secrets_file)
api = get_hf_api(token=token) job = api.create_scheduled_uv_job( script=script, script_args=script_args or [], schedule=schedule, suspend=suspend, concurrency=concurrency, dependencies=with_, python=python, image=image, env=env_map, secrets=secrets_map, labels=_parse_labels_map(label), volumes=parse_volumes(volume), flavor=flavor, # type: ignore[arg-type,misc] timeout=timeout, namespace=namespace, ) print(f"Scheduled Job created with ID: {job.id}")
### UTILS
def _parse_labels_map(labels: list[str] | None) -> dict[str, str] | None: """Parse label key-value pairs from CLI arguments.
Args: labels: List of label strings in KEY=VALUE format. If KEY only, then VALUE is set to empty string.
Returns: Dictionary mapping label keys to values, or None if no labels provided. """ if not labels: return None labels_map: dict[str, str] = {} for label_var in labels: key, value = label_var.split("=", 1) if "=" in label_var else (label_var, "") labels_map[key] = value return labels_map
def _tabulate(rows: list[list[str | int]], headers: list[str]) -> str: """ Inspired by:
- stackoverflow.com/a/8356620/593036 - stackoverflow.com/questions/9535954/printing-lists-as-tabular-data """ col_widths = [max(len(str(x)) for x in col) for col in zip(*rows, headers)] terminal_width = max(shutil.get_terminal_size().columns, len(headers) * 12) while len(headers) + sum(col_widths) > terminal_width: col_to_minimize = col_widths.index(max(col_widths)) col_widths[col_to_minimize] //= 2 if len(headers) + sum(col_widths) <= terminal_width: col_widths[col_to_minimize] = terminal_width - sum(col_widths) - len(headers) + col_widths[col_to_minimize] row_format = ("{{:{}}} " * len(headers)).format(*col_widths) lines = [] lines.append(row_format.format(*headers)) lines.append(row_format.format(*["-" * w for w in col_widths])) for row in rows: row_format_args = [ str(x)[: col_width - 3] + "..." if len(str(x)) > col_width else str(x) for x, col_width in zip(row, col_widths) ] lines.append(row_format.format(*row_format_args)) return "\n".join(lines)
T = TypeVar("T")
def _write_generator_to_queue(queue: Queue[T], func: Callable[..., Iterable[T]], kwargs: dict) -> None: for result in func(**kwargs): queue.put(result)
def iflatmap_unordered( pool: multiprocessing.pool.ThreadPool, func: Callable[..., Iterable[T]], *, kwargs_list: list[dict],) -> Iterable[T]: """ Takes a function that returns an iterable of items, and run it in parallel using threads to return the flattened iterable of items as they arrive.
This is inspired by those three `map()` variants, and is the mix of all three:
* `imap()`: like `map()` but returns an iterable instead of a list of results * `imap_unordered()`: like `imap()` but the output is sorted by time of arrival * `flatmap()`: like `map()` but given a function which returns a list, `flatmap()` returns the flattened list that is the concatenation of all the output lists """ queue: Queue[T] = Queue() async_results = [pool.apply_async(_write_generator_to_queue, (queue, func, kwargs)) for kwargs in kwargs_list] try: while True: try: yield queue.get(timeout=0.05) except Empty: if all(async_result.ready() for async_result in async_results) and queue.empty(): break except KeyboardInterrupt: pass finally: # we get the result in case there's an error to raise try: [async_result.get(timeout=0.05) for async_result in async_results] except multiprocessing.TimeoutError: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"""Implementation of a custom transfer agent for the transfer type "multipart" forgit-lfs.
Inspired by:github.com/cbartz/git-lfs-swift-transfer-agent/blob/master/git_lfs_swift_transfer.py
Spec is: github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md
To launch debugger while developing:
``` [lfs "customtransfer.multipart"]path = /path/to/huggingface_hub/.venv/bin/python args = -m debugpy --listen 5678--wait-for-client/path/to/huggingface_hub/src/huggingface_hub/commands/huggingface_cli.pylfs-multipart-upload ```"""
import jsonimport osimport subprocessimport sysfrom typing import Annotated
import typer
from huggingface_hub.errors import CLIErrorfrom huggingface_hub.lfs import LFS_MULTIPART_UPLOAD_COMMAND
from ..utils import get_session, hf_raise_for_status, loggingfrom ..utils._lfs import SliceFileObj
logger = logging.get_logger(__name__)
def lfs_enable_largefiles( path: Annotated[ str, typer.Argument( help="Local path to repository you want to configure.", ), ],) -> None: """ Configure your repository to enable upload of files > 5GB.
This command sets up git-lfs to use the custom multipart transfer agent which enables efficient uploading of large files in chunks. """ local_path = os.path.abspath(path) if not os.path.isdir(local_path): raise CLIError("This does not look like a valid git repo.") subprocess.run( "git config lfs.customtransfer.multipart.path hf".split(), check=True, cwd=local_path, ) subprocess.run( f"git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}".split(), check=True, cwd=local_path, ) print("Local repo set up for largefiles")
def write_msg(msg: dict): """Write out the message in Line delimited JSON.""" msg_str = json.dumps(msg) + "\n" sys.stdout.write(msg_str) sys.stdout.flush()
def read_msg() -> dict | None: """Read Line delimited JSON from stdin.""" msg = json.loads(sys.stdin.readline().strip())
if "terminate" in (msg.get("type"), msg.get("event")): # terminate message received return None
if msg.get("event") not in ("download", "upload"): logger.critical("Received unexpected message") sys.exit(1)
return msg
def lfs_multipart_upload() -> None: """Internal git-lfs custom transfer agent for multipart uploads.
This function implements the custom transfer protocol for git-lfs multipart uploads. Handles chunked uploads of large files to Hugging Face Hub. """ # Immediately after invoking a custom transfer process, git-lfs # sends initiation data to the process over stdin. # This tells the process useful information about the configuration. init_msg = json.loads(sys.stdin.readline().strip()) if not (init_msg.get("event") == "init" and init_msg.get("operation") == "upload"): write_msg({"error": {"code": 32, "message": "Wrong lfs init operation"}}) sys.exit(1)
# The transfer process should use the information it needs from the # initiation structure, and also perform any one-off setup tasks it # needs to do. It should then respond on stdout with a simple empty # confirmation structure, as follows: write_msg({})
# After the initiation exchange, git-lfs will send any number of # transfer requests to the stdin of the transfer process, in a serial sequence. while True: msg = read_msg() if msg is None: # When all transfers have been processed, git-lfs will send # a terminate event to the stdin of the transfer process. # On receiving this message the transfer process should # clean up and terminate. No response is expected. sys.exit(0)
oid = msg["oid"] filepath = msg["path"] completion_url = msg["action"]["href"] header = msg["action"]["header"] chunk_size = int(header.pop("chunk_size")) presigned_urls: list[str] = list(header.values())
# Send a "started" progress event to allow other workers to start. # Otherwise they're delayed until first "progress" event is reported, # i.e. after the first 5GB by default (!) write_msg( { "event": "progress", "oid": oid, "bytesSoFar": 1, "bytesSinceLast": 0, } )
parts = [] with open(filepath, "rb") as file: for i, presigned_url in enumerate(presigned_urls): with SliceFileObj( file, seek_from=i * chunk_size, read_limit=chunk_size, ) as data: r = get_session().put(presigned_url, data=data) hf_raise_for_status(r) parts.append( { "etag": r.headers.get("etag"), "partNumber": i + 1, } ) # In order to support progress reporting while data is uploading / downloading, # the transfer process should post messages to stdout write_msg( { "event": "progress", "oid": oid, "bytesSoFar": (i + 1) * chunk_size, "bytesSinceLast": chunk_size, } )
r = get_session().post( completion_url, json={ "oid": oid, "parts": parts, }, ) hf_raise_for_status(r)
write_msg({"event": "complete", "oid": oid})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with models on the Hugging Face Hub.
Usage: # list models on the Hub hf models ls
# list models with a search query hf models ls --search "llama"
# get info about a model hf models info Lightricks/LTX-2"""
import enumfrom typing import Annotated, get_args
import typer
from huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundErrorfrom huggingface_hub.hf_api import ExpandModelProperty_T, ModelSort_T
from ._cli_utils import ( AuthorOpt, FilterOpt, FormatWithAutoOpt, LimitOpt, RevisionOpt, SearchOpt, TokenOpt, api_object_to_dict, get_hf_api, make_expand_properties_parser, typer_factory,)from ._output import OutputFormatWithAuto, out
_EXPAND_PROPERTIES = sorted(get_args(ExpandModelProperty_T))_SORT_OPTIONS = get_args(ModelSort_T)ModelSortEnum = enum.Enum("ModelSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
ExpandOpt = Annotated[ str | None, typer.Option( help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=downloads,likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.", callback=make_expand_properties_parser(_EXPAND_PROPERTIES), ),]
models_cli = typer_factory(help="Interact with models on the Hub.")
@models_cli.command( "list | ls", examples=[ "hf models ls --sort downloads --limit 10", 'hf models ls --search "llama" --author meta-llama', "hf models ls --num-parameters min:6B,max:128B --sort likes", ],)def models_ls( search: SearchOpt = None, author: AuthorOpt = None, filter: FilterOpt = None, num_parameters: Annotated[ str | None, typer.Option(help="Filter by parameter count, e.g. 'min:6B,max:128B'."), ] = None, sort: Annotated[ ModelSortEnum | None, typer.Option(help="Sort results."), ] = None, limit: LimitOpt = 10, expand: ExpandOpt = None, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """List models on the Hub.""" api = get_hf_api(token=token) sort_key = sort.value if sort else None results = [ api_object_to_dict(model_info) for model_info in api.list_models( filter=filter, author=author, search=search, num_parameters=num_parameters, sort=sort_key, limit=limit, expand=expand, # type: ignore ) ] out.table(results)
@models_cli.command( "info", examples=[ "hf models info meta-llama/Llama-3.2-1B-Instruct", "hf models info Qwen/Qwen3.5-9B --expand downloads,likes,tags", ],)def models_info( model_id: Annotated[str, typer.Argument(help="The model ID (e.g. `username/repo-name`).")], revision: RevisionOpt = None, expand: ExpandOpt = None, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """Get info about a model on the Hub.""" api = get_hf_api(token=token) try: info = api.model_info(repo_id=model_id, revision=revision, expand=expand) # type: ignore except RepositoryNotFoundError as e: raise CLIError(f"Model '{model_id}' not found.") from e except RevisionNotFoundError as e: raise CLIError(f"Revision '{revision}' not found on '{model_id}'.") from e out.dict(info)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with papers on the Hugging Face Hub.
Usage: # list daily papers (most recently submitted) hf papers ls
# list trending papers hf papers ls --sort=trending
# list papers from a specific date, ordered by upvotes hf papers ls --date=2025-01-23
# list today's papers, ordered by upvotes hf papers ls --date=today
# list papers from a specific week hf papers ls --week=2025-W09
# list papers by a specific submitter hf papers ls --submitter=someuser
# search papers hf papers search "vision language"
# get info about a paper hf papers info 2502.08025
# read a paper as markdown hf papers read 2502.08025"""
import datetimeimport enumfrom typing import Annotated, get_args
import typer
from huggingface_hub.errors import CLIError, HfHubHTTPErrorfrom huggingface_hub.hf_api import DailyPapersSort_T
from ._cli_utils import ( FormatWithAutoOpt, LimitOpt, TokenOpt, api_object_to_dict, get_hf_api, typer_factory,)from ._output import OutputFormatWithAuto, out
_SORT_OPTIONS = get_args(DailyPapersSort_T)PaperSortEnum = enum.Enum("PaperSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
def _parse_date(value: str | None) -> str | None: """Parse date option, converting 'today' to current date.""" if value is None: return None if value.lower() == "today": return datetime.date.today().isoformat() return value
papers_cli = typer_factory(help="Interact with papers on the Hub.")
@papers_cli.command( "list | ls", examples=[ "hf papers ls", "hf papers ls --sort trending", "hf papers ls --date 2025-01-23", "hf papers ls --week 2025-W09", "hf papers ls --submitter akhaliq", "hf papers ls --format json", ],)def papers_ls( date: Annotated[ str | None, typer.Option( help="Date in ISO format (YYYY-MM-DD) or 'today'.", callback=_parse_date, ), ] = None, week: Annotated[ str | None, typer.Option(help="ISO week to filter by, e.g. '2025-W09'."), ] = None, month: Annotated[ str | None, typer.Option(help="Month to filter by in ISO format (YYYY-MM), e.g. '2025-02'."), ] = None, submitter: Annotated[ str | None, typer.Option(help="Filter by username of the submitter."), ] = None, sort: Annotated[ PaperSortEnum | None, typer.Option(help="Sort results."), ] = None, limit: LimitOpt = 50, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """List daily papers on the Hub.""" api = get_hf_api(token=token) sort_key = sort.value if sort else None results = [] for paper_info in api.list_daily_papers( date=date, week=week, month=month, submitter=submitter, sort=sort_key, limit=limit, ): item = api_object_to_dict(paper_info) submitted_by = item.get("submitted_by") or {} item["submitted_by_name"] = submitted_by.get("fullname") or submitted_by.get("username") or "" results.append(item) out.table( results, headers=["id", "title", "upvotes", "comments", "published_at", "submitted_by_name"], alignments={"upvotes": "right", "comments": "right"}, )
@papers_cli.command( "search", examples=[ 'hf papers search "vision language"', 'hf papers search "attention mechanism" --limit 10', 'hf papers search "diffusion" --format json', ],)def papers_search( query: Annotated[str, typer.Argument(help="Search query string.")], limit: LimitOpt = 20, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """Search papers on the Hub.""" api = get_hf_api(token=token) results = [api_object_to_dict(paper_info) for paper_info in api.list_papers(query=query, limit=limit)] out.table(results, headers=["id", "title", "summary", "upvotes", "published_at"], alignments={"upvotes": "right"})
@papers_cli.command( "info", examples=[ "hf papers info 2601.15621", ],)def papers_info( paper_id: Annotated[str, typer.Argument(help="The arXiv paper ID (e.g. '2502.08025').")], format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """Get info about a paper on the Hub.""" api = get_hf_api(token=token) try: info = api.paper_info(id=paper_id) except HfHubHTTPError as e: if e.response.status_code == 404: raise CLIError(f"Paper '{paper_id}' not found on the Hub.") from e raise out.dict(info)
@papers_cli.command( "read", examples=[ "hf papers read 2601.15621", ],)def papers_read( paper_id: Annotated[str, typer.Argument(help="The arXiv paper ID (e.g. '2502.08025').")], token: TokenOpt = None,) -> None: """Read a paper as markdown.""" api = get_hf_api(token=token) try: content = api.read_paper(id=paper_id) except HfHubHTTPError as e: if e.response.status_code == 404: raise CLIError(f"Paper '{paper_id}' not found on the Hub.") from e raise out.text(content)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Copyright 2023-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Legacy `hf repo-files` command.
Kept for backward compatibility. Users are nudged to use `hf repos delete-files` instead."""
import sysfrom typing import Annotated
import typer
from huggingface_hub import loggingfrom huggingface_hub.utils import ANSI
from ._cli_utils import RepoIdArg, RepoType, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api, typer_factory
logger = logging.get_logger(__name__)
repo_files_cli = typer_factory( help="(Deprecated) Manage files in a repo on the Hub. Use `hf repos delete-files` instead.")
@repo_files_cli.command( "delete",)def repo_files_delete( repo_id: RepoIdArg, patterns: Annotated[ list[str], typer.Argument( help="Glob patterns to match files to delete. Based on fnmatch, '*' matches files recursively.", ), ], repo_type: RepoTypeOpt = RepoType.model, revision: RevisionOpt = None, commit_message: Annotated[ str | None, typer.Option( help="The summary / title / first line of the generated commit.", ), ] = None, commit_description: Annotated[ str | None, typer.Option( help="The description of the generated commit.", ), ] = None, create_pr: Annotated[ bool, typer.Option( help="Whether to create a new Pull Request for these changes.", ), ] = False, token: TokenOpt = None,) -> None: print( ANSI.yellow("FutureWarning: `hf repo-files delete` is deprecated. Use `hf repos delete-files` instead."), file=sys.stderr, ) api = get_hf_api(token=token) url = api.delete_files( delete_patterns=patterns, repo_id=repo_id, repo_type=repo_type.value, revision=revision, commit_message=commit_message, commit_description=commit_description, create_pr=create_pr, ) print(f"Files correctly deleted from repo. Commit: {url}.") logging.set_verbosity_warning()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with repositories on the Hugging Face Hub.
Usage: # create a new dataset repo on the Hub hf repos create my-cool-dataset --repo-type=dataset
# create a private model repo on the Hub hf repos create my-cool-model --private
# delete files from a repo on the Hub hf repos delete-files my-model file.txt"""
import enumimport sysfrom typing import Annotated
import typer
from huggingface_hub import SpaceHardware, SpaceStoragefrom huggingface_hub.errors import CLIError, HfHubHTTPError, RepositoryNotFoundError, RevisionNotFoundErrorfrom huggingface_hub.utils import ANSI
from ._cli_utils import ( EnvFileOpt, EnvOpt, PrivateOpt, RepoIdArg, RepoType, RepoTypeOpt, RevisionOpt, SecretsFileOpt, SecretsOpt, TokenOpt, VolumesOpt, env_map_to_key_value_list, get_hf_api, parse_env_map, parse_volumes, typer_factory,)
repos_cli = typer_factory(help="Manage repos on the Hub.")
@repos_cli.callback(invoke_without_command=True)def _repos_callback(ctx: typer.Context) -> None: if ctx.info_name == "repo": print( ANSI.yellow("FutureWarning: `hf repo` is deprecated in favor of `hf repos`."), file=sys.stderr, )
tag_cli = typer_factory(help="Manage tags for a repo on the Hub.")branch_cli = typer_factory(help="Manage branches for a repo on the Hub.")repos_cli.add_typer(tag_cli, name="tag")repos_cli.add_typer(branch_cli, name="branch")
class GatedChoices(str, enum.Enum): auto = "auto" manual = "manual" false = "false"
PublicOpt = Annotated[ bool | None, typer.Option( "--public", help="Whether to make the repo public. Ignored if the repo already exists.", ),]
ProtectedOpt = Annotated[ bool | None, typer.Option( "--protected", help="Whether to make the Space protected (Spaces only). Ignored if the repo already exists.", ),]SpaceHardwareOpt = Annotated[ SpaceHardware | None, typer.Option( "--flavor", help="Space hardware flavor (e.g. 'cpu-basic', 't4-medium', 'l4x4'). Only for Spaces.", ),]
SpaceStorageOpt = Annotated[ SpaceStorage | None, typer.Option( "--storage", help="(Deprecated, use volumes instead) Space persistent storage tier ('small', 'medium', or 'large'). Only for Spaces.", ),]
SpaceSleepTimeOpt = Annotated[ int | None, typer.Option( "--sleep-time", help="Seconds of inactivity before the Space is put to sleep. Use -1 to disable. Only for Spaces.", ),]
@repos_cli.command( "create", examples=[ "hf repos create my-model", "hf repos create my-dataset --repo-type dataset --private", "hf repos create my-space --type space --space-sdk gradio --flavor t4-medium --secrets HF_TOKEN -e THEME=dark --protected", "hf repos create my-space --type space --space-sdk gradio -v hf://gpt2:/models -v hf://buckets/org/b:/data", ],)def repo_create( repo_id: RepoIdArg, repo_type: RepoTypeOpt = RepoType.model, space_sdk: Annotated[ str | None, typer.Option( help="Hugging Face Spaces SDK type. Required when --type is set to 'space'.", ), ] = None, private: PrivateOpt = None, public: PublicOpt = None, protected: ProtectedOpt = None, token: TokenOpt = None, exist_ok: Annotated[ bool, typer.Option( help="Do not raise an error if repo already exists.", ), ] = False, resource_group_id: Annotated[ str | None, typer.Option( help="Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations.", ), ] = None, hardware: SpaceHardwareOpt = None, storage: SpaceStorageOpt = None, sleep_time: SpaceSleepTimeOpt = None, secrets: SecretsOpt = None, secrets_file: SecretsFileOpt = None, env: EnvOpt = None, env_file: EnvFileOpt = None, volume: VolumesOpt = None,) -> None: """Create a new repo on the Hub.""" api = get_hf_api(token=token) repo_url = api.create_repo( repo_id=repo_id, repo_type=repo_type.value, visibility="private" if private else "public" if public else "protected" if protected else None, # type: ignore [arg-type] token=token, exist_ok=exist_ok, resource_group_id=resource_group_id, space_sdk=space_sdk, space_hardware=hardware, space_storage=storage, space_sleep_time=sleep_time, space_secrets=env_map_to_key_value_list(parse_env_map(secrets, secrets_file)), space_variables=env_map_to_key_value_list(parse_env_map(env, env_file)), space_volumes=parse_volumes(volume), ) print(f"Successfully created {ANSI.bold(repo_url.repo_id)} on the Hub.") print(f"Your repo is now available at {ANSI.bold(repo_url)}")
@repos_cli.command( "duplicate", examples=[ "hf repos duplicate openai/gdpval --type dataset", "hf repos duplicate multimodalart/dreambooth-training my-dreambooth --type space --flavor l4x4 --secrets HF_TOKEN --private", "hf repos duplicate org/my-space my-space --type space -v hf://gpt2:/models -v hf://buckets/org/b:/data", ],)def repo_duplicate( from_id: RepoIdArg, to_id: Annotated[ str | None, typer.Argument( help="Destination repo ID (e.g. `myorg/my-copy`). Defaults to your namespace with the same repo name.", ), ] = None, repo_type: RepoTypeOpt = RepoType.model, private: PrivateOpt = None, public: PublicOpt = None, protected: ProtectedOpt = None, token: TokenOpt = None, exist_ok: Annotated[ bool, typer.Option( help="Do not raise an error if repo already exists.", ), ] = False, hardware: SpaceHardwareOpt = None, storage: SpaceStorageOpt = None, sleep_time: SpaceSleepTimeOpt = None, secrets: SecretsOpt = None, secrets_file: SecretsFileOpt = None, env: EnvOpt = None, env_file: EnvFileOpt = None, volume: VolumesOpt = None,) -> None: """Duplicate a repo on the Hub (model, dataset, or Space).""" api = get_hf_api(token=token) repo_url = api.duplicate_repo( from_id=from_id, to_id=to_id, repo_type=repo_type.value, visibility="private" if private else "public" if public else "protected" if protected else None, # type: ignore [arg-type] token=token, exist_ok=exist_ok, space_hardware=hardware, space_storage=storage, space_sleep_time=sleep_time, space_secrets=env_map_to_key_value_list(parse_env_map(secrets, secrets_file)), space_variables=env_map_to_key_value_list(parse_env_map(env, env_file)), space_volumes=parse_volumes(volume), ) print(f"Successfully duplicated {ANSI.bold(from_id)} to {ANSI.bold(repo_url.repo_id)} on the Hub.") print(f"Your repo is now available at {ANSI.bold(repo_url)}")
@repos_cli.command("delete", examples=["hf repos delete my-model"])def repo_delete( repo_id: RepoIdArg, repo_type: RepoTypeOpt = RepoType.model, token: TokenOpt = None, missing_ok: Annotated[ bool, typer.Option( help="If set to True, do not raise an error if repo does not exist.", ), ] = False,) -> None: """Delete a repo from the Hub. This is an irreversible operation.""" api = get_hf_api(token=token) api.delete_repo( repo_id=repo_id, repo_type=repo_type.value, missing_ok=missing_ok, ) print(f"Successfully deleted {ANSI.bold(repo_id)} on the Hub.")
@repos_cli.command("move", examples=["hf repos move old-namespace/my-model new-namespace/my-model"])def repo_move( from_id: RepoIdArg, to_id: RepoIdArg, token: TokenOpt = None, repo_type: RepoTypeOpt = RepoType.model,) -> None: """Move a repository from a namespace to another namespace.""" api = get_hf_api(token=token) api.move_repo( from_id=from_id, to_id=to_id, repo_type=repo_type.value, ) print(f"Successfully moved {ANSI.bold(from_id)} to {ANSI.bold(to_id)} on the Hub.")
@repos_cli.command( "settings", examples=[ "hf repos settings my-model --private", "hf repos settings my-model --gated auto", "hf repos settings my-space --repo-type space --protected", ],)def repo_settings( repo_id: RepoIdArg, gated: Annotated[ GatedChoices | None, typer.Option( help="The gated status for the repository.", ), ] = None, private: PrivateOpt = None, public: PublicOpt = None, protected: ProtectedOpt = None, token: TokenOpt = None, repo_type: RepoTypeOpt = RepoType.model,) -> None: """Update the settings of a repository.""" api = get_hf_api(token=token) api.update_repo_settings( repo_id=repo_id, gated=(None if gated is None else False if gated is GatedChoices.false else gated.value), visibility="private" if private else "public" if public else "protected" if protected else None, # type: ignore [arg-type] repo_type=repo_type.value, ) print(f"Successfully updated the settings of {ANSI.bold(repo_id)} on the Hub.")
@repos_cli.command( "delete-files", examples=[ "hf repos delete-files my-model file.txt", 'hf repos delete-files my-model "*.json"', "hf repos delete-files my-model folder/", ],)def repo_delete_files( repo_id: RepoIdArg, patterns: Annotated[ list[str], typer.Argument( help="Glob patterns to match files to delete. Based on fnmatch, '*' matches files recursively.", ), ], repo_type: RepoTypeOpt = RepoType.model, revision: RevisionOpt = None, commit_message: Annotated[ str | None, typer.Option( help="The summary / title / first line of the generated commit.", ), ] = None, commit_description: Annotated[ str | None, typer.Option( help="The description of the generated commit.", ), ] = None, create_pr: Annotated[ bool, typer.Option( help="Whether to create a new Pull Request for these changes.", ), ] = False, token: TokenOpt = None,) -> None: """Delete files from a repo on the Hub.""" api = get_hf_api(token=token) url = api.delete_files( delete_patterns=patterns, repo_id=repo_id, repo_type=repo_type.value, revision=revision, commit_message=commit_message, commit_description=commit_description, create_pr=create_pr, ) print(f"Files correctly deleted from repo. Commit: {url}.")
@branch_cli.command( "create", examples=[ "hf repos branch create my-model dev", "hf repos branch create my-model dev --revision abc123", ],)def branch_create( repo_id: RepoIdArg, branch: Annotated[ str, typer.Argument( help="The name of the branch to create.", ), ], revision: RevisionOpt = None, token: TokenOpt = None, repo_type: RepoTypeOpt = RepoType.model, exist_ok: Annotated[ bool, typer.Option( help="If set to True, do not raise an error if branch already exists.", ), ] = False,) -> None: """Create a new branch for a repo on the Hub.""" api = get_hf_api(token=token) api.create_branch( repo_id=repo_id, branch=branch, revision=revision, repo_type=repo_type.value, exist_ok=exist_ok, ) print(f"Successfully created {ANSI.bold(branch)} branch on {repo_type.value} {ANSI.bold(repo_id)}")
@branch_cli.command("delete", examples=["hf repos branch delete my-model dev"])def branch_delete( repo_id: RepoIdArg, branch: Annotated[ str, typer.Argument( help="The name of the branch to delete.", ), ], token: TokenOpt = None, repo_type: RepoTypeOpt = RepoType.model,) -> None: """Delete a branch from a repo on the Hub.""" api = get_hf_api(token=token) api.delete_branch( repo_id=repo_id, branch=branch, repo_type=repo_type.value, ) print(f"Successfully deleted {ANSI.bold(branch)} branch on {repo_type.value} {ANSI.bold(repo_id)}")
@tag_cli.command( "create", examples=[ "hf repos tag create my-model v1.0", 'hf repos tag create my-model v1.0 -m "First release"', ],)def tag_create( repo_id: RepoIdArg, tag: Annotated[ str, typer.Argument( help="The name of the tag to create.", ), ], message: Annotated[ str | None, typer.Option( "-m", "--message", help="The description of the tag to create.", ), ] = None, revision: RevisionOpt = None, token: TokenOpt = None, repo_type: RepoTypeOpt = RepoType.model,) -> None: """Create a tag for a repo.""" repo_type_str = repo_type.value api = get_hf_api(token=token) print(f"You are about to create tag {ANSI.bold(tag)} on {repo_type_str} {ANSI.bold(repo_id)}") try: api.create_tag(repo_id=repo_id, tag=tag, tag_message=message, revision=revision, repo_type=repo_type_str) except RepositoryNotFoundError as e: raise CLIError(f"{repo_type_str.capitalize()} '{repo_id}' not found.") from e except RevisionNotFoundError as e: raise CLIError(f"Revision '{revision}' not found.") from e except HfHubHTTPError as e: if e.response.status_code == 409: raise CLIError(f"Tag '{tag}' already exists on '{repo_id}'.") from e raise print(f"Tag {ANSI.bold(tag)} created on {ANSI.bold(repo_id)}")
@tag_cli.command("list | ls", examples=["hf repos tag list my-model"])def tag_list( repo_id: RepoIdArg, token: TokenOpt = None, repo_type: RepoTypeOpt = RepoType.model,) -> None: """List tags for a repo.""" repo_type_str = repo_type.value api = get_hf_api(token=token) try: refs = api.list_repo_refs(repo_id=repo_id, repo_type=repo_type_str) except RepositoryNotFoundError as e: raise CLIError(f"{repo_type_str.capitalize()} '{repo_id}' not found.") from e if len(refs.tags) == 0: print("No tags found") raise typer.Exit(code=0) print(f"Tags for {repo_type_str} {ANSI.bold(repo_id)}:") for t in refs.tags: print(t.name)
@tag_cli.command("delete", examples=["hf repos tag delete my-model v1.0"])def tag_delete( repo_id: RepoIdArg, tag: Annotated[ str, typer.Argument( help="The name of the tag to delete.", ), ], yes: Annotated[ bool, typer.Option( "-y", "--yes", help="Answer Yes to prompt automatically", ), ] = False, token: TokenOpt = None, repo_type: RepoTypeOpt = RepoType.model,) -> None: """Delete a tag for a repo.""" repo_type_str = repo_type.value print(f"You are about to delete tag {ANSI.bold(tag)} on {repo_type_str} {ANSI.bold(repo_id)}") if not yes: choice = input("Proceed? [Y/n] ").lower() if choice not in ("", "y", "yes"): print("Abort") raise typer.Exit() api = get_hf_api(token=token) try: api.delete_tag(repo_id=repo_id, tag=tag, repo_type=repo_type_str) except RepositoryNotFoundError as e: raise CLIError(f"{repo_type_str.capitalize()} '{repo_id}' not found.") from e except RevisionNotFoundError as e: raise CLIError(f"Tag '{tag}' not found on '{repo_id}'.") from e print(f"Tag {ANSI.bold(tag)} deleted on {ANSI.bold(repo_id)}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to manage skills for AI assistants.
Usage: # install the hf-cli skill in common .agents/skills directory (either in current directory or user-level) hf skills add hf skills add --global
# install the hf-cli skill for Claude (project-level, in current directory) hf skills add --claude
# install globally (user-level) hf skills add --claude --global
# install to a custom directory hf skills add --dest=~/my-skills
# overwrite an existing skill hf skills add --claude --force"""
import osimport shutilfrom pathlib import Pathfrom typing import Annotated
import typerfrom click import Command, Context, Groupfrom typer.main import get_command
from huggingface_hub.errors import CLIError
from . import _skillsfrom ._cli_utils import typer_factory
DEFAULT_SKILL_ID = "hf-cli"
_SKILL_DESCRIPTION = ( "Hugging Face Hub CLI (`hf`) for downloading, uploading, and managing" " models, datasets, spaces, buckets, repos, papers, jobs, and more on the Hugging Face Hub." " Use when: handling authentication;" " managing local cache;" " managing Hugging Face Buckets;" " running or scheduling jobs on Hugging Face infrastructure;" " managing Hugging Face repos;" " discussions and pull requests;" " browsing models, datasets and spaces;" " reading, searching, or browsing academic papers;" " managing collections;" " querying datasets;" " configuring spaces;" " setting up webhooks;" " or deploying and managing HF Inference Endpoints." " Make sure to use this skill whenever the user mentions" " 'hf', 'huggingface', 'Hugging Face', 'huggingface-cli', or 'hugging face cli'," " or wants to do anything related to the Hugging Face ecosystem and to AI and ML in general." " Also use for cloud storage needs like training checkpoints, data pipelines, or agent traces." " Use even if the user doesn't explicitly ask for a CLI command." " Replaces the deprecated `huggingface-cli`.")
_SKILL_YAML_PREFIX = f"""\---name: hf-clidescription: "{_SKILL_DESCRIPTION}"---
Install: `curl -LsSf https://hf.co/cli/install.sh | bash -s`.
The Hugging Face Hub CLI tool `hf` is available. IMPORTANT: The `hf` command replaces the deprecated `huggingface-cli` command.
Use `hf --help` to view available functions. Note that auth commands are now all under `hf auth` e.g. `hf auth whoami`."""
_SKILL_TIPS = """## Mounting repos as local filesystems
To mount Hub repositories or buckets as local filesystems — no download, no copy, no waiting — use `hf-mount`. Files are fetched on demand. GitHub: https://github.com/huggingface/hf-mount
Install: `curl -fsSL https://raw.githubusercontent.com/huggingface/hf-mount/main/install.sh | sh`
Some command examples:- `hf-mount start repo openai-community/gpt2 /tmp/gpt2` — mount a repo (read-only)- `hf-mount start --hf-token $HF_TOKEN bucket myuser/my-bucket /tmp/data` — mount a bucket (read-write)- `hf-mount status` / `hf-mount stop /tmp/data` — list or unmount
## Tips
- Use `hf <command> --help` for full options, descriptions, usage, and real-world examples- Authenticate with `HF_TOKEN` env var (recommended) or with `--token`"""
CENTRAL_LOCAL = Path(".agents/skills")CENTRAL_GLOBAL = Path("~/.agents/skills")CLAUDE_LOCAL = Path(".claude/skills")CLAUDE_GLOBAL = Path("~/.claude/skills")# Flags worth explaining in the common-options glossary. Self-explanatory flags# (--namespace, --yes, --private, …) are omitted even if they appear frequently._COMMON_FLAG_ALLOWLIST = {"--token", "--quiet", "--type", "--format", "--revision"}# Keep token out of inline command signatures to encourage env based auth._INLINE_FLAG_EXCLUDE = {"--token"}
_COMMON_FLAG_HELP_OVERRIDES: dict[str, str] = { "--format": "Output format: `--format json` (or `--json`) or `--format table` (default).", "--token": "Use a User Access Token. Prefer setting `HF_TOKEN` env var instead of passing `--token`.",}
skills_cli = typer_factory(help="Manage skills for AI assistants.")
def _format_params(cmd: Command) -> str: """Format required params: positional as UPPER_CASE, options as ``--name TYPE``.""" parts = [] for p in cmd.params: if not p.required or p.human_readable_name == "--help": continue if p.name and p.name.startswith("_"): continue long_name = next((o for o in getattr(p, "opts", []) if o.startswith("--")), None) if long_name is not None: type_name = getattr(p.type, "name", "").upper() or "VALUE" parts.append(f"{long_name} {type_name}") elif p.name: parts.append(p.human_readable_name) return " ".join(parts)
def _collect_leaf_commands(group: Group, ctx: Context, path_parts: list[str]) -> list[tuple[list[str], Command]]: """Recursively walk a Click Group, returning (full_path_parts, cmd) for every leaf command.""" leaves: list[tuple[list[str], Command]] = [] sub_ctx = Context(group, parent=ctx, info_name=path_parts[-1]) for name in group.list_commands(sub_ctx): cmd = group.get_command(sub_ctx, name) if cmd is None or cmd.hidden: continue child_path = [*path_parts, name] if isinstance(cmd, Group): leaves.extend(_collect_leaf_commands(cmd, sub_ctx, child_path)) else: leaves.append((child_path, cmd)) return leaves
def _iter_optional_params(cmd: Command): """Yield (param, long_name, short_name) for each optional, non-internal param.""" for p in cmd.params: if p.required or p.human_readable_name == "--help": continue if p.name and p.name.startswith("_"): continue long_name = None short_name = None for opt in getattr(p, "opts", []): if opt.startswith("--"): long_name = long_name or opt elif opt.startswith("-"): short_name = opt if long_name: yield p, long_name, short_name
def _get_flag_names(cmd: Command, *, exclude: set[str] | None = None) -> list[str]: """Return long-form flag names (--foo) for optional, non-internal params.
Boolean flags are bare (``--dry-run``). Value-taking options include a type hint (``--include TEXT``, ``--max-workers INTEGER``). """ flags: list[str] = [] for p, long_name, _short in _iter_optional_params(cmd): if exclude and long_name in exclude: continue if getattr(p, "is_flag", False): flags.append(long_name) else: type_name = getattr(p.type, "name", "").upper() or "VALUE" flags.append(f"{long_name} {type_name}") return flags
def _compute_common_flags( leaf_commands: list[tuple[list[str], Command]],) -> dict[str, tuple[str, str]]: """Collect display info for flags in the allowlist.""" flag_info: dict[str, tuple[str, str]] = {}
for _path, cmd in leaf_commands: for p, long_name, short_name in _iter_optional_params(cmd): if long_name not in _COMMON_FLAG_ALLOWLIST: continue # Prefer the version with a short form (e.g. "-q / --quiet" over just "--quiet") if long_name not in flag_info or (short_name and " / " not in flag_info[long_name][0]): display = f"{short_name} / {long_name}" if short_name else long_name help_text = (getattr(p, "help", None) or "").split("\n")[0].strip() flag_info[long_name] = (display, help_text)
return flag_info
def _render_leaf(path_parts: list[str], cmd: Command) -> str: """Render a single leaf command as a markdown list entry.""" help_text = (cmd.help or "").split("\n")[0].strip() params = _format_params(cmd) parts = ["hf", *path_parts] + ([params] if params else []) entry = f"- `{' '.join(parts)}` — {help_text}" flags = _get_flag_names(cmd, exclude=_INLINE_FLAG_EXCLUDE) if flags: entry += f" `[{' '.join(flags)}]`" return entry
def build_skill_md() -> str: # Lazy import to avoid circular dependency (hf.py imports skills_cli from this module) from huggingface_hub import __version__ from huggingface_hub.cli.hf import app
click_app = get_command(app) ctx = Context(click_app, info_name="hf")
top_level: list[tuple[list[str], Command]] = [] groups: list[tuple[str, Group]] = [] for name in sorted(click_app.list_commands(ctx)): # type: ignore[attr-defined] cmd = click_app.get_command(ctx, name) # type: ignore[attr-defined] if cmd is None or cmd.hidden: continue if isinstance(cmd, Group): groups.append((name, cmd)) else: top_level.append(([name], cmd))
group_leaves: list[tuple[str, list[tuple[list[str], Command]]]] = [] all_leaf_commands: list[tuple[list[str], Command]] = list(top_level) for name, group in groups: leaves = _collect_leaf_commands(group, ctx, [name]) group_leaves.append((name, leaves)) all_leaf_commands.extend(leaves)
common_flags = _compute_common_flags(all_leaf_commands)
# wrap in list to widen list[LiteralString] -> list[str] for `ty` lines: list[str] = list(_SKILL_YAML_PREFIX.splitlines()) lines.append("") lines.append(f"Generated with `huggingface_hub v{__version__}`. Run `hf skills add --force` to regenerate.") lines.append("") lines.append("## Commands") lines.append("")
for path_parts, cmd in top_level: lines.append(_render_leaf(path_parts, cmd))
groups_dict = dict(groups) for name, leaves in group_leaves: group_cmd = groups_dict[name] help_text = (group_cmd.help or "").split("\n")[0].strip() lines.append("") lines.append(f"### `hf {name}` — {help_text}") lines.append("") for path_parts, cmd in leaves: lines.append(_render_leaf(path_parts, cmd))
if common_flags: lines.append("") lines.append("## Common options") lines.append("") for long_name, (display, help_text) in sorted(common_flags.items()): help_text = _COMMON_FLAG_HELP_OVERRIDES.get(long_name, help_text) if help_text: lines.append(f"- `{display}` — {help_text}") else: lines.append(f"- `{display}`")
lines.extend(_SKILL_TIPS.splitlines())
return "\n".join(lines)
def _remove_existing(path: Path, force: bool) -> None: """Remove existing file/directory/symlink if force is True, otherwise raise an error.""" if not (path.exists() or path.is_symlink()): return if not force: raise CLIError(f"Skill already exists at {path}.\nRe-run with --force to overwrite.") if path.is_dir() and not path.is_symlink(): shutil.rmtree(path) else: path.unlink()
def _install_to(skills_dir: Path, skill_name: str, force: bool) -> Path: """Install a marketplace skill into a skills directory. Returns the installed path.""" skill = _skills.get_marketplace_skill(skill_name) try: return _skills.install_marketplace_skill(skill, skills_dir, force=force) except FileExistsError as exc: raise CLIError(f"{exc}\nRe-run with --force to overwrite.") from exc
def _create_symlink(agent_skills_dir: Path, skill_name: str, central_skill_path: Path, force: bool) -> Path: """Create a relative symlink from agent directory to the central skill location.""" agent_skills_dir = agent_skills_dir.expanduser().resolve() agent_skills_dir.mkdir(parents=True, exist_ok=True) link_path = agent_skills_dir / skill_name
_remove_existing(link_path, force) link_path.symlink_to(os.path.relpath(central_skill_path, agent_skills_dir))
return link_path
def _resolve_update_roots( *, claude: bool, global_: bool, dest: Path | None,) -> list[Path]: if dest is not None: if claude or global_: raise CLIError("--dest cannot be combined with --claude or --global.") return [dest.expanduser().resolve()]
roots: list[Path] = [CENTRAL_GLOBAL if global_ else CENTRAL_LOCAL] if claude: roots.append(CLAUDE_GLOBAL if global_ else CLAUDE_LOCAL) return [root.expanduser().resolve() for root in roots]
@skills_cli.command("preview")def skills_preview() -> None: """Print the generated `hf-cli` SKILL.md to stdout.""" print(build_skill_md())
@skills_cli.command( "add", examples=[ "hf skills add", "hf skills add huggingface-gradio --dest=~/my-skills", "hf skills add --global", "hf skills add --claude", "hf skills add huggingface-gradio --claude --global", ],)def skills_add( name: Annotated[ str, typer.Argument(help="Marketplace skill name.", show_default=False), ] = DEFAULT_SKILL_ID, claude: Annotated[bool, typer.Option("--claude", help="Install for Claude.")] = False, global_: Annotated[ bool, typer.Option( "--global", "-g", help="Install globally (user-level) instead of in the current project directory.", ), ] = False, dest: Annotated[ Path | None, typer.Option( help="Install into a custom destination (path to skills directory).", ), ] = None, force: Annotated[ bool, typer.Option( "--force", help="Overwrite existing skills in the destination.", ), ] = False,) -> None: """Download a Hugging Face skill and install it for an AI assistant.
Default location is in the current directory (.agents/skills) or user-level (~/.agents/skills). If `--claude` is specified, the skill is also symlinked into Claude's legacy skills directory. """ if dest is not None: if claude or global_: raise CLIError("--dest cannot be combined with --claude or --global.") skill_dest = _install_to(dest, name, force) print(f"Installed '{name}' to {skill_dest}") return
# Install to central location central_path = CENTRAL_GLOBAL if global_ else CENTRAL_LOCAL central_skill_path = _install_to(central_path, name, force) print(f"Installed '{name}' to central location: {central_skill_path}")
if claude: agent_target = CLAUDE_GLOBAL if global_ else CLAUDE_LOCAL link_path = _create_symlink(agent_target, name, central_skill_path, force) print(f"Created symlink: {link_path}")
@skills_cli.command( "upgrade", examples=[ "hf skills upgrade", "hf skills upgrade hf-cli", "hf skills upgrade huggingface-gradio --dest=~/my-skills", "hf skills upgrade --claude", ],)def skills_upgrade( name: Annotated[ str | None, typer.Argument(help="Optional installed skill name to upgrade.", show_default=False), ] = None, claude: Annotated[bool, typer.Option("--claude", help="Upgrade skills installed for Claude.")] = False, global_: Annotated[ bool, typer.Option( "--global", "-g", help="Use global skills directories instead of the current project.", ), ] = False, dest: Annotated[ Path | None, typer.Option( help="Upgrade skills in a custom skills directory.", ), ] = None,) -> None: """Upgrade installed Hugging Face marketplace skills.""" roots = _resolve_update_roots(claude=claude, global_=global_, dest=dest)
results = _skills.apply_updates(roots, selector=name) if not results: print("No installed skills found.") return
for result in results: detail = f" ({result.detail})" if result.detail else "" print(f"{result.name}: {result.status}{detail}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to interact with spaces on the Hugging Face Hub.
Usage: # list spaces on the Hub hf spaces ls
# list spaces with a search query hf spaces ls --search "chatbot"
# get info about a space hf spaces info enzostvs/deepsite"""
import enumimport functoolsimport osimport shleximport shutilimport subprocessimport sysimport tempfileimport timefrom typing import Annotated, Literal, get_args
import typerfrom packaging import versionfrom typing_extensions import assert_never
from huggingface_hub._hot_reload.client import multi_replica_reload_eventsfrom huggingface_hub._hot_reload.types import ApiGetReloadEventSourceData, ReloadRegionfrom huggingface_hub._space_api import SpaceStagefrom huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundErrorfrom huggingface_hub.file_download import hf_hub_downloadfrom huggingface_hub.hf_api import ExpandSpaceProperty_T, HfApi, SpaceSort_Tfrom huggingface_hub.utils import StatusLine, are_progress_bars_disabled, disable_progress_bars, enable_progress_bars
from ._cli_utils import ( AuthorOpt, FilterOpt, FormatWithAutoOpt, LimitOpt, RevisionOpt, SearchOpt, TokenOpt, api_object_to_dict, get_hf_api, make_expand_properties_parser, typer_factory,)from ._output import OutputFormatWithAuto, out
HOT_RELOADING_MIN_GRADIO = "6.1.0"
_EXPAND_PROPERTIES = sorted(get_args(ExpandSpaceProperty_T))_SORT_OPTIONS = get_args(SpaceSort_T)SpaceSortEnum = enum.Enum("SpaceSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
ExpandOpt = Annotated[ str | None, typer.Option( help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.", callback=make_expand_properties_parser(_EXPAND_PROPERTIES), ),]
spaces_cli = typer_factory(help="Interact with spaces on the Hub.")
@spaces_cli.command( "list | ls", examples=[ "hf spaces ls --limit 10", 'hf spaces ls --search "chatbot" --author huggingface', ],)def spaces_ls( search: SearchOpt = None, author: AuthorOpt = None, filter: FilterOpt = None, sort: Annotated[ SpaceSortEnum | None, typer.Option(help="Sort results."), ] = None, limit: LimitOpt = 10, expand: ExpandOpt = None, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """List spaces on the Hub.""" api = get_hf_api(token=token) sort_key = sort.value if sort else None results = [ api_object_to_dict(space_info) for space_info in api.list_spaces( filter=filter, author=author, search=search, sort=sort_key, limit=limit, expand=expand, # type: ignore[arg-type] ) ] out.table(results)
@spaces_cli.command( "info", examples=[ "hf spaces info enzostvs/deepsite", "hf spaces info gradio/theme_builder --expand sdk,runtime,likes", ],)def spaces_info( space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")], revision: RevisionOpt = None, expand: ExpandOpt = None, format: FormatWithAutoOpt = OutputFormatWithAuto.auto, token: TokenOpt = None,) -> None: """Get info about a space on the Hub.""" api = get_hf_api(token=token) try: info = api.space_info(repo_id=space_id, revision=revision, expand=expand) # type: ignore[arg-type] except RepositoryNotFoundError as e: raise CLIError(f"Space '{space_id}' not found.") from e except RevisionNotFoundError as e: raise CLIError(f"Revision '{revision}' not found on '{space_id}'.") from e out.dict(info)
@spaces_cli.command( "dev-mode", examples=[ "hf spaces dev-mode my-user-name/deepsite", ],)def dev_mode( space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")], stop: Annotated[bool, typer.Option(help="Stop dev mode.")] = False, token: TokenOpt = None,): """ Enable or disable dev mode on a Space.
Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you to restart your application without stopping the Space container itself. This feature is available as part of a PRO or Team & Enterprise plan.
See docs: https://huggingface.co/docs/hub/spaces-dev-mode """ api = get_hf_api(token=token) if stop: api.disable_space_dev_mode(space_id) print(f"Dev mode disabled for '{space_id}'") return api.enable_space_dev_mode(space_id) info = api.space_info(space_id) folder = getattr(info.card_data, "dev-mode-folder", "" if info.sdk == "docker" else "/home/user/app") folder_query_param = f"folder={folder}" if folder else "" print(f"Dev mode is currently building, track the progress here: https://huggingface.co/spaces/{info.id}") intermediate_statuses_and_messages = { SpaceStage.BUILDING: "building...", SpaceStage.RUNNING_BUILDING: "building...", SpaceStage.APP_STARTING: "app starting...", SpaceStage.RUNNING_APP_STARTING: "app starting...", } status = StatusLine() while True: info = api.space_info(space_id) if info.runtime is None: print("Runtime of the space unavailable") return if info.runtime.stage not in intermediate_statuses_and_messages: break status.update(intermediate_statuses_and_messages[info.runtime.stage]) time.sleep(1) if info.runtime.stage != SpaceStage.RUNNING: status.done(f"Dev mode is not ready (stage='{info.runtime.stage}')") return status.done("Dev mode ready!") print("Connect to dev environment:") print("") print("Web:") vscode_web_url = f"https://huggingface.co/spaces/{info.id}/dev-mode/vscode-web" if folder_query_param: vscode_web_url += f"?{folder_query_param}" ssh_host = f"{info.subdomain}@ssh.hf.space" print(f" * VSCode: {vscode_web_url}") print("") print("Local:") print("1. Add your SSH key to https://huggingface.co/settings/keys") print(f"2. SSH with `ssh -i <your_key> {ssh_host}`") print(" Or open") print(f" * VSCode: vscode://vscode-remote/ssh-remote+{ssh_host}{folder}") print(f" * Cursor: cursor://vscode-remote/ssh-remote+{ssh_host}{folder}") print("") print("PS: Dev mode stops after 48h of inactivity, don't forget to save your changes regularly.")
@spaces_cli.command( "hot-reload", examples=[ "hf spaces hot-reload username/repo-name app.py # Open an interactive editor to the remote app.py file", "hf spaces hot-reload username/repo-name -f app.py # Take local version from ./app.py and patch app.py remotely", "hf spaces hot-reload username/repo-name app.py -f src/app.py # Take local version from ./src/app.py", ],)def spaces_hot_reload( space_id: Annotated[ str, typer.Argument( help="The space ID (e.g. `username/repo-name`).", ), ], filename: Annotated[ str | None, typer.Argument( help="Path to the Python file in the Space repository. Can be omitted when --local-file is specified and path in repository matches." ), ] = None, local_file: Annotated[ str | None, typer.Option( "--local-file", "-f", help="Path of local file. Interactive editor mode if not specified", ), ] = None, skip_checks: Annotated[bool, typer.Option(help="Skip hot-reload compatibility checks.")] = False, skip_summary: Annotated[bool, typer.Option(help="Skip summary display after hot-reload is triggered")] = False, token: TokenOpt = None,) -> None: """ Hot-reload any Python file of a Space without a full rebuild + restart.
⚠ This feature is experimental ⚠
Only works with Gradio SDK (6.1+) Opens an interactive editor unless --local-file/-f is specified.
This command patches the live Python process using https://github.com/breuleux/jurigged (AST-based diffing, in-place function updates, etc.), integrated with Gradio's native hot-reload support (meaning that Gradio demo object changes are reflected in the UI)
The command creates a remote commit. If you are working from a local clone, run `git pull --autostash` afterwards to bring the commit back and keep your local git state in sync. """
typer.secho("This feature is experimental and subject to change", fg=typer.colors.BRIGHT_BLACK)
api = get_hf_api(token=token)
if not skip_checks: space_info = api.space_info(space_id) if space_info.sdk != "gradio": raise CLIError(f"Hot-reloading is only available on Gradio SDK. Found {space_info.sdk} SDK") if (card_data := space_info.card_data) is None: raise CLIError(f"Unable to read cardData for Space {space_id}") if (sdk_version := card_data.sdk_version) is None: raise CLIError(f"Unable to read sdk_version from {space_id} cardData") if version.parse(sdk_version) < version.Version(HOT_RELOADING_MIN_GRADIO): raise CLIError(f"Hot-reloading requires Gradio >= {HOT_RELOADING_MIN_GRADIO} (found {sdk_version})")
if local_file: local_path = local_file filename = local_file if filename is None else filename elif filename: if not skip_checks: try: api.auth_check( repo_type="space", repo_id=space_id, write=True, ) except RepositoryNotFoundError as e: raise CLIError( f"Write access check to {space_id} repository failed. Make sure that you are authenticated" ) from e temp_dir = tempfile.TemporaryDirectory() local_path = os.path.join(temp_dir.name, filename) if not (pbar_disabled := are_progress_bars_disabled()): disable_progress_bars() try: hf_hub_download( repo_type="space", repo_id=space_id, filename=filename, local_dir=temp_dir.name, ) finally: if not pbar_disabled: enable_progress_bars() editor_res = _editor_open(local_path) if editor_res == "no-tty": raise CLIError("Cannot open an editor (no TTY). Use -f flag to hot-reload from local path") if editor_res == "no-editor": raise CLIError("No editor found in local environment. Use -f flag to hot-reload from local path") if editor_res != 0: raise CLIError(f"Editor returned a non-zero exit code while attempting to edit {local_path}") else: raise CLIError("Either filename or --local-file/-f must be specified")
commit_info = api.upload_file( repo_type="space", repo_id=space_id, path_or_fileobj=local_path, path_in_repo=filename, _hot_reload=True, )
if not skip_summary: _spaces_hot_reload_summary( api=api, space_id=space_id, commit_sha=commit_info.oid, local_path=local_path if local_file else os.path.basename(local_path), token=token, )
def _spaces_hot_reload_summary( api: HfApi, space_id: str, commit_sha: str, local_path: str | None, token: str | None,) -> None: space_info = api.space_info(space_id) if (runtime := space_info.runtime) is None: raise CLIError(f"Unable to read SpaceRuntime from {space_id} infos") if (hot_reloading := runtime.hot_reloading) is None: raise CLIError(f"Space {space_id} current running version has not been hot-reloaded") if hot_reloading.status != "created": typer.echo(f"Failed creating hot-reloaded commit. {hot_reloading.replica_statuses=}") return
if (space_host := space_info.host) is None: raise CLIError("Unexpected None host on hotReloaded Space") if (space_subdomain := space_info.subdomain) is None: raise CLIError("Unexpected None subdomain on hotReloaded Space")
def render_region(region: ReloadRegion) -> str: res = "" if local_path is not None: res += f"{local_path}, " if region["startLine"] == region["endLine"]: res += f"line {region['startLine'] - 1}" else: res += f"lines {region['startLine'] - 1}-{region['endLine']}" return res
def display_event(event: ApiGetReloadEventSourceData) -> None: if event["data"]["kind"] == "error": typer.secho("✘ Unexpected hot-reloading error", bold=True) typer.secho(event["data"]["traceback"], italic=True) elif event["data"]["kind"] == "exception": typer.secho(f"✘ Exception at {render_region(event['data']['region'])}", bold=True) typer.secho(event["data"]["traceback"], italic=True) elif event["data"]["kind"] == "add": typer.secho(f"✔︎ Created {event['data']['objectName']} {event['data']['objectType']}", bold=True) elif event["data"]["kind"] == "delete": typer.secho(f"∅ Deleted {event['data']['objectName']} {event['data']['objectType']}", bold=True) elif event["data"]["kind"] == "update": typer.secho(f"✔︎ Updated {event['data']['objectName']} {event['data']['objectType']}", bold=True) elif event["data"]["kind"] == "run": typer.secho(f"▶ Run {render_region(event['data']['region'])}", bold=True) typer.secho(event["data"]["codeLines"], italic=True) elif event["data"]["kind"] == "ui": if event["data"]["updated"]: typer.secho("⟳ UI updated", bold=True) else: typer.secho("∅ UI untouched", bold=True) else: assert_never(event["data"]["kind"])
for replica_stream_event in multi_replica_reload_events( commit_sha=commit_sha, host=space_host, subdomain=space_subdomain, replica_hashes=[hash for hash, _ in hot_reloading.replica_statuses], token=token, ): if replica_stream_event["kind"] == "event": display_event(replica_stream_event["event"]) elif replica_stream_event["kind"] == "replicaHash": typer.secho(f"---- Replica {replica_stream_event['hash']} ----") elif replica_stream_event["kind"] == "fullMatch": typer.echo("✔︎ Same as first replica") else: assert_never(replica_stream_event)
PREFERRED_EDITORS = ( ("code", "code --wait"), ("nvim", "nvim"), ("nano", "nano"), ("vim", "vim"), ("vi", "vi"),)
@functools.cachedef _get_editor_command() -> str | None: for env in ("HF_EDITOR", "VISUAL", "EDITOR"): if command := os.getenv(env, "").strip(): return command for binary_path, editor_command in PREFERRED_EDITORS: if shutil.which(binary_path) is not None: return editor_command return None
def _editor_open(local_path: str) -> int | Literal["no-tty", "no-editor"]: if not (sys.stdin.isatty() and sys.stdout.isatty()): return "no-tty" if (editor_command := _get_editor_command()) is None: return "no-editor" command = [*shlex.split(editor_command), local_path] res = subprocess.run(command, start_new_session=True) return res.returncode12345678910111213141516171819202122232425262728# Copyright 2022 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to print information about the environment and version."""
from huggingface_hub import __version__
from ..utils import dump_environment_info
def env() -> None: """Print information about the environment.""" dump_environment_info()
def version() -> None: """Print information about the hf version.""" print(__version__)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300# Copyright 2023-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains command to upload a repo or file with the CLI.
Usage: # Upload file (implicit) hf upload my-cool-model ./my-cool-model.safetensors
# Upload file (explicit) hf upload my-cool-model ./my-cool-model.safetensors model.safetensors
# Upload directory (implicit). If `my-cool-model/` is a directory it will be uploaded, otherwise an exception is raised. hf upload my-cool-model
# Upload directory (explicit) hf upload my-cool-model ./models/my-cool-model .
# Upload filtered directory (example: tensorboard logs except for the last run) hf upload my-cool-model ./model/training /logs --include "*.tfevents.*" --exclude "*20230905*"
# Upload with wildcard hf upload my-cool-model "./model/training/*.safetensors"
# Upload private dataset hf upload Wauplin/my-cool-dataset ./data . --repo-type=dataset --private
# Upload with token hf upload Wauplin/my-cool-model --token=hf_****
# Sync local Space with Hub (upload new files, delete removed files) hf upload Wauplin/space-example --repo-type=space --exclude="/logs/*" --delete="*" --commit-message="Sync local Space with Hub"
# Schedule commits every 30 minutes hf upload Wauplin/my-cool-model --every=30"""
import osimport timeimport warningsfrom typing import Annotated
import typer
from huggingface_hub import loggingfrom huggingface_hub._commit_scheduler import CommitSchedulerfrom huggingface_hub.errors import RevisionNotFoundErrorfrom huggingface_hub.utils import disable_progress_bars, enable_progress_bars
from ._cli_utils import ( PrivateOpt, RepoIdArg, RepoType, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api,)
logger = logging.get_logger(__name__)
UPLOAD_EXAMPLES = [ "hf upload my-cool-model . .", "hf upload Wauplin/my-cool-model ./models/model.safetensors", "hf upload Wauplin/my-cool-dataset ./data /train --repo-type=dataset", 'hf upload Wauplin/my-cool-model ./models . --commit-message="Epoch 34/50" --commit-description="Val accuracy: 68%"', "hf upload bigcode/the-stack . . --repo-type dataset --create-pr",]
def upload( repo_id: RepoIdArg, local_path: Annotated[ str | None, typer.Argument( help="Local path to the file or folder to upload. Wildcard patterns are supported. Defaults to current directory.", ), ] = None, path_in_repo: Annotated[ str | None, typer.Argument( help="Path of the file or folder in the repo. Defaults to the relative path of the file or folder.", ), ] = None, repo_type: RepoTypeOpt = RepoType.model, revision: RevisionOpt = None, private: PrivateOpt = None, include: Annotated[ list[str] | None, typer.Option( help="Glob patterns to match files to upload.", ), ] = None, exclude: Annotated[ list[str] | None, typer.Option( help="Glob patterns to exclude from files to upload.", ), ] = None, delete: Annotated[ list[str] | None, typer.Option( help="Glob patterns for file to be deleted from the repo while committing.", ), ] = None, commit_message: Annotated[ str | None, typer.Option( help="The summary / title / first line of the generated commit.", ), ] = None, commit_description: Annotated[ str | None, typer.Option( help="The description of the generated commit.", ), ] = None, create_pr: Annotated[ bool, typer.Option( help="Whether to upload content as a new Pull Request.", ), ] = False, every: Annotated[ float | None, typer.Option( help="If set, a background job is scheduled to create commits every `every` minutes.", ), ] = None, token: TokenOpt = None, quiet: Annotated[ bool, typer.Option( help="Disable progress bars and warnings; print only the returned path.", ), ] = False,) -> None: """Upload a file or a folder to the Hub. Recommended for single-commit uploads."""
if every is not None and every <= 0: raise typer.BadParameter("--every must be a positive value", param_hint="every")
repo_type_str = repo_type.value
api = get_hf_api(token=token)
# Resolve local_path and path_in_repo based on implicit/explicit rules resolved_local_path, resolved_path_in_repo, resolved_include = _resolve_upload_paths( repo_id=repo_id, local_path=local_path, path_in_repo=path_in_repo, include=include )
def run_upload() -> str: if os.path.isfile(resolved_local_path): if resolved_include is not None and len(resolved_include) > 0 and isinstance(resolved_include, list): warnings.warn("Ignoring --include since a single file is uploaded.") if exclude is not None and len(exclude) > 0: warnings.warn("Ignoring --exclude since a single file is uploaded.") if delete is not None and len(delete) > 0: warnings.warn("Ignoring --delete since a single file is uploaded.")
# Schedule commits if `every` is set if every is not None: allow_patterns: list[str] | None ignore_patterns: list[str] | None if os.path.isfile(resolved_local_path): # If file => watch entire folder + use allow_patterns folder_path = os.path.dirname(resolved_local_path) pi = ( resolved_path_in_repo[: -len(resolved_local_path)] if resolved_path_in_repo.endswith(resolved_local_path) else resolved_path_in_repo ) allow_patterns = [resolved_local_path] ignore_patterns = [] else: folder_path = resolved_local_path pi = resolved_path_in_repo allow_patterns = resolved_include ignore_patterns = exclude if delete is not None and len(delete) > 0: warnings.warn("Ignoring --delete when uploading with scheduled commits.")
scheduler = CommitScheduler( folder_path=folder_path, repo_id=repo_id, repo_type=repo_type_str, revision=revision, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, path_in_repo=pi, private=private, every=every, hf_api=api, ) print(f"Scheduling commits every {every} minutes to {scheduler.repo_id}.") try: while True: time.sleep(100) except KeyboardInterrupt: scheduler.stop() return "Stopped scheduled commits."
# Otherwise, create repo and proceed with the upload if not os.path.isfile(resolved_local_path) and not os.path.isdir(resolved_local_path): raise FileNotFoundError(f"No such file or directory: '{resolved_local_path}'.") created = api.create_repo( repo_id=repo_id, repo_type=repo_type_str, exist_ok=True, private=private, space_sdk="gradio" if repo_type_str == "space" else None, # ^ We don't want it to fail when uploading to a Space => let's set Gradio by default. # ^ I'd rather not add CLI args to set it explicitly as we already have `hf repos create` for that. ).repo_id
# Check if branch already exists and if not, create it if revision is not None and not create_pr: try: api.repo_info(repo_id=created, repo_type=repo_type_str, revision=revision) except RevisionNotFoundError: logger.info(f"Branch '{revision}' not found. Creating it...") api.create_branch(repo_id=created, repo_type=repo_type_str, branch=revision, exist_ok=True) # ^ `exist_ok=True` to avoid race concurrency issues
# File-based upload if os.path.isfile(resolved_local_path): return api.upload_file( path_or_fileobj=resolved_local_path, path_in_repo=resolved_path_in_repo, repo_id=created, repo_type=repo_type_str, revision=revision, commit_message=commit_message, commit_description=commit_description, create_pr=create_pr, )
# Folder-based upload return api.upload_folder( folder_path=resolved_local_path, path_in_repo=resolved_path_in_repo, repo_id=created, repo_type=repo_type_str, revision=revision, commit_message=commit_message, commit_description=commit_description, create_pr=create_pr, allow_patterns=resolved_include, ignore_patterns=exclude, delete_patterns=delete, )
if quiet: disable_progress_bars() with warnings.catch_warnings(): warnings.simplefilter("ignore") print(run_upload()) enable_progress_bars() else: print(run_upload()) logging.set_verbosity_warning()
def _resolve_upload_paths( *, repo_id: str, local_path: str | None, path_in_repo: str | None, include: list[str] | None) -> tuple[str, str, list[str] | None]: repo_name = repo_id.split("/")[-1] resolved_include = include
if local_path is not None and any(c in local_path for c in ["*", "?", "["]): if include is not None: raise ValueError("Cannot set --include when local_path contains a wildcard.") if path_in_repo is not None and path_in_repo != ".": raise ValueError("Cannot set path_in_repo when local_path contains a wildcard.") return ".", local_path, ["."] # will be adjusted below; placeholder for type
if local_path is None and os.path.isfile(repo_name): return repo_name, repo_name, resolved_include if local_path is None and os.path.isdir(repo_name): return repo_name, ".", resolved_include if local_path is None: raise ValueError(f"'{repo_name}' is not a local file or folder. Please set local_path explicitly.")
if path_in_repo is None and os.path.isfile(local_path): return local_path, os.path.basename(local_path), resolved_include if path_in_repo is None: return local_path, ".", resolved_include return local_path, path_in_repo, resolved_include123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Copyright 2023-present, the HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains command to upload a large folder with the CLI."""
import osfrom typing import Annotated
import typer
from huggingface_hub import loggingfrom huggingface_hub.utils import ANSI, disable_progress_bars
from ._cli_utils import ( PrivateOpt, RepoIdArg, RepoType, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api,)
logger = logging.get_logger(__name__)
UPLOAD_LARGE_FOLDER_EXAMPLES = [ "hf upload-large-folder Wauplin/my-cool-model ./large_model_dir", "hf upload-large-folder Wauplin/my-cool-model ./large_model_dir --revision v1.0",]
def upload_large_folder( repo_id: RepoIdArg, local_path: Annotated[ str, typer.Argument( help="Local path to the folder to upload.", ), ], repo_type: RepoTypeOpt = RepoType.model, revision: RevisionOpt = None, private: PrivateOpt = None, include: Annotated[ list[str] | None, typer.Option( help="Glob patterns to match files to upload.", ), ] = None, exclude: Annotated[ list[str] | None, typer.Option( help="Glob patterns to exclude from files to upload.", ), ] = None, token: TokenOpt = None, num_workers: Annotated[ int | None, typer.Option( help="Number of workers to use to hash, upload and commit files.", ), ] = None, no_report: Annotated[ bool, typer.Option( help="Whether to disable regular status report.", ), ] = False, no_bars: Annotated[ bool, typer.Option( help="Whether to disable progress bars.", ), ] = False,) -> None: """Upload a large folder to the Hub. Recommended for resumable uploads.""" if not os.path.isdir(local_path): raise typer.BadParameter("Large upload is only supported for folders.", param_hint="local_path")
print( ANSI.yellow( "You are about to upload a large folder to the Hub using `hf upload-large-folder`. " "This is a new feature so feedback is very welcome!\n" "\n" "A few things to keep in mind:\n" " - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations\n" " - Do not start several processes in parallel.\n" " - You can interrupt and resume the process at any time. " "The script will pick up where it left off except for partially uploaded files that would have to be entirely reuploaded.\n" " - Do not upload the same folder to several repositories. If you need to do so, you must delete the `./.cache/huggingface/` folder first.\n" "\n" f"Some temporary metadata will be stored under `{local_path}/.cache/huggingface`.\n" " - You must not modify those files manually.\n" " - You must not delete the `./.cache/huggingface/` folder while a process is running.\n" " - You can delete the `./.cache/huggingface/` folder to reinitialize the upload state when process is not running. Files will have to be hashed and preuploaded again, except for already committed files.\n" "\n" "If the process output is too verbose, you can disable the progress bars with `--no-bars`. " "You can also entirely disable the status report with `--no-report`.\n" "\n" "For more details, run `hf upload-large-folder --help` or check the documentation at " "https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-large-folder." ) )
if no_bars: disable_progress_bars()
api = get_hf_api(token=token) api.upload_large_folder( repo_id=repo_id, folder_path=local_path, repo_type=repo_type.value, revision=revision, private=private, allow_patterns=include, ignore_patterns=exclude, num_workers=num_workers, print_report=not no_report, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310# Copyright 2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains commands to manage webhooks on the Hugging Face Hub.
Usage: # list all webhooks hf webhooks ls
# show details of a single webhook hf webhooks info <webhook_id>
# create a new webhook hf webhooks create --url https://example.com/hook --watch model:bert-base-uncased
# create a webhook watching multiple items and domains hf webhooks create --url https://example.com/hook --watch org:HuggingFace --watch model:gpt2 --domain repo
# update a webhook hf webhooks update <webhook_id> --url https://new-url.com/hook
# enable / disable a webhook hf webhooks enable <webhook_id> hf webhooks disable <webhook_id>
# delete a webhook hf webhooks delete <webhook_id>"""
import enumimport jsonfrom typing import Annotated, get_args, get_type_hints
import typer
from huggingface_hub.constants import WEBHOOK_DOMAIN_Tfrom huggingface_hub.hf_api import WebhookWatchedItem
from ._cli_utils import ( FormatOpt, OutputFormat, QuietOpt, TokenOpt, api_object_to_dict, get_hf_api, print_list_output, typer_factory,)
# Build enums dynamically from Literal types to avoid duplication_WATCHED_TYPES = get_args(get_type_hints(WebhookWatchedItem)["type"])WatchedItemType = enum.Enum("WatchedItemType", {t: t for t in _WATCHED_TYPES}, type=str) # type: ignore[misc]
_DOMAIN_TYPES = get_args(WEBHOOK_DOMAIN_T)WebhookDomain = enum.Enum("WebhookDomain", {d: d for d in _DOMAIN_TYPES}, type=str) # type: ignore[misc]
def _parse_watch(values: list[str]) -> list[WebhookWatchedItem]: """Parse 'type:name' strings into WebhookWatchedItem objects.
Args: values: List of strings in the format 'type:name' (e.g., 'model:bert-base-uncased', 'org:HuggingFace').
Returns: List of WebhookWatchedItem objects.
Raises: typer.BadParameter: If any value doesn't match the expected format. """ items = [] valid_types = tuple(_WATCHED_TYPES) for v in values: if ":" not in v: raise typer.BadParameter( f"Expected format 'type:name' (e.g. 'model:bert-base-uncased'), got '{v}'." f" Valid types: {', '.join(valid_types)}." ) kind, name = v.split(":", 1) if kind not in valid_types: raise typer.BadParameter(f"Invalid type '{kind}'. Valid types: {', '.join(valid_types)}.") items.append(WebhookWatchedItem(type=kind, name=name)) # type: ignore return items
webhooks_cli = typer_factory(help="Manage webhooks on the Hub.")
@webhooks_cli.command( "list | ls", examples=[ "hf webhooks ls", "hf webhooks ls --format json", "hf webhooks ls -q", ],)def webhooks_ls( format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False, token: TokenOpt = None,) -> None: """List all webhooks for the current user.""" api = get_hf_api(token=token) results = [api_object_to_dict(w) for w in api.list_webhooks()] print_list_output( results, format=format, quiet=quiet, headers=["id", "url", "disabled", "domains", "watched"], row_fn=lambda item: [ item.get("id", ""), item.get("url") or "(job)", str(item.get("disabled", False)), ", ".join(item.get("domains") or []), ", ".join( f"{w['type']}:{w['name']}" if isinstance(w, dict) else str(w) for w in (item.get("watched") or []) ), ], )
@webhooks_cli.command( "info", examples=[ "hf webhooks info abc123", ],)def webhooks_info( webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook.")], token: TokenOpt = None,) -> None: """Show full details for a single webhook as JSON.""" api = get_hf_api(token=token) webhook = api.get_webhook(webhook_id) print(json.dumps(api_object_to_dict(webhook), indent=2))
@webhooks_cli.command( "create", examples=[ "hf webhooks create --url https://example.com/hook --watch model:bert-base-uncased", "hf webhooks create --url https://example.com/hook --watch org:HuggingFace --watch model:gpt2 --domain repo", "hf webhooks create --job-id 687f911eaea852de79c4a50a --watch user:julien-c", ],)def webhooks_create( watch: Annotated[ list[str], typer.Option( "--watch", help="Item to watch, in 'type:name' format (e.g. 'model:bert-base-uncased'). Repeatable.", ), ], url: Annotated[ str | None, typer.Option(help="URL to send webhook payloads to. Mutually exclusive with --job-id."), ] = None, job_id: Annotated[ str | None, typer.Option( "--job-id", help="ID of a Job to trigger (from job.id) instead of pinging a URL. Mutually exclusive with --url.", ), ] = None, domain: Annotated[ list[WebhookDomain] | None, typer.Option( "--domain", help="Domain to watch: 'repo' or 'discussions'. Repeatable. Defaults to all domains.", ), ] = None, secret: Annotated[ str | None, typer.Option(help="Optional secret used to sign webhook payloads."), ] = None, token: TokenOpt = None,) -> None: """Create a new webhook.
Provide either --url (to ping a remote server) or --job-id (to trigger a Job), but not both. """ if url is not None and job_id is not None: raise typer.BadParameter("Provide either --url or --job-id, not both.") if url is None and job_id is None: raise typer.BadParameter("Provide either --url or --job-id.") api = get_hf_api(token=token) watched_items = _parse_watch(watch) domains = [d.value for d in domain] if domain else None webhook = api.create_webhook(url=url, job_id=job_id, watched=watched_items, domains=domains, secret=secret) # type: ignore print(f"Webhook created: {webhook.id}") print(json.dumps(api_object_to_dict(webhook), indent=2))
@webhooks_cli.command( "update", examples=[ "hf webhooks update abc123 --url https://new-url.com/hook", "hf webhooks update abc123 --watch model:gpt2 --domain repo", "hf webhooks update abc123 --secret newsecret", ],)def webhooks_update( webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook to update.")], url: Annotated[ str | None, typer.Option(help="New URL to send webhook payloads to."), ] = None, watch: Annotated[ list[str] | None, typer.Option( "--watch", help=( "New list of items to watch, in 'type:name' format. " "Repeatable. Replaces the entire existing watched list." ), ), ] = None, domain: Annotated[ list[WebhookDomain] | None, typer.Option( "--domain", help="New list of domains to watch: 'repo' or 'discussions'. Repeatable.", ), ] = None, secret: Annotated[ str | None, typer.Option(help="New secret used to sign webhook payloads."), ] = None, token: TokenOpt = None,) -> None: """Update an existing webhook. Only provided options are changed.""" api = get_hf_api(token=token) watched_items = _parse_watch(watch) if watch else None domains = [d.value for d in domain] if domain else None webhook = api.update_webhook(webhook_id, url=url, watched=watched_items, domains=domains, secret=secret) # type: ignore print(f"Webhook updated: {webhook.id}") print(json.dumps(api_object_to_dict(webhook), indent=2))
@webhooks_cli.command( "enable", examples=[ "hf webhooks enable abc123", ],)def webhooks_enable( webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook to enable.")], token: TokenOpt = None,) -> None: """Enable a disabled webhook.""" api = get_hf_api(token=token) webhook = api.enable_webhook(webhook_id) print(f"Webhook enabled: {webhook.id}")
@webhooks_cli.command( "disable", examples=[ "hf webhooks disable abc123", ],)def webhooks_disable( webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook to disable.")], token: TokenOpt = None,) -> None: """Disable an active webhook.""" api = get_hf_api(token=token) webhook = api.disable_webhook(webhook_id) print(f"Webhook disabled: {webhook.id}")
@webhooks_cli.command( "delete", examples=[ "hf webhooks delete abc123", "hf webhooks delete abc123 --yes", ],)def webhooks_delete( webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook to delete.")], yes: Annotated[ bool, typer.Option( "--yes", "-y", help="Skip confirmation prompt.", ), ] = False, token: TokenOpt = None,) -> None: """Delete a webhook permanently.""" if not yes: confirm = typer.confirm(f"Are you sure you want to delete webhook '{webhook_id}'?") if not confirm: print("Aborted.") raise typer.Abort() api = get_hf_api(token=token) api.delete_webhook(webhook_id) print(f"Webhook deleted: {webhook_id}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363"""Data structures to interact with Discussions and Pull Requests on the Hub.
See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions)for more information on Pull Requests, Discussions, and the community tab."""
from dataclasses import dataclassfrom datetime import datetimefrom typing import Literal, TypedDict
from . import constantsfrom .utils import parse_datetime
DiscussionStatus = Literal["open", "closed", "merged", "draft"]
@dataclassclass Discussion: """ A Discussion or Pull Request on the Hub.
This dataclass is not intended to be instantiated directly.
Attributes: title (`str`): The title of the Discussion / Pull Request status (`str`): The status of the Discussion / Pull Request. It must be one of: * `"open"` * `"closed"` * `"merged"` (only for Pull Requests ) * `"draft"` (only for Pull Requests ) num (`int`): The number of the Discussion / Pull Request. repo_id (`str`): The id (`"{namespace}/{repo_name}"`) of the repo on which the Discussion / Pull Request was open. repo_type (`str`): The type of the repo on which the Discussion / Pull Request was open. Possible values are: `"model"`, `"dataset"`, `"space"`. author (`str`): The username of the Discussion / Pull Request author. Can be `"deleted"` if the user has been deleted since. is_pull_request (`bool`): Whether or not this is a Pull Request. created_at (`datetime`): The `datetime` of creation of the Discussion / Pull Request. endpoint (`str`): Endpoint of the Hub. Default is https://huggingface.co. git_reference (`str`, *optional*): (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. url (`str`): (property) URL of the discussion on the Hub. """
title: str status: DiscussionStatus num: int repo_id: str repo_type: str author: str is_pull_request: bool created_at: datetime endpoint: str
@property def git_reference(self) -> str | None: """ If this is a Pull Request , returns the git reference to which changes can be pushed. Returns `None` otherwise. """ if self.is_pull_request: return f"refs/pr/{self.num}" return None
@property def url(self) -> str: """Returns the URL of the discussion on the Hub.""" if self.repo_type is None or self.repo_type == constants.REPO_TYPE_MODEL: return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}" return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}"
@dataclassclass DiscussionWithDetails(Discussion): """ Subclass of [`Discussion`].
Attributes: title (`str`): The title of the Discussion / Pull Request status (`str`): The status of the Discussion / Pull Request. It can be one of: * `"open"` * `"closed"` * `"merged"` (only for Pull Requests ) * `"draft"` (only for Pull Requests ) num (`int`): The number of the Discussion / Pull Request. repo_id (`str`): The id (`"{namespace}/{repo_name}"`) of the repo on which the Discussion / Pull Request was open. repo_type (`str`): The type of the repo on which the Discussion / Pull Request was open. Possible values are: `"model"`, `"dataset"`, `"space"`. author (`str`): The username of the Discussion / Pull Request author. Can be `"deleted"` if the user has been deleted since. is_pull_request (`bool`): Whether or not this is a Pull Request. created_at (`datetime`): The `datetime` of creation of the Discussion / Pull Request. events (`list` of [`DiscussionEvent`]) The list of [`DiscussionEvents`] in this Discussion or Pull Request. conflicting_files (`Union[list[str], bool, None]`, *optional*): A list of conflicting files if this is a Pull Request. `None` if `self.is_pull_request` is `False`. `True` if there are conflicting files but the list can't be retrieved. target_branch (`str`, *optional*): The branch into which changes are to be merged if this is a Pull Request . `None` if `self.is_pull_request` is `False`. merge_commit_oid (`str`, *optional*): If this is a merged Pull Request , this is set to the OID / SHA of the merge commit, `None` otherwise. diff (`str`, *optional*): The git diff if this is a Pull Request , `None` otherwise. endpoint (`str`): Endpoint of the Hub. Default is https://huggingface.co. git_reference (`str`, *optional*): (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. url (`str`): (property) URL of the discussion on the Hub. """
events: list["DiscussionEvent"] conflicting_files: list[str] | bool | None target_branch: str | None merge_commit_oid: str | None diff: str | None
class DiscussionEventArgs(TypedDict): id: str type: str created_at: datetime author: str _event: dict
@dataclassclass DiscussionEvent: """ An event in a Discussion or Pull Request.
Use concrete classes: * [`DiscussionComment`] * [`DiscussionStatusChange`] * [`DiscussionCommit`] * [`DiscussionTitleChange`]
Attributes: id (`str`): The ID of the event. An hexadecimal string. type (`str`): The type of the event. created_at (`datetime`): A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) object holding the creation timestamp for the event. author (`str`): The username of the Discussion / Pull Request author. Can be `"deleted"` if the user has been deleted since. """
id: str type: str created_at: datetime author: str
_event: dict """Stores the original event data, in case we need to access it later."""
@dataclassclass DiscussionComment(DiscussionEvent): """A comment in a Discussion / Pull Request.
Subclass of [`DiscussionEvent`].
Attributes: id (`str`): The ID of the event. An hexadecimal string. type (`str`): The type of the event. created_at (`datetime`): A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) object holding the creation timestamp for the event. author (`str`): The username of the Discussion / Pull Request author. Can be `"deleted"` if the user has been deleted since. content (`str`): The raw markdown content of the comment. Mentions, links and images are not rendered. edited (`bool`): Whether or not this comment has been edited. hidden (`bool`): Whether or not this comment has been hidden. """
content: str edited: bool hidden: bool
@property def rendered(self) -> str: """The rendered comment, as a HTML string""" return self._event["data"]["latest"]["html"]
@property def last_edited_at(self) -> datetime: """The last edit time, as a `datetime` object.""" return parse_datetime(self._event["data"]["latest"]["updatedAt"])
@property def last_edited_by(self) -> str: """The last edit time, as a `datetime` object.""" return self._event["data"]["latest"].get("author", {}).get("name", "deleted")
@property def edit_history(self) -> list[dict]: """The edit history of the comment""" return self._event["data"]["history"]
@property def number_of_edits(self) -> int: return len(self.edit_history)
@dataclassclass DiscussionStatusChange(DiscussionEvent): """A change of status in a Discussion / Pull Request.
Subclass of [`DiscussionEvent`].
Attributes: id (`str`): The ID of the event. An hexadecimal string. type (`str`): The type of the event. created_at (`datetime`): A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) object holding the creation timestamp for the event. author (`str`): The username of the Discussion / Pull Request author. Can be `"deleted"` if the user has been deleted since. new_status (`str`): The status of the Discussion / Pull Request after the change. It can be one of: * `"open"` * `"closed"` * `"merged"` (only for Pull Requests ) """
new_status: str
@dataclassclass DiscussionCommit(DiscussionEvent): """A commit in a Pull Request.
Subclass of [`DiscussionEvent`].
Attributes: id (`str`): The ID of the event. An hexadecimal string. type (`str`): The type of the event. created_at (`datetime`): A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) object holding the creation timestamp for the event. author (`str`): The username of the Discussion / Pull Request author. Can be `"deleted"` if the user has been deleted since. summary (`str`): The summary of the commit. oid (`str`): The OID / SHA of the commit, as a hexadecimal string. """
summary: str oid: str
@dataclassclass DiscussionTitleChange(DiscussionEvent): """A rename event in a Discussion / Pull Request.
Subclass of [`DiscussionEvent`].
Attributes: id (`str`): The ID of the event. An hexadecimal string. type (`str`): The type of the event. created_at (`datetime`): A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) object holding the creation timestamp for the event. author (`str`): The username of the Discussion / Pull Request author. Can be `"deleted"` if the user has been deleted since. old_title (`str`): The previous title for the Discussion / Pull Request. new_title (`str`): The new title. """
old_title: str new_title: str
def deserialize_event(event: dict) -> DiscussionEvent: """Instantiates a [`DiscussionEvent`] from a dict""" event_id: str = event["id"] event_type: str = event["type"] created_at = parse_datetime(event["createdAt"])
common_args: DiscussionEventArgs = { "id": event_id, "type": event_type, "created_at": created_at, "author": event.get("author", {}).get("name", "deleted"), "_event": event, }
if event_type == "comment": return DiscussionComment( **common_args, edited=event["data"]["edited"], hidden=event["data"]["hidden"], content=event["data"]["latest"]["raw"], ) if event_type == "status-change": return DiscussionStatusChange( **common_args, new_status=event["data"]["status"], ) if event_type == "commit": return DiscussionCommit( **common_args, summary=event["data"]["subject"], oid=event["data"]["oid"], ) if event_type == "title-change": return DiscussionTitleChange( **common_args, old_title=event["data"]["from"], new_title=event["data"]["to"], )
return DiscussionEvent(**common_args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291import osimport reimport typingfrom typing import Literal
# Possible values for env variables
ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
def _is_true(value: str | None) -> bool: if value is None: return False return value.upper() in ENV_VARS_TRUE_VALUES
def _as_int(value: str | None) -> int | None: if value is None: return None return int(value)
# Constants for file downloads
PYTORCH_WEIGHTS_NAME = "pytorch_model.bin"TF2_WEIGHTS_NAME = "tf_model.h5"TF_WEIGHTS_NAME = "model.ckpt"FLAX_WEIGHTS_NAME = "flax_model.msgpack"CONFIG_NAME = "config.json"REPOCARD_NAME = "README.md"EVAL_RESULTS_FOLDER = ".eval_results"DEFAULT_ETAG_TIMEOUT = 10DEFAULT_DOWNLOAD_TIMEOUT = 10DEFAULT_REQUEST_TIMEOUT = 10DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024MAX_HTTP_DOWNLOAD_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB
# Constants for serialization
PYTORCH_WEIGHTS_FILE_PATTERN = "pytorch_model{suffix}.bin" # Unsafe pickle: use safetensors insteadSAFETENSORS_WEIGHTS_FILE_PATTERN = "model{suffix}.safetensors"TF2_WEIGHTS_FILE_PATTERN = "tf_model{suffix}.h5"
# Constants for safetensors repos
SAFETENSORS_SINGLE_FILE = "model.safetensors"SAFETENSORS_INDEX_FILE = "model.safetensors.index.json"SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000
# Timeout of aquiring file lock and logging the attemptFILELOCK_LOG_EVERY_SECONDS = 10
# Git-related constants
DEFAULT_REVISION = "main"REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}")
HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/"
_staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING"))
_HF_DEFAULT_ENDPOINT = "https://huggingface.co"_HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"ENDPOINT = os.getenv("HF_ENDPOINT", _HF_DEFAULT_ENDPOINT).rstrip("/")HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
if _staging_mode: ENDPOINT = _HF_DEFAULT_STAGING_ENDPOINT HUGGINGFACE_CO_URL_TEMPLATE = _HF_DEFAULT_STAGING_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
DATASETS_SERVER_ENDPOINT = "https://datasets-server.huggingface.co"
HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"HUGGINGFACE_HEADER_X_BILL_TO = "X-HF-Bill-To"
INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co")
# See https://huggingface.co/docs/inference-endpoints/indexINFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2"INFERENCE_CATALOG_ENDPOINT = "https://endpoints.huggingface.co/api/catalog"
# See https://api.endpoints.huggingface.cloud/#post-/v2/endpoint/-namespace-INFERENCE_ENDPOINT_IMAGE_KEYS = [ "custom", "huggingface", "huggingfaceNeuron", "llamacpp", "tei", "tgi", "tgiNeuron",]
# Proxy for third-party providersINFERENCE_PROXY_TEMPLATE = "https://router.huggingface.co/{provider}"
REPO_ID_SEPARATOR = "--"# ^ this substring is not allowed in repo_ids on hf.co# and is the canonical one we use for serialization of repo ids elsewhere.
REPO_TYPE_DATASET = "dataset"REPO_TYPE_SPACE = "space"REPO_TYPE_MODEL = "model"REPO_TYPE_KERNEL = "kernel"REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE]REPO_TYPES_WITH_KERNEL = REPO_TYPES + [REPO_TYPE_KERNEL]SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"]
REPO_TYPES_URL_PREFIXES = { REPO_TYPE_DATASET: "datasets/", REPO_TYPE_SPACE: "spaces/", REPO_TYPE_KERNEL: "kernels/",}REPO_TYPES_MAPPING = { "datasets": REPO_TYPE_DATASET, "spaces": REPO_TYPE_SPACE, "models": REPO_TYPE_MODEL, "kernels": REPO_TYPE_KERNEL,}
DiscussionTypeFilter = Literal["all", "discussion", "pull_request"]DISCUSSION_TYPES: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter)DiscussionStatusFilter = Literal["all", "open", "closed"]DISCUSSION_STATUS: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter)
# Webhook subscription typesWEBHOOK_DOMAIN_T = Literal["repo", "discussions"]
# default cachedefault_home = os.path.join(os.path.expanduser("~"), ".cache")HF_HOME = os.path.expandvars( os.path.expanduser( os.getenv( "HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"), ) ))
default_cache_path = os.path.join(HF_HOME, "hub")default_assets_cache_path = os.path.join(HF_HOME, "assets")
# Legacy env variablesHUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path)HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path)
# New env variablesHF_HUB_CACHE = os.path.expandvars( os.path.expanduser( os.getenv( "HF_HUB_CACHE", HUGGINGFACE_HUB_CACHE, ) ))HF_ASSETS_CACHE = os.path.expandvars( os.path.expanduser( os.getenv( "HF_ASSETS_CACHE", HUGGINGFACE_ASSETS_CACHE, ) ))
HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE"))
def is_offline_mode() -> bool: """Returns whether we are in offline mode for the Hub.
When offline mode is enabled, all HTTP requests made with `get_session` will raise an `OfflineModeIsEnabled` exception.
Example: ```py from huggingface_hub import is_offline_mode
def list_files(repo_id: str): if is_offline_mode(): ... # list files from local cache (degraded experience but still functional) else: ... # list files from Hub (complete experience) ``` """ return HF_HUB_OFFLINE
# File created to mark that the version check has been done.# Check is performed once per 24 hours at most.CHECK_FOR_UPDATE_DONE_PATH = os.path.join(HF_HOME, ".check_for_update_done")
# If set, log level will be set to DEBUG and all requests made to the Hub will be logged# as curl commands for reproducibility.HF_DEBUG = _is_true(os.environ.get("HF_DEBUG"))
# Opt-out from telemetry requestsHF_HUB_DISABLE_TELEMETRY = ( _is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable or _is_true(os.environ.get("DISABLE_TELEMETRY")) or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/)
HF_TOKEN_PATH = os.path.expandvars( os.path.expanduser( os.getenv( "HF_TOKEN_PATH", os.path.join(HF_HOME, "token"), ) ))HF_STORED_TOKENS_PATH = os.path.join(os.path.dirname(HF_TOKEN_PATH), "stored_tokens")
if _staging_mode: # In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens # In practice in `huggingface_hub` tests, we monkeypatch these values with temporary directories. The following # lines are only used in third-party libraries tests (e.g. `transformers`, `diffusers`, etc.). _staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging") HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub") HF_TOKEN_PATH = os.path.join(_staging_home, "token")
# Here, `True` will disable progress bars globally without possibility of enabling it# programmatically. `False` will enable them without possibility of disabling them.# If environment variable is not set (None), then the user is free to enable/disable# them programmatically.# TL;DR: env variable has priority over code__HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")HF_HUB_DISABLE_PROGRESS_BARS: bool | None = ( _is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None)
# Disable symlinks in the cache (files are copied instead of symlinked)HF_HUB_DISABLE_SYMLINKS: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS"))
# Disable warning on machines that do not support symlinks (e.g. Windows non-developer)HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING"))
# Disable warning when using experimental featuresHF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING"))
# Disable sending the cached token by default is all HTTP requests to the HubHF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN"))
HF_XET_HIGH_PERFORMANCE: bool = _is_true(os.environ.get("HF_XET_HIGH_PERFORMANCE"))
# hf_transfer is not used anymore. Let's warn user is case they set the env variableif _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER")) and not HF_XET_HIGH_PERFORMANCE: import warnings
warnings.warn( "The `HF_HUB_ENABLE_HF_TRANSFER` environment variable is deprecated as 'hf_transfer' is not used anymore. " "Please use `HF_XET_HIGH_PERFORMANCE` instead to enable high performance transfer with Xet. " "Visit https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfxethighperformance for more details.", DeprecationWarning, )
# Used to override the etag timeout on a system levelHF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT
# Used to override the get request timeout on a system level# Also used as a default timeout for other requests if not specified (kept the naming for legacy reasons)HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT
# Allows to add information about the requester in the user-agent (e.g. partner name)HF_HUB_USER_AGENT_ORIGIN: str | None = os.environ.get("HF_HUB_USER_AGENT_ORIGIN")
# If OAuth didn't work after 2 redirects, there's likely a third-party cookie issue in the Space iframe view.# In this case, we redirect the user to the non-iframe view.OAUTH_MAX_REDIRECTS = 2
# OAuth-related environment variables injected by the SpaceOAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")OAUTH_CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET")OAUTH_SCOPES = os.environ.get("OAUTH_SCOPES")OPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL")
# Xet constantsHUGGINGFACE_HEADER_X_XET_ENDPOINT = "X-Xet-Cas-Url"HUGGINGFACE_HEADER_X_XET_ACCESS_TOKEN = "X-Xet-Access-Token"HUGGINGFACE_HEADER_X_XET_EXPIRATION = "X-Xet-Token-Expiration"HUGGINGFACE_HEADER_X_XET_HASH = "X-Xet-Hash"HUGGINGFACE_HEADER_X_XET_REFRESH_ROUTE = "X-Xet-Refresh-Route"HUGGINGFACE_HEADER_LINK_XET_AUTH_KEY = "xet-auth"
default_xet_cache_path = os.path.join(HF_HOME, "xet")HF_XET_CACHE = os.getenv("HF_XET_CACHE", default_xet_cache_path)HF_HUB_DISABLE_XET: bool = _is_true(os.environ.get("HF_HUB_DISABLE_XET"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684import collections.abcimport inspectimport typesfrom collections.abc import Callablefrom dataclasses import _MISSING_TYPE, MISSING, Field, field, fields, make_dataclassfrom functools import lru_cache, wrapsfrom typing import ( Annotated, Any, ForwardRef, Literal, Type, TypeVar, Union, get_args, get_origin, overload,)
try: # Python 3.11+ from typing import NotRequired, Required # type: ignoreexcept ImportError: try: # In case typing_extensions is installed from typing_extensions import NotRequired, Required # type: ignore except ImportError: # Fallback: create dummy types that will never match Required = type("Required", (), {}) # type: ignore NotRequired = type("NotRequired", (), {}) # type: ignore
from .errors import ( StrictDataclassClassValidationError, StrictDataclassDefinitionError, StrictDataclassFieldValidationError,)
Validator_T = Callable[[Any], None]T = TypeVar("T")TypedDictType = TypeVar("TypedDictType", bound=dict[str, Any])
_TYPED_DICT_DEFAULT_VALUE = object() # used as default value in TypedDict fields (to distinguish from None)
# The overload decorator helps type checkers understand the different return types@overloaddef strict(cls: Type[T]) -> Type[T]: ...
@overloaddef strict(*, accept_kwargs: bool = False) -> Callable[[Type[T]], Type[T]]: ...
def strict(cls: Type[T] | None = None, *, accept_kwargs: bool = False) -> Type[T] | Callable[[Type[T]], Type[T]]: """ Decorator to add strict validation to a dataclass.
This decorator must be used on top of `@dataclass` to ensure IDEs and static typing tools recognize the class as a dataclass.
Can be used with or without arguments: - `@strict` - `@strict(accept_kwargs=True)`
Args: cls: The class to convert to a strict dataclass. accept_kwargs (`bool`, *optional*): If True, allows arbitrary keyword arguments in `__init__`. Defaults to False.
Returns: The enhanced dataclass with strict validation on field assignment.
Example: ```py >>> from dataclasses import dataclass >>> from huggingface_hub.dataclasses import as_validated_field, strict, validated_field
>>> @as_validated_field >>> def positive_int(value: int): ... if not value >= 0: ... raise ValueError(f"Value must be positive, got {value}")
>>> @strict(accept_kwargs=True) ... @dataclass ... class User: ... name: str ... age: int = positive_int(default=10)
# Initialize >>> User(name="John") User(name='John', age=10)
# Extra kwargs are accepted >>> User(name="John", age=30, lastname="Doe") User(name='John', age=30, *lastname='Doe')
# Invalid type => raises >>> User(name="John", age="30") huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age': TypeError: Field 'age' expected int, got str (value: '30')
# Invalid value => raises >>> User(name="John", age=-1) huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age': ValueError: Value must be positive, got -1 ``` """
def wrap(cls: Type[T]) -> Type[T]: if not hasattr(cls, "__dataclass_fields__"): raise StrictDataclassDefinitionError( f"Class '{cls.__name__}' must be a dataclass before applying @strict." )
# List and store validators field_validators: dict[str, list[Validator_T]] = {} for f in fields(cls): # type: ignore [arg-type] validators = [] validators.append(_create_type_validator(f)) custom_validator = f.metadata.get("validator") if custom_validator is not None: if not isinstance(custom_validator, list): custom_validator = [custom_validator] for validator in custom_validator: if not _is_validator(validator): raise StrictDataclassDefinitionError( f"Invalid validator for field '{f.name}': {validator}. Must be a callable taking a single argument." ) validators.extend(custom_validator) field_validators[f.name] = validators cls.__validators__ = field_validators # type: ignore
# Override __setattr__ to validate fields on assignment original_setattr = cls.__setattr__
def __strict_setattr__(self: Any, name: str, value: Any) -> None: """Custom __setattr__ method for strict dataclasses.""" # Run all validators for validator in self.__validators__.get(name, []): try: validator(value) except (ValueError, TypeError) as e: raise StrictDataclassFieldValidationError(field=name, cause=e) from e
# If validation passed, set the attribute original_setattr(self, name, value)
cls.__setattr__ = __strict_setattr__ # type: ignore
if accept_kwargs: # (optional) Override __init__ to accept arbitrary keyword arguments original_init = cls.__init__
@wraps(original_init) def __init__(self, *args, **kwargs: Any) -> None: # Extract only the fields that are part of the dataclass dataclass_fields = {f.name for f in fields(cls)} # type: ignore [arg-type] standard_kwargs = {k: v for k, v in kwargs.items() if k in dataclass_fields}
# User shouldn't define custom `__init__` when `accepts_kwargs`, and instead # are advised to move field manipulation to `__post_init__` (e.g., derive new field from existing ones) # We need to call bare `__init__` here without `__post_init__` but the``original_init`` would call # post-init right away with no kwargs. if len(args) > 0: raise ValueError( f"When `accept_kwargs=True`, {cls.__name__} accepts only keyword arguments, " f"but found `{len(args)}` positional args." )
for f in fields(cls): # type: ignore if f.name in standard_kwargs: setattr(self, f.name, standard_kwargs[f.name]) elif f.default is not MISSING: setattr(self, f.name, f.default) elif f.default_factory is not MISSING: setattr(self, f.name, f.default_factory()) else: raise TypeError(f"Missing required field - '{f.name}'")
# Pass any additional kwargs to `__post_init__` and let the object # decide whether to set the attr or use for different purposes (e.g. BC checks) additional_kwargs = {} for name, value in kwargs.items(): if name not in dataclass_fields: additional_kwargs[name] = value
self.__post_init__(**additional_kwargs)
cls.__init__ = __init__ # type: ignore
# Define a default __post_init__ if not defined if not hasattr(cls, "__post_init__"):
def __post_init__(self, **kwargs: Any) -> None: """Default __post_init__ to accept additional kwargs.""" for name, value in kwargs.items(): setattr(self, name, value)
cls.__post_init__ = __post_init__ # type: ignore
# (optional) Override __repr__ to include additional kwargs original_repr = cls.__repr__
@wraps(original_repr) def __repr__(self) -> str: # Call the original __repr__ to get the standard fields standard_repr = original_repr(self)
# Get additional kwargs additional_kwargs = [ # add a '*' in front of additional kwargs to let the user know they are not part of the dataclass f"*{k}={v!r}" for k, v in self.__dict__.items() if k not in cls.__dataclass_fields__ # type: ignore [attr-defined] ] additional_repr = ", ".join(additional_kwargs)
# Combine both representations return f"{standard_repr[:-1]}, {additional_repr})" if additional_kwargs else standard_repr
if cls.__dataclass_params__.repr is True: # type: ignore [attr-defined] cls.__repr__ = __repr__ # type: ignore
# List all public methods starting with `validate_` => class validators. class_validators = []
for name in dir(cls): if not name.startswith("validate_"): continue method = getattr(cls, name) if not callable(method): continue if len(inspect.signature(method).parameters) != 1: raise StrictDataclassDefinitionError( f"Class '{cls.__name__}' has a class validator '{name}' that takes more than one argument." " Class validators must take only 'self' as an argument. Methods starting with 'validate_'" " are considered to be class validators." ) class_validators.append(method)
cls.__class_validators__ = class_validators # type: ignore
# Add `validate` method to the class, but first check if it already exists def validate(self: T) -> None: """Run class validators on the instance.""" for validator in cls.__class_validators__: # type: ignore [attr-defined] try: validator(self) except (ValueError, TypeError) as e: raise StrictDataclassClassValidationError(validator=validator.__name__, cause=e) from e
# Hack to be able to raise if `.validate()` already exists except if it was created by this decorator on a parent class # (in which case we just override it) validate.__is_defined_by_strict_decorator__ = True # type: ignore [attr-defined]
if hasattr(cls, "validate"): if not getattr(cls.validate, "__is_defined_by_strict_decorator__", False): # type: ignore [attr-defined] raise StrictDataclassDefinitionError( f"Class '{cls.__name__}' already implements a method called 'validate'." " This method name is reserved when using the @strict decorator on a dataclass." " If you want to keep your own method, please rename it." )
cls.validate = validate # type: ignore
# Run class validators after initialization initial_init = cls.__init__
@wraps(initial_init) def init_with_validate(self, *args, **kwargs) -> None: """Run class validators after initialization.""" initial_init(self, *args, **kwargs) # type: ignore [call-arg] cls.validate(self) # type: ignore [attr-defined]
setattr(cls, "__init__", init_with_validate)
return cls
# Return wrapped class or the decorator itself return wrap(cls) if cls is not None else wrap
def validate_typed_dict(schema: type[TypedDictType], data: dict) -> None: """ Validate that a dictionary conforms to the types defined in a TypedDict class.
Under the hood, the typed dict is converted to a strict dataclass and validated using the `@strict` decorator.
Args: schema (`type[TypedDictType]`): The TypedDict class defining the expected structure and types. data (`dict`): The dictionary to validate.
Raises: `StrictDataclassFieldValidationError`: If any field in the dictionary does not conform to the expected type.
Example: ```py >>> from typing import Annotated, TypedDict >>> from huggingface_hub.dataclasses import validate_typed_dict
>>> def positive_int(value: int): ... if not value >= 0: ... raise ValueError(f"Value must be positive, got {value}")
>>> class User(TypedDict): ... name: str ... age: Annotated[int, positive_int]
>>> # Valid data >>> validate_typed_dict(User, {"name": "John", "age": 30})
>>> # Invalid type for age >>> validate_typed_dict(User, {"name": "John", "age": "30"}) huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age': TypeError: Field 'age' expected int, got str (value: '30')
>>> # Invalid value for age >>> validate_typed_dict(User, {"name": "John", "age": -1}) huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age': ValueError: Value must be positive, got -1 ``` """ # Convert typed dict to dataclass strict_cls = _build_strict_cls_from_typed_dict(schema)
# Validate the data by instantiating the strict dataclass strict_cls(**data) # will raise if validation fails
@lru_cachedef _build_strict_cls_from_typed_dict(schema: type[TypedDictType]) -> Type: # Extract type hints from the TypedDict class type_hints = _get_typed_dict_annotations(schema)
# If the TypedDict is not total, wrap fields as NotRequired (unless explicitly Required or NotRequired) if not getattr(schema, "__total__", True): for key, value in type_hints.items(): origin = get_origin(value)
if origin is Annotated: base, *meta = get_args(value) if not _is_required_or_notrequired(base): base = NotRequired[base] type_hints[key] = Annotated[tuple([base] + list(meta))] # type: ignore elif not _is_required_or_notrequired(value): type_hints[key] = NotRequired[value]
# Convert type hints to dataclass fields fields = [] for key, value in type_hints.items(): if get_origin(value) is Annotated: base, *meta = get_args(value) fields.append((key, base, field(default=_TYPED_DICT_DEFAULT_VALUE, metadata={"validator": meta[0]}))) else: fields.append((key, value, field(default=_TYPED_DICT_DEFAULT_VALUE)))
# Create a strict dataclass from the TypedDict fields return strict(make_dataclass(schema.__name__, fields))
def _get_typed_dict_annotations(schema: type[TypedDictType]) -> dict[str, Any]: """Extract type annotations from a TypedDict class.""" try: # Available in Python 3.14+ import annotationlib
return annotationlib.get_annotations(schema) except ImportError: return { # We do not use `get_type_hints` here to avoid evaluating ForwardRefs (which might fail). # ForwardRefs are not validated by @strict anyway. name: value if value is not None else type(None) for name, value in schema.__dict__.get("__annotations__", {}).items() }
def validated_field( validator: list[Validator_T] | Validator_T, default: Any | _MISSING_TYPE = MISSING, default_factory: Callable[[], Any] | _MISSING_TYPE = MISSING, init: bool = True, repr: bool = True, hash: bool | None = None, compare: bool = True, metadata: dict | None = None, **kwargs: Any,) -> Any: """ Create a dataclass field with a custom validator.
Useful to apply several checks to a field. If only applying one rule, check out the [`as_validated_field`] decorator.
Args: validator (`Callable` or `list[Callable]`): A method that takes a value as input and raises ValueError/TypeError if the value is invalid. Can be a list of validators to apply multiple checks. **kwargs: Additional arguments to pass to `dataclasses.field()`.
Returns: A field with the validator attached in metadata """ if not isinstance(validator, list): validator = [validator] if metadata is None: metadata = {} metadata["validator"] = validator return field( # type: ignore default=default, # type: ignore [arg-type] default_factory=default_factory, # type: ignore [arg-type] init=init, repr=repr, hash=hash, compare=compare, metadata=metadata, **kwargs, )
def as_validated_field(validator: Validator_T): """ Decorates a validator function as a [`validated_field`] (i.e. a dataclass field with a custom validator).
Args: validator (`Callable`): A method that takes a value as input and raises ValueError/TypeError if the value is invalid. """
def _inner( default: Any | _MISSING_TYPE = MISSING, default_factory: Callable[[], Any] | _MISSING_TYPE = MISSING, init: bool = True, repr: bool = True, hash: bool | None = None, compare: bool = True, metadata: dict | None = None, **kwargs: Any, ): return validated_field( validator, default=default, default_factory=default_factory, init=init, repr=repr, hash=hash, compare=compare, metadata=metadata, **kwargs, )
return _inner
def type_validator(name: str, value: Any, expected_type: Any) -> None: """Validate that 'value' matches 'expected_type'.""" origin = get_origin(expected_type) args = get_args(expected_type)
if expected_type is Any: return elif expected_type is None: _validate_none(name, value) elif validator := _BASIC_TYPE_VALIDATORS.get(origin): validator(name, value, args) elif isinstance(expected_type, type): # simple types _validate_simple_type(name, value, expected_type) elif isinstance(expected_type, ForwardRef) or isinstance(expected_type, str): return elif origin is Required: if value is _TYPED_DICT_DEFAULT_VALUE: raise TypeError(f"Field '{name}' is required but missing.") type_validator(name, value, args[0]) elif origin is NotRequired: if value is _TYPED_DICT_DEFAULT_VALUE: return type_validator(name, value, args[0]) else: raise TypeError(f"Unsupported type for field '{name}': {expected_type}")
def _validate_none(name: str, value: Any) -> None: """Validate None type.
'None' is not a type, it's a special value. Type should be `NoneType` instead. But in type annotations 'None' is accepted so we must support it. """ if value is not None: raise TypeError(f"Field '{name}' expected None, got {type(value).__name__}")
def _validate_union(name: str, value: Any, args: tuple[Any, ...]) -> None: """Validate that value matches one of the types in a Union.""" errors = [] for t in args: try: type_validator(name, value, t) return # Valid if any type matches except TypeError as e: errors.append(str(e))
raise TypeError( f"Field '{name}' with value {repr(value)} doesn't match any type in {args}. Errors: {'; '.join(errors)}" )
def _validate_literal(name: str, value: Any, args: tuple[Any, ...]) -> None: """Validate Literal type.""" if isinstance(value, bool): if value not in [arg for arg in args if isinstance(arg, bool)]: raise TypeError(f"Field '{name}' expected one of {args}, got {value}") elif isinstance(value, int): if value not in [arg for arg in args if isinstance(arg, int) and not isinstance(arg, bool)]: raise TypeError(f"Field '{name}' expected one of {args}, got {value}") elif value not in args: raise TypeError(f"Field '{name}' expected one of {args}, got {value}")
def _validate_list(name: str, value: Any, args: tuple[Any, ...]) -> None: """Validate list[T] type.""" if not isinstance(value, list): raise TypeError(f"Field '{name}' expected a list, got {type(value).__name__}")
# Validate each item in the list item_type = args[0] for i, item in enumerate(value): try: type_validator(f"{name}[{i}]", item, item_type) except TypeError as e: raise TypeError(f"Invalid item at index {i} in list '{name}'") from e
def _validate_dict(name: str, value: Any, args: tuple[Any, ...]) -> None: """Validate dict[K, V] type.""" if not isinstance(value, dict): raise TypeError(f"Field '{name}' expected a dict, got {type(value).__name__}")
# Validate keys and values key_type, value_type = args for k, v in value.items(): try: type_validator(f"{name}.key", k, key_type) type_validator(f"{name}[{k!r}]", v, value_type) except TypeError as e: raise TypeError(f"Invalid key or value in dict '{name}'") from e
def _validate_tuple(name: str, value: Any, args: tuple[Any, ...]) -> None: """Validate Tuple type.""" if not isinstance(value, tuple): raise TypeError(f"Field '{name}' expected a tuple, got {type(value).__name__}")
# Handle variable-length tuples: tuple[T, ...] if len(args) == 2 and args[1] is Ellipsis: for i, item in enumerate(value): try: type_validator(f"{name}[{i}]", item, args[0]) except TypeError as e: raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e # Handle fixed-length tuples: tuple[T1, T2, ...] elif len(args) != len(value): raise TypeError(f"Field '{name}' expected a tuple of length {len(args)}, got {len(value)}") else: for i, (item, expected) in enumerate(zip(value, args)): try: type_validator(f"{name}[{i}]", item, expected) except TypeError as e: raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e
def _validate_set(name: str, value: Any, args: tuple[Any, ...]) -> None: """Validate set[T] type.""" if not isinstance(value, set): raise TypeError(f"Field '{name}' expected a set, got {type(value).__name__}")
# Validate each item in the set item_type = args[0] for i, item in enumerate(value): try: type_validator(f"{name} item", item, item_type) except TypeError as e: raise TypeError(f"Invalid item in set '{name}'") from e
def _validate_sequence(name: str, value: Any, args: tuple[Any, ...]) -> None: """Validate Sequence or Sequence[T] type.""" if not isinstance(value, collections.abc.Sequence): raise TypeError(f"Field '{name}' expected a Sequence, got {type(value).__name__}")
# If no type argument is provided (i.e., just `Sequence`), skip item validation if not args: return
# Validate each item in the sequence item_type = args[0] for i, item in enumerate(value): try: type_validator(f"{name}[{i}]", item, item_type) except TypeError as e: raise TypeError(f"Invalid item at index {i} in sequence '{name}'") from e
def _validate_simple_type(name: str, value: Any, expected_type: type) -> None: """Validate simple type (int, str, etc.).""" if expected_type is int and isinstance(value, bool): raise TypeError( f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})" ) if not isinstance(value, expected_type): raise TypeError( f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})" )
def _create_type_validator(field: Field) -> Validator_T: """Create a type validator function for a field.""" # Hacky: we cannot use a lambda here because of reference issues
def validator(value: Any) -> None: type_validator(field.name, value, field.type)
return validator
def _is_validator(validator: Any) -> bool: """Check if a function is a validator.
A validator is a Callable that can be called with a single positional argument. The validator can have more arguments with default values.
Basically, returns True if `validator(value)` is possible. """ if not callable(validator): return False
signature = inspect.signature(validator) parameters = list(signature.parameters.values()) if len(parameters) == 0: return False if parameters[0].kind not in ( inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.VAR_POSITIONAL, ): return False for parameter in parameters[1:]: if parameter.default == inspect.Parameter.empty: return False return True
def _is_required_or_notrequired(type_hint: Any) -> bool: """Helper to check if a type is Required/NotRequired.""" return type_hint in (Required, NotRequired) or (get_origin(type_hint) in (Required, NotRequired))
_BASIC_TYPE_VALIDATORS: dict[Any, Callable[[str, Any, tuple[Any, ...]], None]] = { Union: _validate_union, Literal: _validate_literal, list: _validate_list, dict: _validate_dict, tuple: _validate_tuple, set: _validate_set, collections.abc.Sequence: _validate_sequence,}
# TODO: make it first class citizen when bumping to Python 3.10+_BASIC_TYPE_VALIDATORS[types.UnionType] = _validate_union # x | y syntax, available only Python 3.10+
__all__ = [ "strict", "validate_typed_dict", "validated_field", "Validator_T", "StrictDataclassClassValidationError", "StrictDataclassDefinitionError", "StrictDataclassFieldValidationError",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473"""Contains all custom errors."""
from pathlib import Path
from httpx import HTTPError, Response
# CACHE ERRORS
class CacheNotFound(Exception): """Exception thrown when the Huggingface cache is not found."""
cache_dir: str | Path
def __init__(self, msg: str, cache_dir: str | Path, *args, **kwargs): super().__init__(msg, *args, **kwargs) self.cache_dir = cache_dir
class CorruptedCacheException(Exception): """Exception for any unexpected structure in the Huggingface cache-system."""
# HEADERS ERRORS
class LocalTokenNotFoundError(EnvironmentError): """Raised if local token is required but not found."""
# HTTP ERRORS
class OfflineModeIsEnabled(ConnectionError): """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""
class HfHubHTTPError(HTTPError, OSError): """ HTTPError to inherit from for any custom HTTP Error raised in HF Hub.
Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is sent back by the server, it will be added to the error message.
Added details: - Request ID sourced from headers in order of precedence: "X-Request-Id", "X-Amzn-Trace-Id", "X-Amz-Cf-Id". - Server error message from the header "X-Error-Message". - Server error message if we can found one in the response body.
Example: ```py import httpx from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
response = get_session().post(...) try: hf_raise_for_status(response) except HfHubHTTPError as e: print(str(e)) # formatted message e.request_id, e.server_message # details returned by server
# Complete the error message with additional information once it's raised e.append_to_message("\n`create_commit` expects the repository to exist.") raise ``` """
def __init__( self, message: str, *, response: Response, server_message: str | None = None, ): self.request_id = ( response.headers.get("x-request-id") or response.headers.get("X-Amzn-Trace-Id") or response.headers.get("x-amz-cf-id") ) self.server_message = server_message self.response = response self.request = response.request super().__init__(message)
def append_to_message(self, additional_message: str) -> None: """Append additional information to the `HfHubHTTPError` initial message.""" self.args = (self.args[0] + additional_message,) + self.args[1:]
@classmethod def _reconstruct_hf_hub_http_error( cls, message: str, response: Response, server_message: str | None ) -> "HfHubHTTPError": return cls(message, response=response, server_message=server_message)
def __reduce_ex__(self, protocol): """Fix pickling of Exception subclass with kwargs. We need to override __reduce_ex__ of the parent class""" return (self.__class__._reconstruct_hf_hub_http_error, (str(self), self.response, self.server_message))
# INFERENCE CLIENT ERRORS
class InferenceTimeoutError(HTTPError, TimeoutError): """Error raised when a model is unavailable or the request times out."""
# INFERENCE ENDPOINT ERRORS
class InferenceEndpointError(Exception): """Generic exception when dealing with Inference Endpoints."""
class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError): """Exception for timeouts while waiting for Inference Endpoint."""
# SAFETENSORS ERRORS
class SafetensorsParsingError(Exception): """Raised when failing to parse a safetensors file metadata.
This can be the case if the file is not a safetensors file or does not respect the specification. """
class NotASafetensorsRepoError(Exception): """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a `model.safetensors.index.json` file. """
# TEXT GENERATION ERRORS
class TextGenerationError(HTTPError): """Generic error raised if text-generation went wrong."""
# Text Generation Inference Errorsclass ValidationError(TextGenerationError): """Server-side validation error."""
class GenerationError(TextGenerationError): pass
class OverloadedError(TextGenerationError): pass
class IncompleteGenerationError(TextGenerationError): pass
class UnknownError(TextGenerationError): pass
# VALIDATION ERRORS
class HFValidationError(ValueError): """Generic exception thrown by `huggingface_hub` validators.
Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError). """
# FILE METADATA ERRORS
class DryRunError(OSError): """Error triggered when a dry run is requested but cannot be performed (e.g. invalid repo)."""
class FileMetadataError(OSError): """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).
Inherits from `OSError` for backward compatibility. """
# BUCKET ERRORS
class BucketNotFoundError(HfHubHTTPError): """ Raised when trying to access a bucket that does not exist.
Attributes: bucket_id (`str` or `None`): The bucket id (namespace/name) that was not found, if it could be determined from the request URL.
Example:
```py >>> from huggingface_hub import bucket_info >>> bucket_info("<non_existent_bucket>") (...) huggingface_hub.errors.BucketNotFoundError: 404 Client Error. (Request ID: XXX)
Bucket Not Found for url: https://huggingface.co/api/buckets/namespace/name. Please make sure you specified the correct bucket id (namespace/name). If the bucket is private, make sure you are authenticated and your token has the required permissions. ``` """
bucket_id: str | None = None
# REPOSITORY ERRORS
class RepositoryNotFoundError(HfHubHTTPError): """ Raised when trying to access a hf.co URL with an invalid repository name, or with a private repo name the user does not have access to.
Attributes: repo_id (`str` or `None`): The repo id that was not found, if it could be determined from the request URL. repo_type (`str` or `None`): The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
Example:
```py >>> from huggingface_hub import model_info >>> model_info("<non_existent_repository>") (...) huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E. Please make sure you specified the correct `repo_id` and `repo_type`. If the repo is private, make sure you are authenticated and your token has the required permissions. Invalid username or password. ``` """
repo_id: str | None = None repo_type: str | None = None
class GatedRepoError(RepositoryNotFoundError): """ Raised when trying to access a gated repository for which the user is not on the authorized list.
Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.
Example:
```py >>> from huggingface_hub import model_info >>> model_info("<gated_repository>") (...) huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model. Access to model ardent-figment/gated-model is restricted and you are not in the authorized list. Visit https://huggingface.co/ardent-figment/gated-model to ask for access. ``` """
class DisabledRepoError(HfHubHTTPError): """ Raised when trying to access a repository that has been disabled by its author.
Example:
```py >>> from huggingface_hub import dataset_info >>> dataset_info("laion/laion-art") (...) huggingface_hub.errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)
Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art. Access to this resource is disabled. ``` """
# REVISION ERROR
class RevisionNotFoundError(HfHubHTTPError): """ Raised when trying to access a hf.co URL with a valid repository but an invalid revision.
Attributes: repo_id (`str` or `None`): The repo id, if it could be determined from the request URL. repo_type (`str` or `None`): The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
Example:
```py >>> from huggingface_hub import hf_hub_download >>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>') (...) huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json. ``` """
repo_id: str | None = None repo_type: str | None = None
# ENTRY ERRORSclass EntryNotFoundError(Exception): """ Raised when entry not found, either locally or remotely.
Example:
```py >>> from huggingface_hub import hf_hub_download >>> hf_hub_download('bert-base-cased', '<non-existent-file>') (...) huggingface_hub.errors.RemoteEntryNotFoundError (...) >>> hf_hub_download('bert-base-cased', '<non-existent-file>', local_files_only=True) (...) huggingface_hub.utils.errors.LocalEntryNotFoundError (...) ``` """
class RemoteEntryNotFoundError(HfHubHTTPError, EntryNotFoundError): """ Raised when trying to access a hf.co URL with a valid repository and revision but an invalid filename.
Attributes: repo_id (`str` or `None`): The repo id, if it could be determined from the request URL. repo_type (`str` or `None`): The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
Example:
```py >>> from huggingface_hub import hf_hub_download >>> hf_hub_download('bert-base-cased', '<non-existent-file>') (...) huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E. ``` """
repo_id: str | None = None repo_type: str | None = None
class LocalEntryNotFoundError(FileNotFoundError, EntryNotFoundError): """ Raised when trying to access a file or snapshot that is not on the disk when network is disabled or unavailable (connection issue). The entry may exist on the Hub.
Example:
```py >>> from huggingface_hub import hf_hub_download >>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True) (...) 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. ``` """
def __init__(self, message: str): super().__init__(message)
# REQUEST ERRORclass BadRequestError(HfHubHTTPError, ValueError): """ Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.
Example:
```py >>> resp = httpx.post("hf.co/api/check", ...) >>> hf_raise_for_status(resp, endpoint_name="check") huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX) ``` """
# DDUF file format ERROR
class DDUFError(Exception): """Base exception for errors related to the DDUF format."""
class DDUFCorruptedFileError(DDUFError): """Exception thrown when the DDUF file is corrupted."""
class DDUFExportError(DDUFError): """Base exception for errors during DDUF export."""
class DDUFInvalidEntryNameError(DDUFExportError): """Exception thrown when the entry name is invalid."""
# STRICT DATACLASSES ERRORS
class StrictDataclassError(Exception): """Base exception for strict dataclasses."""
class StrictDataclassDefinitionError(StrictDataclassError): """Exception thrown when a strict dataclass is defined incorrectly."""
class StrictDataclassFieldValidationError(StrictDataclassError): """Exception thrown when a strict dataclass fails validation for a given field."""
def __init__(self, field: str, cause: Exception): error_message = f"Validation error for field '{field}':" error_message += f"\n {cause.__class__.__name__}: {cause}" super().__init__(error_message)
class StrictDataclassClassValidationError(StrictDataclassError): """Exception thrown when a strict dataclass fails validation on a class validator."""
def __init__(self, validator: str, cause: Exception): error_message = f"Class validation error for validator '{validator}':" error_message += f"\n {cause.__class__.__name__}: {cause}" super().__init__(error_message)
# XET ERRORS
class XetError(Exception): """Base exception for errors related to Xet Storage."""
class XetAuthorizationError(XetError): """Exception thrown when the user does not have the right authorization to use Xet Storage."""
class XetRefreshTokenError(XetError): """Exception thrown when the refresh token is invalid."""
class XetDownloadError(Exception): """Exception thrown when the download from Xet Storage fails."""
# CLI ERRORS
class CLIError(Exception): """CLI error with clean message (no traceback by default)."""
class CLIExtensionInstallError(CLIError): """Error during CLI extension installation."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414import jsonimport osfrom pathlib import Pathfrom pickle import DEFAULT_PROTOCOL, PicklingErrorfrom typing import Any
from packaging import version
from huggingface_hub import constants, snapshot_downloadfrom huggingface_hub.hf_api import HfApifrom huggingface_hub.utils import ( SoftTemporaryDirectory, get_fastai_version, get_fastcore_version, get_python_version,)
from .utils import logging, validate_hf_hub_args
logger = logging.get_logger(__name__)
def _check_fastai_fastcore_versions( fastai_min_version: str = "2.4", fastcore_min_version: str = "1.3.27",): """ Checks that the installed fastai and fastcore versions are compatible for pickle serialization.
Args: fastai_min_version (`str`, *optional*): The minimum fastai version supported. fastcore_min_version (`str`, *optional*): The minimum fastcore version supported.
> [!TIP] > Raises the following error: > > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) > if the fastai or fastcore libraries are not available or are of an invalid version. """
if (get_fastcore_version() or get_fastai_version()) == "N/A": raise ImportError( f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are" f" required. Currently using fastai=={get_fastai_version()} and" f" fastcore=={get_fastcore_version()}." )
current_fastai_version = version.Version(get_fastai_version()) current_fastcore_version = version.Version(get_fastcore_version())
if current_fastai_version < version.Version(fastai_min_version): raise ImportError( "`push_to_hub_fastai` and `from_pretrained_fastai` require a" f" fastai>={fastai_min_version} version, but you are using fastai version" f" {get_fastai_version()} which is incompatible. Upgrade with `pip install" " fastai==2.5.6`." )
if current_fastcore_version < version.Version(fastcore_min_version): raise ImportError( "`push_to_hub_fastai` and `from_pretrained_fastai` require a" f" fastcore>={fastcore_min_version} version, but you are using fastcore" f" version {get_fastcore_version()} which is incompatible. Upgrade with" " `pip install fastcore==1.3.27`." )
def _check_fastai_fastcore_pyproject_versions( storage_folder: str, fastai_min_version: str = "2.4", fastcore_min_version: str = "1.3.27",): """ Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist or does not contain versions for fastai and fastcore, then it logs a warning.
Args: storage_folder (`str`): Folder to look for the `pyproject.toml` file. fastai_min_version (`str`, *optional*): The minimum fastai version supported. fastcore_min_version (`str`, *optional*): The minimum fastcore version supported.
> [!TIP] > Raises the following errors: > > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) > if the `toml` module is not installed. > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) > if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore. """
try: import toml except ModuleNotFoundError: raise ImportError( "`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module." " Install it with `pip install toml`." )
# Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages. if not os.path.isfile(f"{storage_folder}/pyproject.toml"): logger.warning( "There is no `pyproject.toml` in the repository that contains the fastai" " `Learner`. The `pyproject.toml` would allow us to verify that your fastai" " and fastcore versions are compatible with those of the model you want to" " load." ) return pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml")
if "build-system" not in pyproject_toml.keys(): logger.warning( "There is no `build-system` section in the pyproject.toml of the repository" " that contains the fastai `Learner`. The `build-system` would allow us to" " verify that your fastai and fastcore versions are compatible with those" " of the model you want to load." ) return build_system_toml = pyproject_toml["build-system"]
if "requires" not in build_system_toml.keys(): logger.warning( "There is no `requires` section in the pyproject.toml of the repository" " that contains the fastai `Learner`. The `requires` would allow us to" " verify that your fastai and fastcore versions are compatible with those" " of the model you want to load." ) return package_versions = build_system_toml["requires"]
# Extracts contains fastai and fastcore versions from `pyproject.toml` if available. # If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest. fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")] if len(fastai_packages) == 0: logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.") # fastai_version is an empty string if not specified else: fastai_version = str(fastai_packages[0]).partition("=")[2] if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version): raise ImportError( "`from_pretrained_fastai` requires" f" fastai>={fastai_min_version} version but the model to load uses" f" {fastai_version} which is incompatible." )
fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")] if len(fastcore_packages) == 0: logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.") # fastcore_version is an empty string if not specified else: fastcore_version = str(fastcore_packages[0]).partition("=")[2] if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version): raise ImportError( "`from_pretrained_fastai` requires" f" fastcore>={fastcore_min_version} version, but you are using fastcore" f" version {fastcore_version} which is incompatible." )
README_TEMPLATE = """---tags:- fastai---
# Amazing!
🥳 Congratulations on hosting your fastai model on the Hugging Face Hub!
# Some next steps1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))!
2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)).
3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)!
Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card.
---
# Model card
## Model descriptionMore information needed
## Intended uses & limitationsMore information needed
## Training and evaluation dataMore information needed"""
PYPROJECT_TEMPLATE = f"""[build-system]requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]build-backend = "setuptools.build_meta:__legacy__""""
def _create_model_card(repo_dir: Path): """ Creates a model card for the repository.
Args: repo_dir (`Path`): Directory where model card is created. """ readme_path = repo_dir / "README.md"
if not readme_path.exists(): with readme_path.open("w", encoding="utf-8") as f: f.write(README_TEMPLATE)
def _create_model_pyproject(repo_dir: Path): """ Creates a `pyproject.toml` for the repository.
Args: repo_dir (`Path`): Directory where `pyproject.toml` is created. """ pyproject_path = repo_dir / "pyproject.toml"
if not pyproject_path.exists(): with pyproject_path.open("w", encoding="utf-8") as f: f.write(PYPROJECT_TEMPLATE)
def _save_pretrained_fastai( learner, save_directory: str | Path, config: dict[str, Any] | None = None,): """ Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used.
Args: learner (`Learner`): The `fastai.Learner` you'd like to save. save_directory (`str` or `Path`): Specific directory in which you want to save the fastai learner. config (`dict`, *optional*): Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'.
> [!TIP] > Raises the following error: > > - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) > if the config file provided is not a dictionary. """ _check_fastai_fastcore_versions()
os.makedirs(save_directory, exist_ok=True)
# if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE. if config is not None: if not isinstance(config, dict): raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'") path = os.path.join(save_directory, constants.CONFIG_NAME) with open(path, "w") as f: json.dump(config, f)
_create_model_card(Path(save_directory)) _create_model_pyproject(Path(save_directory))
# learner.export saves the model in `self.path`. learner.path = Path(save_directory) os.makedirs(save_directory, exist_ok=True) try: learner.export( fname="model.pkl", pickle_protocol=DEFAULT_PROTOCOL, ) except PicklingError: raise PicklingError( "You are using a lambda function, i.e., an anonymous function. `pickle`" " cannot pickle function objects and requires that all functions have" " names. One possible solution is to name the function." )
@validate_hf_hub_argsdef from_pretrained_fastai( repo_id: str, revision: str | None = None,): """ Load pretrained fastai model from the Hub or from a local directory.
Args: repo_id (`str`): The location where the pickled fastai.Learner is. It can be either of the two: - Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'. You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`. Revision is the specific model version to use. Since we use a git-based system for storing models and other artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id. - Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`. revision (`str`, *optional*): Revision at which the repo's files are downloaded. See documentation of `snapshot_download`.
Returns: The `fastai.Learner` model in the `repo_id` repo. """ _check_fastai_fastcore_versions()
# Load the `repo_id` repo. # `snapshot_download` returns the folder where the model was stored. # `cache_dir` will be the default '/root/.cache/huggingface/hub' if not os.path.isdir(repo_id): storage_folder = snapshot_download( repo_id=repo_id, revision=revision, library_name="fastai", library_version=get_fastai_version(), ) else: storage_folder = repo_id
_check_fastai_fastcore_pyproject_versions(storage_folder)
from fastai.learner import load_learner # type: ignore
return load_learner(os.path.join(storage_folder, "model.pkl"))
@validate_hf_hub_argsdef push_to_hub_fastai( learner, *, repo_id: str, commit_message: str = "Push FastAI model using huggingface_hub.", private: bool | None = None, token: str | None = None, config: dict | None = None, branch: str | None = None, create_pr: bool | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, delete_patterns: list[str] | str | None = None, api_endpoint: str | None = None,): """ Upload learner checkpoint files to the Hub.
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more details.
Args: learner (`Learner`): The `fastai.Learner' you'd like to push to the Hub. repo_id (`str`): 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'). commit_message (`str`, *optional*): Message to commit while pushing. Will default to :obj:`"add model"`. private (`bool`, *optional*): Whether or not the repository created should be private. If `None` (default), will default to been public except if the organization's default is private. token (`str`, *optional*): 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. config (`dict`, *optional*): Configuration object to be saved alongside the model weights. branch (`str`, *optional*): The git branch on which to push the model. This defaults to the default branch as specified in your repository, which defaults to `"main"`. create_pr (`boolean`, *optional*): Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`. api_endpoint (`str`, *optional*): The API endpoint to use when pushing the model to the hub. allow_patterns (`list[str]` or `str`, *optional*): If provided, only files matching at least one pattern are pushed. ignore_patterns (`list[str]` or `str`, *optional*): If provided, files matching any of the patterns are not pushed. delete_patterns (`list[str]` or `str`, *optional*): If provided, remote files matching any of the patterns will be deleted from the repo.
Returns: The url of the commit of your model in the given repository.
> [!TIP] > Raises the following error: > > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) > if the user is not log on to the Hugging Face Hub. """ _check_fastai_fastcore_versions() api = HfApi(endpoint=api_endpoint) repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
# Push the files to the repo in a single commit with SoftTemporaryDirectory() as tmp: saved_path = Path(tmp) / repo_id _save_pretrained_fastai(learner, saved_path, config=config) return api.upload_folder( repo_id=repo_id, token=token, folder_path=saved_path, commit_message=commit_message, revision=branch, create_pr=create_pr, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, delete_patterns=delete_patterns, ).cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/METADATAAdded+324
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/WHEELAdded+5
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/entry_points.txtAdded+7
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/licenses/LICENSEAdded+201
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/top_level.txtAdded+1
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/__init__.pyAdded+1717
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_buckets.pyAdded+1193
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_commit_api.pyAdded+976
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_commit_scheduler.pyAdded+353
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_dataset_viewer.pyAdded+172
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_eval_results.pyAdded+211
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_inference_endpoints.pyAdded+418
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_jobs_api.pyAdded+410
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_local_folder.pyAdded+473
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_login.pyAdded+494
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_oauth.pyAdded+460
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_snapshot_download.pyAdded+471
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_space_api.pyAdded+251
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_tensorboard_logger.pyAdded+189
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_upload_large_folder.pyAdded+766
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_webhooks_payload.pyAdded+136
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_webhooks_server.pyAdded+376
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/auth.pyAdded+165
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/buckets.pyAdded+1082
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/cache.pyAdded+812
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/collections.pyAdded+331
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/datasets.pyAdded+175
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/deprecated_cli.pyAdded+35
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/discussions.pyAdded+595
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/download.pyAdded+224
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/extensions.pyAdded+620
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/hf.pyAdded+127
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/inference_endpoints.pyAdded+463
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/jobs.pyAdded+1150
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/lfs.pyAdded+175
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/models.pyAdded+133
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/papers.pyAdded+203
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/repo_files.pyAdded+86
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/repos.pyAdded+524
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/skills.pyAdded+446
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/spaces.pyAdded+437
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/system.pyAdded+28
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/upload.pyAdded+300
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/upload_large_folder.pyAdded+130
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/webhooks.pyAdded+310
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/community.pyAdded+363
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/constants.pyAdded+291
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/dataclasses.pyAdded+684
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/errors.pyAdded+473
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/fastai_utils.pyAdded+414