text
stringlengths 3
7.31k
| source
stringclasses 40
values | file_type
stringclasses 1
value | id
stringlengths 3
6
|
---|---|---|---|
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_0 |
The [Hugging Face Hub](https://huggingface.co/) is the go-to place for sharing machine learning
models, demos, datasets, and metrics. `huggingface_hub` library helps you interact with
the Hub without leaving your development environment. You can create and manage
repositories easily, download and upload files, and get useful model and dataset
metadata from the Hub. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_1 |
To get started, install the `huggingface_hub` library:
```bash
pip install --upgrade huggingface_hub
```
For more details, check out the [installation](installation) guide. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_2 |
Repositories on the Hub are git version controlled, and users can download a single file
or the whole repository. You can use the [`hf_hub_download`] function to download files.
This function will download and cache a file on your local disk. The next time you need
that file, it will load from your cache, so you don't need to re-download it.
You will need the repository id and the filename of the file you want to download. For
example, to download the [Pegasus](https://huggingface.co/google/pegasus-xsum) model
configuration file:
```py
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download(repo_id="google/pegasus-xsum", filename="config.json")
```
To download a specific version of the file, use the `revision` parameter to specify the
branch name, tag, or commit hash. If you choose to use the commit hash, it must be the
full-length hash instead of the shorter 7-character commit hash:
```py
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download(
... repo_id="google/pegasus-xsum",
... filename="config.json",
... revision="4d33b01d79672f27f001f6abade33f22d993b151"
... )
```
For more details and options, see the API reference for [`hf_hub_download`].
<a id="login"></a> <!-- backward compatible anchor --> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_3 |
In a lot of cases, you must be authenticated with a Hugging Face account to interact with
the Hub: download private repos, upload files, create PRs,...
[Create an account](https://huggingface.co/join) if you don't already have one, and then sign in
to get your [User Access Token](https://huggingface.co/docs/hub/security-tokens) from
your [Settings page](https://huggingface.co/settings/tokens). The User Access Token is
used to authenticate your identity to the Hub.
<Tip>
Tokens can have `read` or `write` permissions. Make sure to have a `write` access token if you want to create or edit a repository. Otherwise, it's best to generate a `read` token to reduce risk in case your token is inadvertently leaked.
</Tip> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_4 |
The easiest way to authenticate is to save the token on your machine. You can do that from the terminal using the [`login`] command:
```bash
huggingface-cli login
```
The command will tell you if you are already logged in and prompt you for your token. The token is then validated and saved in your `HF_HOME` directory (defaults to `~/.cache/huggingface/token`). Any script or library interacting with the Hub will use this token when sending requests.
Alternatively, you can programmatically login using [`login`] in a notebook or a script:
```py
>>> from huggingface_hub import login
>>> login()
```
You can only be logged in to one account at a time. Logging in to a new account will automatically log you out of the previous one. To determine your currently active account, simply run the `huggingface-cli whoami` command.
<Tip warning={true}>
Once logged in, all requests to the Hub - even methods that don't necessarily require authentication - will use your access token by default. If you want to disable the implicit use of your token, you should set `HF_HUB_DISABLE_IMPLICIT_TOKEN=1` as an environment variable (see [reference](../package_reference/environment_variables#hfhubdisableimplicittoken)).
</Tip> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_5 |
You can save multiple tokens on your machine by simply logging in with the [`login`] command with each token. If you need to switch between these tokens locally, you can use the [`auth switch`] command:
```bash
huggingface-cli auth switch
```
This command will prompt you to select a token by its name from a list of saved tokens. Once selected, the chosen token becomes the _active_ token, and it will be used for all interactions with the Hub.
You can list all available access tokens on your machine with `huggingface-cli auth list`. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_6 |
The environment variable `HF_TOKEN` can also be used to authenticate yourself. This is especially useful in a Space where you can set `HF_TOKEN` as a [Space secret](https://huggingface.co/docs/hub/spaces-overview#managing-secrets).
<Tip>
**NEW:** Google Colaboratory lets you define [private keys](https://twitter.com/GoogleColab/status/1719798406195867814) for your notebooks. Define a `HF_TOKEN` secret to be automatically authenticated!
</Tip>
Authentication via an environment variable or a secret has priority over the token stored on your machine. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_7 |
Finally, it is also possible to authenticate by passing your token to any method that accepts `token` as a parameter.
```
from huggingface_hub import whoami
user = whoami(token=...)
```
This is usually discouraged except in an environment where you don't want to store your token permanently or if you need to handle several tokens at once.
<Tip warning={true}>
Please be careful when passing tokens as a parameter. It is always best practice to load the token from a secure vault instead of hardcoding it in your codebase or notebook. Hardcoded tokens present a major leak risk if you share your code inadvertently.
</Tip> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_8 |
Once you've registered and logged in, create a repository with the [`create_repo`]
function:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.create_repo(repo_id="super-cool-model")
```
If you want your repository to be private, then:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.create_repo(repo_id="super-cool-model", private=True)
```
Private repositories will not be visible to anyone except yourself.
<Tip>
To create a repository or to push content to the Hub, you must provide a User Access
Token that has the `write` permission. You can choose the permission when creating the
token in your [Settings page](https://huggingface.co/settings/tokens).
</Tip> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_9 |
Use the [`upload_file`] function to add a file to your newly created repository. You
need to specify:
1. The path of the file to upload.
2. The path of the file in the repository.
3. The repository id of where you want to add the file.
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.upload_file(
... path_or_fileobj="/home/lysandre/dummy-test/README.md",
... path_in_repo="README.md",
... repo_id="lysandre/test-model",
... )
```
To upload more than one file at a time, take a look at the [Upload](./guides/upload) guide
which will introduce you to several methods for uploading files (with or without git). | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_10 |
The `huggingface_hub` library provides an easy way for users to interact with the Hub
with Python. To learn more about how you can manage your files and repositories on the
Hub, we recommend reading our [how-to guides](./guides/overview) to:
- [Manage your repository](./guides/repository).
- [Download](./guides/download) files from the Hub.
- [Upload](./guides/upload) files to the Hub.
- [Search the Hub](./guides/search) for your desired model or dataset.
- [Access the Inference API](./guides/inference) for fast inference. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/quick-start.md | .md | 0_11 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/index.md | .md | 1_0 |
The `huggingface_hub` library allows you to interact with the [Hugging Face
Hub](https://hf.co), a machine learning platform for creators and collaborators.
Discover pre-trained models and datasets for your projects or play with the hundreds of
machine learning apps hosted on the Hub. You can also create and share your own models
and datasets with the community. The `huggingface_hub` library provides a simple way to
do all these things with Python.
Read the [quick start guide](quick-start) to get up and running with the
`huggingface_hub` library. You will learn how to download files from the Hub, create a
repository, and upload files to the Hub. Keep reading to learn more about how to manage
your repositories on the π€ Hub, how to interact in discussions or even how to access
the Inference API.
<div class="mt-10">
<div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
<a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./guides/overview">
<div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">How-to guides</div>
<p class="text-gray-700">Practical guides to help you achieve a specific goal. Take a look at these guides to learn how to use huggingface_hub to solve real-world problems.</p>
</a>
<a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./package_reference/overview">
<div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Reference</div>
<p class="text-gray-700">Exhaustive and technical description of huggingface_hub classes and methods.</p>
</a>
<a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./concepts/git_vs_http">
<div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div>
<p class="text-gray-700">High-level explanations for building a better understanding of huggingface_hub philosophy.</p>
</a>
</div>
</div>
<!--
<a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/overview"
><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div>
<p class="text-gray-700">Learn the basics and become familiar with using huggingface_hub to programmatically interact with the π€ Hub!</p>
</a> --> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/index.md | .md | 1_1 |
All contributions to the `huggingface_hub` are welcomed and equally valued! π€ Besides
adding or fixing existing issues in the code, you can also help improve the
documentation by making sure it is accurate and up-to-date, help answer questions on
issues, and request new features you think will improve the library. Take a look at the
[contribution
guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to
learn more about how to submit a new issue or feature request, how to submit a pull
request, and how to test your contributions to make sure everything works as expected.
Contributors should also be respectful of our [code of
conduct](https://github.com/huggingface/huggingface_hub/blob/main/CODE_OF_CONDUCT.md) to
create an inclusive and welcoming collaborative space for everyone. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/index.md | .md | 1_2 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_0 |
Before you start, you will need to setup your environment by installing the appropriate packages.
`huggingface_hub` is tested on **Python 3.8+**. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_1 |
It is highly recommended to install `huggingface_hub` in a [virtual environment](https://docs.python.org/3/library/venv.html).
If you are unfamiliar with Python virtual environments, take a look at this [guide](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/).
A virtual environment makes it easier to manage different projects, and avoid compatibility issues between dependencies.
Start by creating a virtual environment in your project directory:
```bash
python -m venv .env
```
Activate the virtual environment. On Linux and macOS:
```bash
source .env/bin/activate
```
Activate virtual environment on Windows:
```bash
.env/Scripts/activate
```
Now you're ready to install `huggingface_hub` [from the PyPi registry](https://pypi.org/project/huggingface-hub/):
```bash
pip install --upgrade huggingface_hub
```
Once done, [check installation](#check-installation) is working correctly. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_2 |
Some dependencies of `huggingface_hub` are [optional](https://setuptools.pypa.io/en/latest/userguide/dependency_management.html#optional-dependencies) because they are not required to run the core features of `huggingface_hub`. However, some features of the `huggingface_hub` may not be available if the optional dependencies aren't installed.
You can install optional dependencies via `pip`:
```bash
# Install dependencies for tensorflow-specific features
# /!\ Warning: this is not equivalent to `pip install tensorflow`
pip install 'huggingface_hub[tensorflow]'
# Install dependencies for both torch-specific and CLI-specific features.
pip install 'huggingface_hub[cli,torch]'
```
Here is the list of optional dependencies in `huggingface_hub`:
- `cli`: provide a more convenient CLI interface for `huggingface_hub`.
- `fastai`, `torch`, `tensorflow`: dependencies to run framework-specific features.
- `dev`: dependencies to contribute to the lib. Includes `testing` (to run tests), `typing` (to run type checker) and `quality` (to run linters). | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_3 |
In some cases, it is interesting to install `huggingface_hub` directly from source.
This allows you to use the bleeding edge `main` version rather than the latest stable version.
The `main` version is useful for staying up-to-date with the latest developments, for instance
if a bug has been fixed since the last official release but a new release hasn't been rolled out yet.
However, this means the `main` version may not always be stable. We strive to keep the
`main` version operational, and most issues are usually resolved
within a few hours or a day. If you run into a problem, please open an Issue so we can
fix it even sooner!
```bash
pip install git+https://github.com/huggingface/huggingface_hub
```
When installing from source, you can also specify a specific branch. This is useful if you
want to test a new feature or a new bug-fix that has not been merged yet:
```bash
pip install git+https://github.com/huggingface/huggingface_hub@my-feature-branch
```
Once done, [check installation](#check-installation) is working correctly. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_4 |
Installing from source allows you to setup an [editable install](https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs).
This is a more advanced installation if you plan to contribute to `huggingface_hub`
and need to test changes in the code. You need to clone a local copy of `huggingface_hub`
on your machine.
```bash
# First, clone repo locally
git clone https://github.com/huggingface/huggingface_hub.git
# Then, install with -e flag
cd huggingface_hub
pip install -e .
```
These commands will link the folder you cloned the repository to and your Python library paths.
Python will now look inside the folder you cloned to in addition to the normal library paths.
For example, if your Python packages are typically installed in `./.venv/lib/python3.13/site-packages/`,
Python will also search the folder you cloned `./huggingface_hub/`. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_5 |
If you are more familiar with it, you can install `huggingface_hub` using the [conda-forge channel](https://anaconda.org/conda-forge/huggingface_hub):
```bash
conda install -c conda-forge huggingface_hub
```
Once done, [check installation](#check-installation) is working correctly. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_6 |
Once installed, check that `huggingface_hub` works properly by running the following command:
```bash
python -c "from huggingface_hub import model_info; print(model_info('gpt2'))"
```
This command will fetch information from the Hub about the [gpt2](https://huggingface.co/gpt2) model.
Output should look like this:
```text
Model Name: gpt2
Tags: ['pytorch', 'tf', 'jax', 'tflite', 'rust', 'safetensors', 'gpt2', 'text-generation', 'en', 'doi:10.57967/hf/0039', 'transformers', 'exbert', 'license:mit', 'has_space']
Task: text-generation
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_7 |
With our goal of democratizing good ML everywhere, we built `huggingface_hub` to be a
cross-platform library and in particular to work correctly on both Unix-based and Windows
systems. However, there are a few cases where `huggingface_hub` has some limitations when
run on Windows. Here is an exhaustive list of known issues. Please let us know if you
encounter any undocumented problem by opening [an issue on Github](https://github.com/huggingface/huggingface_hub/issues/new/choose).
- `huggingface_hub`'s cache system relies on symlinks to efficiently cache files downloaded
from the Hub. On Windows, you must activate developer mode or run your script as admin to
enable symlinks. If they are not activated, the cache-system still works but in a non-optimized
manner. Please read [the cache limitations](./guides/manage-cache#limitations) section for more details.
- Filepaths on the Hub can have special characters (e.g. `"path/to?/my/file"`). Windows is
more restrictive on [special characters](https://learn.microsoft.com/en-us/windows/win32/intl/character-sets-used-in-file-names)
which makes it impossible to download those files on Windows. Hopefully this is a rare case.
Please reach out to the repo owner if you think this is a mistake or to us to figure out
a solution. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_8 |
Once `huggingface_hub` is properly installed on your machine, you might want
[configure environment variables](package_reference/environment_variables) or [check one of our guides](guides/overview) to get started. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/installation.md | .md | 2_9 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/authentication.md | .md | 3_0 |
The `huggingface_hub` library allows users to programmatically manage authentication to the Hub. This includes logging in, logging out, switching between tokens, and listing available tokens.
For more details about authentication, check out [this section](../quick-start#authentication). | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/authentication.md | .md | 3_1 |
```python
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 `huggingface-cli 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>
<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`].
</Tip>
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.
new_session (`bool`, defaults to `True`):
If `True`, will request a token even if one is already saved on the machine.
write_permission (`bool`):
Ignored and deprecated argument.
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/authentication.md | .md | 3_2 |
```python
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:
new_session (`bool`, defaults to `True`):
If `True`, will request a token even if one is already saved on the machine.
write_permission (`bool`):
Ignored and deprecated argument.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/authentication.md | .md | 3_3 |
```python
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:
new_session (`bool`, defaults to `True`):
If `True`, will request a token even if one is already saved on the machine.
write_permission (`bool`):
Ignored and deprecated argument.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/authentication.md | .md | 3_4 |
```python
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 logout from all saved access tokens.
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
If the access token name is not found.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/authentication.md | .md | 3_5 |
```python
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/authentication.md | .md | 3_6 |
```python
List all stored access tokens.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/authentication.md | .md | 3_7 |
Inference Endpoints provides a secure production solution to easily deploy models on a dedicated and autoscaling infrastructure managed by Hugging Face. An Inference Endpoint is built from a model from the [Hub](https://huggingface.co/models). This page is a reference for `huggingface_hub`'s integration with Inference Endpoints. For more information about the Inference Endpoints product, check out its [official documentation](https://huggingface.co/docs/inference-endpoints/index).
<Tip>
Check out the [related guide](../guides/inference_endpoints) to learn how to use `huggingface_hub` to manage your Inference Endpoints programmatically.
</Tip>
Inference Endpoints can be fully managed via API. The endpoints are documented with [Swagger](https://api.endpoints.huggingface.cloud/). The [`InferenceEndpoint`] class is a simple wrapper built on top on this API. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_0 |
A subset of the Inference Endpoint features are implemented in [`HfApi`]:
- [`get_inference_endpoint`] and [`list_inference_endpoints`] to get information about your Inference Endpoints
- [`create_inference_endpoint`], [`update_inference_endpoint`] and [`delete_inference_endpoint`] to deploy and manage Inference Endpoints
- [`pause_inference_endpoint`] and [`resume_inference_endpoint`] to pause and resume an Inference Endpoint
- [`scale_to_zero_inference_endpoint`] to manually scale an Endpoint to 0 replicas | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_1 |
The main dataclass is [`InferenceEndpoint`]. It contains information about a deployed `InferenceEndpoint`, including its configuration and current state. Once deployed, you can run inference on the Endpoint using the [`InferenceEndpoint.client`] and [`InferenceEndpoint.async_client`] properties that respectively return an [`InferenceClient`] and an [`AsyncInferenceClient`] object. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_2 |
```python
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', ...) | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_3 |
>>> endpoint.status
'running'
>>> endpoint.url
'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud' | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_4 |
>>> endpoint.client.text_to_image(...) | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_5 |
>>> endpoint.pause() | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_6 |
>>> endpoint.resume()
>>> endpoint.wait()
>>> endpoint.client.text_to_image(...)
```
```
- from_raw
- client
- async_client
- all | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_7 |
```python
An enumeration.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_8 |
```python
An enumeration.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_9 |
```python
Generic exception when dealing with Inference Endpoints.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/inference_endpoints.md | .md | 4_10 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_0 |
Below is the documentation for the `HfApi` class, which serves as a Python wrapper for the Hugging Face Hub's API.
All methods from the `HfApi` are also accessible from the package's root directly. Both approaches are detailed below.
Using the root method is more straightforward but the [`HfApi`] class gives you more flexibility.
In particular, you can pass a token that will be reused in all HTTP calls. This is different
than `huggingface-cli login` or [`login`] as the token is not persisted on the machine.
It is also possible to provide a different endpoint or configure a custom user-agent.
```python
from huggingface_hub import HfApi, list_models
# Use root method
models = list_models()
# Or configure a HfApi client
hf_api = HfApi(
endpoint="https://huggingface.co", # Can be a Private Hub endpoint.
token="hf_xxx", # Token is not persisted on the machine.
)
models = hf_api.list_models()
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_1 |
```python
Client to interact with the Hugging Face Hub via HTTP.
The client is initialized with some high-level settings used in all requests
made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi`
client is preferred but not mandatory as all of its public methods are exposed
directly at the root of `huggingface_hub`.
Args:
endpoint (`str`, *optional*):
Endpoint of the Hub. Defaults to <https://huggingface.co>.
token (Union[bool, str, None], optional):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
library_name (`str`, *optional*):
The name of the library that is making the HTTP request. Will be added to
the user-agent header. Example: `"transformers"`.
library_version (`str`, *optional*):
The version of the library that is making the HTTP request. Will be added
to the user-agent header. Example: `"4.24.0"`.
user_agent (`str`, `dict`, *optional*):
The user agent info in the form of a dictionary or a single string. It will
be completed with information about the installed packages.
headers (`dict`, *optional*):
Additional headers to be sent with each request. Example: `{"X-My-Header": "value"}`.
Headers passed here are taking precedence over the default headers.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_2 |
```python
Data structure containing information about a user access request.
Attributes:
username (`str`):
Username of the user who requested access.
fullname (`str`):
Fullname of the user who requested access.
email (`Optional[str]`):
Email of the user who requested access.
Can only be `None` in the /accepted list if the user was granted access manually.
timestamp (`datetime`):
Timestamp of the request.
status (`Literal["pending", "accepted", "rejected"]`):
Status of the request. Can be one of `["pending", "accepted", "rejected"]`.
fields (`Dict[str, Any]`, *optional*):
Additional fields filled by the user in the gate form.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_3 |
```python
Data structure containing information about a newly created commit.
Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`],
[`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific
to `str` is deprecated.
Attributes:
commit_url (`str`):
Url where to find the commit.
commit_message (`str`):
The summary (first line) of the commit that has been created.
commit_description (`str`):
Description of the commit that has been created. Can be empty.
oid (`str`):
Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`.
pr_url (`str`, *optional*):
Url to the PR that has been created, if any. Populated when `create_pr=True`
is passed.
pr_revision (`str`, *optional*):
Revision of the PR that has been created, if any. Populated when
`create_pr=True` is passed. Example: `"refs/pr/1"`.
pr_num (`int`, *optional*):
Number of the PR discussion that has been created, if any. Populated when
`create_pr=True` is passed. Can be passed as `discussion_num` in
[`get_discussion_details`]. Example: `1`.
repo_url (`RepoUrl`):
Repo URL of the commit containing info like repo_id, repo_type, etc.
_url (`str`, *optional*):
Legacy url for `str` compatibility. Can be the url to the uploaded file on the Hub (if returned by
[`upload_file`]), to the uploaded folder on the Hub (if returned by [`upload_folder`]) or to the commit on
the Hub (if returned by [`create_commit`]). Defaults to `commit_url`. It is deprecated to use this
attribute. Please use `commit_url` instead.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_4 |
```python
Contains information about a dataset on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing datasets
using [`list_datasets`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of dataset.
author (`str`):
Author of the dataset.
sha (`str`):
Repo SHA at this particular revision.
created_at (`datetime`, *optional*):
Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
corresponding to the date when we began to store creation dates.
last_modified (`datetime`, *optional*):
Date of last commit to the repo.
private (`bool`):
Is the repo private.
disabled (`bool`, *optional*):
Is the repo disabled.
gated (`Literal["auto", "manual", False]`, *optional*):
Is the repo gated.
If so, whether there is manual or automatic approval.
downloads (`int`):
Number of downloads of the dataset over the last 30 days.
downloads_all_time (`int`):
Cumulated number of downloads of the model since its creation.
likes (`int`):
Number of likes of the dataset.
tags (`List[str]`):
List of tags of the dataset.
card_data (`DatasetCardData`, *optional*):
Model Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object.
siblings (`List[RepoSibling]`):
List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset.
paperswithcode_id (`str`, *optional*):
Papers with code ID of the dataset.
trending_score (`int`, *optional*):
Trending score of the dataset.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_5 |
```python
Contains information about a git reference for a repo on the Hub.
Attributes:
name (`str`):
Name of the reference (e.g. tag name or branch name).
ref (`str`):
Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`).
target_commit (`str`):
OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_6 |
```python
Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details.
Attributes:
commit_id (`str`):
OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
authors (`List[str]`):
List of authors of the commit.
created_at (`datetime`):
Datetime when the commit was created.
title (`str`):
Title of the commit. This is a free-text value entered by the authors.
message (`str`):
Description of the commit. This is a free-text value entered by the authors.
formatted_title (`str`):
Title of the commit formatted as HTML. Only returned if `formatted=True` is set.
formatted_message (`str`):
Description of the commit formatted as HTML. Only returned if `formatted=True` is set.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_7 |
```python
Contains information about all git references for a repo on the Hub.
Object is returned by [`list_repo_refs`].
Attributes:
branches (`List[GitRefInfo]`):
A list of [`GitRefInfo`] containing information about branches on the repo.
converts (`List[GitRefInfo]`):
A list of [`GitRefInfo`] containing information about "convert" refs on the repo.
Converts are refs used (internally) to push preprocessed data in Dataset repos.
tags (`List[GitRefInfo]`):
A list of [`GitRefInfo`] containing information about tags on the repo.
pull_requests (`List[GitRefInfo]`, *optional*):
A list of [`GitRefInfo`] containing information about pull requests on the repo.
Only returned if `include_prs=True` is set.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_8 |
```python
Contains information about a model on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing models
using [`list_models`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of model.
author (`str`, *optional*):
Author of the model.
sha (`str`, *optional*):
Repo SHA at this particular revision.
created_at (`datetime`, *optional*):
Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
corresponding to the date when we began to store creation dates.
last_modified (`datetime`, *optional*):
Date of last commit to the repo.
private (`bool`):
Is the repo private.
disabled (`bool`, *optional*):
Is the repo disabled.
downloads (`int`):
Number of downloads of the model over the last 30 days.
downloads_all_time (`int`):
Cumulated number of downloads of the model since its creation.
gated (`Literal["auto", "manual", False]`, *optional*):
Is the repo gated.
If so, whether there is manual or automatic approval.
gguf (`Dict`, *optional*):
GGUF information of the model.
inference (`Literal["cold", "frozen", "warm"]`, *optional*):
Status of the model on the inference API.
Warm models are available for immediate use. Cold models will be loaded on first inference call.
Frozen models are not available in Inference API.
likes (`int`):
Number of likes of the model.
library_name (`str`, *optional*):
Library associated with the model.
tags (`List[str]`):
List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub
(e.g. supported libraries, model's arXiv).
pipeline_tag (`str`, *optional*):
Pipeline tag associated with the model.
mask_token (`str`, *optional*):
Mask token used by the model.
widget_data (`Any`, *optional*):
Widget data associated with the model.
model_index (`Dict`, *optional*):
Model index for evaluation.
config (`Dict`, *optional*):
Model configuration.
transformers_info (`TransformersInfo`, *optional*):
Transformers-specific info (auto class, processor, etc.) associated with the model.
trending_score (`int`, *optional*):
Trending score of the model.
card_data (`ModelCardData`, *optional*):
Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object.
siblings (`List[RepoSibling]`):
List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model.
spaces (`List[str]`, *optional*):
List of spaces using the model.
safetensors (`SafeTensorsInfo`, *optional*):
Model's safetensors information.
security_repo_status (`Dict`, *optional*):
Model's security scan status.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_9 |
```python
Contains basic information about a repo file inside a repo on the Hub.
<Tip>
All attributes of this class are optional except `rfilename`. This is because only the file names are returned when
listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more
information like file size, blob id or lfs details, you must request them specifically from one repo at a time
(using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to
retrieve these.
</Tip>
Attributes:
rfilename (str):
file name, relative to the repo root.
size (`int`, *optional*):
The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set
to `True`. It's `None` otherwise.
blob_id (`str`, *optional*):
The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to
`True`. It's `None` otherwise.
lfs (`BlobLfsInfo`, *optional*):
The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to
`True` and the file is stored with Git LFS. It's `None` otherwise.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_10 |
```python
Contains information about a file on the Hub.
Attributes:
path (str):
file path relative to the repo root.
size (`int`):
The file's size, in bytes.
blob_id (`str`):
The file's git OID.
lfs (`BlobLfsInfo`):
The file's LFS metadata.
last_commit (`LastCommitInfo`, *optional*):
The file's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
are called with `expand=True`.
security (`BlobSecurityInfo`, *optional*):
The file's security scan metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
are called with `expand=True`.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_11 |
```python
Subclass of `str` describing a repo URL on the Hub.
`RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward
compatibility. At initialization, the URL is parsed to populate properties:
- endpoint (`str`)
- namespace (`Optional[str]`)
- repo_name (`str`)
- repo_id (`str`)
- repo_type (`Literal["model", "dataset", "space"]`)
- url (`str`)
Args:
url (`Any`):
String value of the repo url.
endpoint (`str`, *optional*):
Endpoint of the Hub. Defaults to <https://huggingface.co>.
Example:
```py
>>> RepoUrl('https://huggingface.co/gpt2')
RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2')
>>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co')
RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset')
>>> RepoUrl('hf://datasets/my-user/my-dataset')
RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')
>>> HfApi.create_repo("dummy_model")
RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')
```
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If URL cannot be parsed.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `repo_type` is unknown.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_12 |
```python
Metadata for a Safetensors repo.
A repo is considered to be a Safetensors repo if it contains either a 'model.safetensors' weight file (non-shared
model) or a 'model.safetensors.index.json' index file (sharded model) at its root.
This class is returned by [`get_safetensors_metadata`].
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Attributes:
metadata (`Dict`, *optional*):
The metadata contained in the 'model.safetensors.index.json' file, if it exists. Only populated for sharded
models.
sharded (`bool`):
Whether the repo contains a sharded model or not.
weight_map (`Dict[str, str]`):
A map of all weights. Keys are tensor names and values are filenames of the files containing the tensors.
files_metadata (`Dict[str, SafetensorsFileMetadata]`):
A map of all files metadata. Keys are filenames and values are the metadata of the corresponding file, as
a [`SafetensorsFileMetadata`] object.
parameter_count (`Dict[str, int]`):
A map of the number of parameters per data type. Keys are data types and values are the number of parameters
of that data type.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_13 |
```python
Metadata for a Safetensors file hosted on the Hub.
This class is returned by [`parse_safetensors_file_metadata`].
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Attributes:
metadata (`Dict`):
The metadata contained in the file.
tensors (`Dict[str, TensorInfo]`):
A map of all tensors. Keys are tensor names and values are information about the corresponding tensor, as a
[`TensorInfo`] object.
parameter_count (`Dict[str, int]`):
A map of the number of parameters per data type. Keys are data types and values are the number of parameters
of that data type.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_14 |
```python
Contains information about a Space on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing spaces
using [`list_spaces`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of the Space.
author (`str`, *optional*):
Author of the Space.
sha (`str`, *optional*):
Repo SHA at this particular revision.
created_at (`datetime`, *optional*):
Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
corresponding to the date when we began to store creation dates.
last_modified (`datetime`, *optional*):
Date of last commit to the repo.
private (`bool`):
Is the repo private.
gated (`Literal["auto", "manual", False]`, *optional*):
Is the repo gated.
If so, whether there is manual or automatic approval.
disabled (`bool`, *optional*):
Is the Space disabled.
host (`str`, *optional*):
Host URL of the Space.
subdomain (`str`, *optional*):
Subdomain of the Space.
likes (`int`):
Number of likes of the Space.
tags (`List[str]`):
List of tags of the Space.
siblings (`List[RepoSibling]`):
List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space.
card_data (`SpaceCardData`, *optional*):
Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object.
runtime (`SpaceRuntime`, *optional*):
Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object.
sdk (`str`, *optional*):
SDK used by the Space.
models (`List[str]`, *optional*):
List of models used by the Space.
datasets (`List[str]`, *optional*):
List of datasets used by the Space.
trending_score (`int`, *optional*):
Trending score of the Space.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_15 |
```python
Information about a tensor.
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Attributes:
dtype (`str`):
The data type of the tensor ("F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL").
shape (`List[int]`):
The shape of the tensor.
data_offsets (`Tuple[int, int]`):
The offsets of the data in the file as a tuple `[BEGIN, END]`.
parameter_count (`int`):
The number of parameters in the tensor.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_16 |
```python
Contains information about a user on the Hub.
Attributes:
username (`str`):
Name of the user on the Hub (unique).
fullname (`str`):
User's full name.
avatar_url (`str`):
URL of the user's avatar.
details (`str`, *optional*):
User's details.
is_following (`bool`, *optional*):
Whether the authenticated user is following this user.
is_pro (`bool`, *optional*):
Whether the user is a pro user.
num_models (`int`, *optional*):
Number of models created by the user.
num_datasets (`int`, *optional*):
Number of datasets created by the user.
num_spaces (`int`, *optional*):
Number of spaces created by the user.
num_discussions (`int`, *optional*):
Number of discussions initiated by the user.
num_papers (`int`, *optional*):
Number of papers authored by the user.
num_upvotes (`int`, *optional*):
Number of upvotes received by the user.
num_likes (`int`, *optional*):
Number of likes given by the user.
num_following (`int`, *optional*):
Number of users this user is following.
num_followers (`int`, *optional*):
Number of users following this user.
orgs (list of [`Organization`]):
List of organizations the user is part of.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_17 |
```python
Contains information about a user likes on the Hub.
Attributes:
user (`str`):
Name of the user for which we fetched the likes.
total (`int`):
Total number of likes.
datasets (`List[str]`):
List of datasets liked by the user (as repo_ids).
models (`List[str]`):
List of models liked by the user (as repo_ids).
spaces (`List[str]`):
List of spaces liked by the user (as repo_ids).
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_18 |
```python
Data structure containing information about a webhook.
Attributes:
id (`str`):
ID of the webhook.
url (`str`):
URL of the webhook.
watched (`List[WebhookWatchedItem]`):
List of items watched by the webhook, see [`WebhookWatchedItem`].
domains (`List[WEBHOOK_DOMAIN_T]`):
List of domains the webhook is watching. Can be one of `["repo", "discussions"]`.
secret (`str`, *optional*):
Secret of the webhook.
disabled (`bool`):
Whether the webhook is disabled or not.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_19 |
```python
Data structure containing information about the items watched by a webhook.
Attributes:
type (`Literal["dataset", "model", "org", "space", "user"]`):
Type of the item to be watched. Can be one of `["dataset", "model", "org", "space", "user"]`.
name (`str`):
Name of the item to be watched. Can be the username, organization name, model name, dataset name or space name.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_20 |
Below are the supported values for [`CommitOperation`]: | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_21 |
```python
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()`.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_22 |
```python
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`.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_23 |
```python
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_24 |
```python
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 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_25 |
>>> 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") | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_26 |
>>> 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") | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_27 |
```
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/hf_api.md | .md | 5_28 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/overview.md | .md | 6_0 |
This section contains an exhaustive and technical description of `huggingface_hub` classes and methods. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/overview.md | .md | 6_1 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/collections.md | .md | 7_0 |
Check out the [`HfApi`] documentation page for the reference of methods to manage your Space on the Hub.
- Get collection content: [`get_collection`]
- Create new collection: [`create_collection`]
- Update a collection: [`update_collection_metadata`]
- Delete a collection: [`delete_collection`]
- Add an item to a collection: [`add_collection_item`]
- Update an item in a collection: [`update_collection_item`]
- Remove an item from a collection: [`delete_collection_item`] | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/collections.md | .md | 7_1 |
```python
Contains information about a Collection on the Hub.
Attributes:
slug (`str`):
Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
title (`str`):
Title of the collection. E.g. `"Recent models"`.
owner (`str`):
Owner of the collection. E.g. `"TheBloke"`.
items (`List[CollectionItem]`):
List of items in the collection.
last_updated (`datetime`):
Date of the last update of the collection.
position (`int`):
Position of the collection in the list of collections of the owner.
private (`bool`):
Whether the collection is private or not.
theme (`str`):
Theme of the collection. E.g. `"green"`.
upvotes (`int`):
Number of upvotes of the collection.
description (`str`, *optional*):
Description of the collection, as plain text.
url (`str`):
(property) URL of the collection on the Hub.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/collections.md | .md | 7_2 |
```python
Contains information about an item of a Collection (model, dataset, Space or paper).
Attributes:
item_object_id (`str`):
Unique ID of the item in the collection.
item_id (`str`):
ID of the underlying object on the Hub. Can be either a repo_id or a paper id
e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`.
item_type (`str`):
Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"` or `"paper"`.
position (`int`):
Position of the item in the collection.
note (`str`, *optional*):
Note associated with the item, as plain text.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/collections.md | .md | 7_3 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_0 |
Check the [`HfApi`] documentation page for the reference of methods enabling
interaction with Pull Requests and Discussions on the Hub.
- [`get_repo_discussions`]
- [`get_discussion_details`]
- [`create_discussion`]
- [`create_pull_request`]
- [`rename_discussion`]
- [`comment_discussion`]
- [`edit_discussion_comment`]
- [`change_discussion_status`]
- [`merge_pull_request`] | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_1 |
```python
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_2 |
```python
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_3 |
```python
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_4 |
```python
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_5 |
```python
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 )
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_6 |
```python
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_7 |
```python
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/community.md | .md | 8_8 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/file_download.md | .md | 9_0 |
```python
Download a given file if it's not already present in the local cache.
The new cache file layout looks like this:
- The cache directory contains one subfolder per repo_id (namespaced by repo type)
- inside each repo folder:
- refs is a list of the latest known revision => commit_hash pairs
- blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
whether they're LFS files or not)
- snapshots contains one subfolder per commit, each "commit" contains the subset of the files
that have been resolved at that particular commit. Each filename is a symlink to the blob
at that particular commit.
```
[ 96] .
βββ [ 160] models--julien-c--EsperBERTo-small
βββ [ 160] blobs
β βββ [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
β βββ [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
β βββ [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
βββ [ 96] refs
β βββ [ 40] main
βββ [ 128] snapshots
βββ [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
β βββ [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
β βββ [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
βββ [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
βββ [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
βββ [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
```
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.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
filename (`str`):
The name of the file in the repo.
subfolder (`str`, *optional*):
An optional value corresponding to a folder inside the model repo.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if downloading from a dataset or space,
`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.
library_name (`str`, *optional*):
The name of the library to which the object corresponds.
library_version (`str`, *optional*):
The version of the library.
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored.
local_dir (`str` or `Path`, *optional*):
If provided, the downloaded file will be placed under this directory.
user_agent (`dict`, `str`, *optional*):
The user-agent info in the form of a dictionary or a string.
force_download (`bool`, *optional*, defaults to `False`):
Whether the file should be downloaded even if it already exists in
the local cache.
proxies (`dict`, *optional*):
Dictionary mapping protocol to the URL of the proxy passed to
`requests.request`.
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 `requests.request`.
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.
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.
headers (`dict`, *optional*):
Additional headers to be sent with the request.
Returns:
`str`: Local path of file or if networking is off, last version of file cached on disk.
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.
[`~utils.EntryNotFoundError`]
If the file to download cannot be found.
[`~utils.LocalEntryNotFoundError`]
If network is disabled or unavailable and file is not found in cache.
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
If `token=True` but 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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/file_download.md | .md | 9_1 |
```python
Construct the URL of a file from the given information.
The resolved address can either be a huggingface.co-hosted url, or a link to
Cloudfront (a Content Delivery Network, or CDN) for large files which are
more than a few MBs.
Args:
repo_id (`str`):
A namespace (user or an organization) name and a repo name separated
by a `/`.
filename (`str`):
The name of the file in the repo.
subfolder (`str`, *optional*):
An optional value corresponding to a folder inside the repo.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if downloading from a dataset or space,
`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.
Example:
```python
>>> from huggingface_hub import hf_hub_url
>>> hf_hub_url(
... repo_id="julien-c/EsperBERTo-small", filename="pytorch_model.bin"
... )
'https://huggingface.co/julien-c/EsperBERTo-small/resolve/main/pytorch_model.bin'
```
<Tip>
Notes:
Cloudfront is replicated over the globe so downloads are way faster for
the end user (and it also lowers our bandwidth costs).
Cloudfront aggressively caches files by default (default TTL is 24
hours), however this is not an issue here because we implement a
git-based versioning system on huggingface.co, which means that we store
the files on S3/Cloudfront in a content-addressable way (i.e., the file
name is its hash). Using content-addressable filenames means cache can't
ever be stale.
In terms of client-side caching from this library, we base our caching
on the objects' entity tag (`ETag`), which is an identifier of a
specific version of a resource [1]_. An object's ETag is: its git-sha1
if stored in git, or its sha256 if stored in git-lfs.
</Tip>
References:
- [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/file_download.md | .md | 9_2 |
```python
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"` or `"space"` if downloading from a dataset or space,
`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.
proxies (`dict`, *optional*):
Dictionary mapping protocol to the URL of the proxy passed to
`requests.request`.
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 `requests.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.
Returns:
`str`: folder path of the repo snapshot.
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.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/file_download.md | .md | 9_3 |
```python
Fetch metadata of a file versioned on the Hub for a given url.
Args:
url (`str`):
File url, for example returned by [`hf_hub_url`].
token (`str` or `bool`, *optional*):
A token to be used for the download.
- If `True`, the token is read from the HuggingFace config
folder.
- If `False` or `None`, no token is provided.
- If a string, it's used as the authentication token.
proxies (`dict`, *optional*):
Dictionary mapping protocol to the URL of the proxy passed to
`requests.request`.
timeout (`float`, *optional*, defaults to 10):
How many seconds to wait for the server to send metadata before giving up.
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 (`dict`, `str`, *optional*):
The user-agent info in the form of a dictionary or a string.
headers (`dict`, *optional*):
Additional headers to be sent with the request.
Returns:
A [`HfFileMetadata`] object containing metadata such as location, etag, size and
commit_hash.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/file_download.md | .md | 9_4 |
```python
Data structure containing information about a file versioned on the Hub.
Returned by [`get_hf_file_metadata`] based on a URL.
Args:
commit_hash (`str`, *optional*):
The commit_hash related to the file.
etag (`str`, *optional*):
Etag of the file on the server.
location (`str`):
Location where to download the file. Can be a Hub url or not (CDN).
size (`size`):
Size of the file. In case of an LFS file, contains the size of the actual
LFS file, not the pointer.
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/file_download.md | .md | 9_5 |
The methods displayed above are designed to work with a caching system that prevents
re-downloading files. The caching system was updated in v0.8.0 to become the central
cache-system shared across libraries that depend on the Hub.
Read the [cache-system guide](../guides/manage-cache) for a detailed presentation of caching at
at HF. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/file_download.md | .md | 9_6 |
<!--β οΈ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/serialization.md | .md | 10_0 |
`huggingface_hub` provides helpers to save and load ML model weights in a standardized way. This part of the library is still under development and will be improved in future releases. The goal is to harmonize how weights are saved and loaded across the Hub, both to remove code duplication across libraries and to establish consistent conventions. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/serialization.md | .md | 10_1 |
DDUF is a file format designed for diffusion models. It allows saving all the information to run a model in a single file. This work is inspired by the [GGUF](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md) format. `huggingface_hub` provides helpers to save and load DDUF files, ensuring the file format is respected.
<Tip warning={true}>
This is a very early version of the parser. The API and implementation can evolve in the near future.
The parser currently does very little validation. For more details about the file format, check out https://github.com/huggingface/huggingface.js/tree/main/packages/dduf.
</Tip> | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/serialization.md | .md | 10_2 |
Here is how to export a folder containing different parts of a diffusion model using [`export_folder_as_dduf`]:
```python
# Export a folder as a DDUF file
>>> from huggingface_hub import export_folder_as_dduf
>>> export_folder_as_dduf("FLUX.1-dev.dduf", folder_path="path/to/FLUX.1-dev")
```
For more flexibility, you can use [`export_entries_as_dduf`] and pass a list of files to include in the final DDUF file:
```python
# Export specific files from the local disk.
>>> from huggingface_hub import export_entries_as_dduf
>>> export_entries_as_dduf(
... dduf_path="stable-diffusion-v1-4-FP16.dduf",
... entries=[ # List entries to add to the DDUF file (here, only FP16 weights)
... ("model_index.json", "path/to/model_index.json"),
... ("vae/config.json", "path/to/vae/config.json"),
... ("vae/diffusion_pytorch_model.fp16.safetensors", "path/to/vae/diffusion_pytorch_model.fp16.safetensors"),
... ("text_encoder/config.json", "path/to/text_encoder/config.json"),
... ("text_encoder/model.fp16.safetensors", "path/to/text_encoder/model.fp16.safetensors"),
... # ... add more entries here
... ]
... )
```
The `entries` parameter also supports passing an iterable of paths or bytes. This can prove useful if you have a loaded model and want to serialize it directly into a DDUF file instead of having to serialize each component to disk first and then as a DDUF file. Here is an example of how a `StableDiffusionPipeline` can be serialized as DDUF:
```python
# Export state_dicts one by one from a loaded pipeline
>>> from diffusers import DiffusionPipeline
>>> from typing import Generator, Tuple
>>> import safetensors.torch
>>> from huggingface_hub import export_entries_as_dduf
>>> pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
... # ... do some work with the pipeline
>>> def as_entries(pipe: DiffusionPipeline) -> Generator[Tuple[str, bytes], None, None]:
... # Build a generator that yields the entries to add to the DDUF file.
... # The first element of the tuple is the filename in the DDUF archive (must use UNIX separator!). The second element is the content of the file.
... # Entries will be evaluated lazily when the DDUF file is created (only 1 entry is loaded in memory at a time)
... yield "vae/config.json", pipe.vae.to_json_string().encode()
... yield "vae/diffusion_pytorch_model.safetensors", safetensors.torch.save(pipe.vae.state_dict())
... yield "text_encoder/config.json", pipe.text_encoder.config.to_json_string().encode()
... yield "text_encoder/model.safetensors", safetensors.torch.save(pipe.text_encoder.state_dict())
... # ... add more entries here
>>> export_entries_as_dduf(dduf_path="stable-diffusion-v1-4.dduf", entries=as_entries(pipe))
```
**Note:** in practice, `diffusers` provides a method to directly serialize a pipeline in a DDUF file. The snippet above is only meant as an example. | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/serialization.md | .md | 10_3 |
```python
>>> import json
>>> import safetensors.torch
>>> from huggingface_hub import read_dduf_file
# Read DDUF metadata
>>> dduf_entries = read_dduf_file("FLUX.1-dev.dduf")
# Returns a mapping filename <> DDUFEntry
>>> dduf_entries["model_index.json"]
DDUFEntry(filename='model_index.json', offset=66, length=587)
# Load model index as JSON
>>> json.loads(dduf_entries["model_index.json"].read_text())
{'_class_name': 'FluxPipeline', '_diffusers_version': '0.32.0.dev0', '_name_or_path': 'black-forest-labs/FLUX.1-dev', 'scheduler': ['diffusers', 'FlowMatchEulerDiscreteScheduler'], 'text_encoder': ['transformers', 'CLIPTextModel'], 'text_encoder_2': ['transformers', 'T5EncoderModel'], 'tokenizer': ['transformers', 'CLIPTokenizer'], 'tokenizer_2': ['transformers', 'T5TokenizerFast'], 'transformer': ['diffusers', 'FluxTransformer2DModel'], 'vae': ['diffusers', 'AutoencoderKL']}
# Load VAE weights using safetensors
>>> with dduf_entries["vae/diffusion_pytorch_model.safetensors"].as_mmap() as mm:
... state_dict = safetensors.torch.load(mm)
``` | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/package_reference/serialization.md | .md | 10_4 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 1