text
stringlengths 1
1.02k
| class_index
int64 0
305
| source
stringclasses 77
values |
---|---|---|
if token is None:
# Cannot do `token = token or self.token` as token can be `False`.
token = self.token
return snapshot_download(
repo_id=repo_id,
repo_type=repo_type,
revision=revision,
endpoint=self.endpoint,
cache_dir=cache_dir,
local_dir=local_dir,
local_dir_use_symlinks=local_dir_use_symlinks,
library_name=self.library_name,
library_version=self.library_version,
user_agent=self.user_agent,
proxies=proxies,
etag_timeout=etag_timeout,
resume_download=resume_download,
force_download=force_download,
token=token,
local_files_only=local_files_only,
allow_patterns=allow_patterns,
ignore_patterns=ignore_patterns,
max_workers=max_workers,
tqdm_class=tqdm_class,
) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
def get_safetensors_metadata(
self,
repo_id: str,
*,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
token: Union[bool, str, None] = None,
) -> SafetensorsRepoMetadata:
"""
Parse metadata for a safetensors repo on the Hub.
We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single
safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the
metadata from the index file and then parse the metadata from each shard.
To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`].
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
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.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
model. Default is `None`.
revision (`str`, *optional*):
The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
head of the `"main"` branch.
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`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
[`SafetensorsRepoMetadata`]: information related to safetensors repo.
Raises:
[`NotASafetensorsRepoError`]
If the repo is not a safetensors repo i.e. doesn't have either a
`model.safetensors` or a `model.safetensors.index.json` file.
[`SafetensorsParsingError`]
If a safetensors file header couldn't be parsed correctly.
Example:
```py
# Parse repo with single weights file
>>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
>>> metadata
SafetensorsRepoMetadata(
metadata=None,
sharded=False,
weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
)
>>> metadata.files_metadata["model.safetensors"].metadata
{'format': 'pt'} | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# Parse repo with sharded model
>>> metadata = get_safetensors_metadata("bigscience/bloom")
Parse safetensors files: 100%|ββββββββββββββββββββββββββββββββββββββββββ| 72/72 [00:12<00:00, 5.78it/s]
>>> metadata
SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
>>> len(metadata.files_metadata)
72 # All safetensors files have been fetched | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# Parse repo with sharded model
>>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.
```
"""
if self.file_exists( # Single safetensors file => non-sharded model
repo_id=repo_id,
filename=constants.SAFETENSORS_SINGLE_FILE,
repo_type=repo_type,
revision=revision,
token=token,
):
file_metadata = self.parse_safetensors_file_metadata(
repo_id=repo_id,
filename=constants.SAFETENSORS_SINGLE_FILE,
repo_type=repo_type,
revision=revision,
token=token,
)
return SafetensorsRepoMetadata(
metadata=None,
sharded=False,
weight_map={ | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys()
},
files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata},
)
elif self.file_exists( # Multiple safetensors files => sharded with index
repo_id=repo_id,
filename=constants.SAFETENSORS_INDEX_FILE,
repo_type=repo_type,
revision=revision,
token=token,
):
# Fetch index
index_file = self.hf_hub_download(
repo_id=repo_id,
filename=constants.SAFETENSORS_INDEX_FILE,
repo_type=repo_type,
revision=revision,
token=token,
)
with open(index_file) as f:
index = json.load(f) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
weight_map = index.get("weight_map", {})
# Fetch metadata per shard
files_metadata = {}
def _parse(filename: str) -> None:
files_metadata[filename] = self.parse_safetensors_file_metadata(
repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, token=token
)
thread_map(
_parse,
set(weight_map.values()),
desc="Parse safetensors files",
tqdm_class=hf_tqdm,
) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
return SafetensorsRepoMetadata(
metadata=index.get("metadata", None),
sharded=True,
weight_map=weight_map,
files_metadata=files_metadata,
)
else:
# Not a safetensors repo
raise NotASafetensorsRepoError(
f"'{repo_id}' is not a safetensors repo. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or '{constants.SAFETENSORS_SINGLE_FILE}' files."
)
def parse_safetensors_file_metadata(
self,
repo_id: str,
filename: str,
*,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
token: Union[bool, str, None] = None,
) -> SafetensorsFileMetadata:
"""
Parse metadata from a safetensors file on the Hub.
To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`]. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
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.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
model. Default is `None`.
revision (`str`, *optional*):
The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
head of the `"main"` branch.
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`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
[`SafetensorsFileMetadata`]: information related to a safetensors file.
Raises:
[`NotASafetensorsRepoError`]:
If the repo is not a safetensors repo i.e. doesn't have either a
`model.safetensors` or a `model.safetensors.index.json` file.
[`SafetensorsParsingError`]:
If a safetensors file header couldn't be parsed correctly.
"""
url = hf_hub_url(
repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, endpoint=self.endpoint
)
_headers = self._build_hf_headers(token=token) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# 1. Fetch first 100kb
# Empirically, 97% of safetensors files have a metadata size < 100kb (over the top 1000 models on the Hub).
# We assume fetching 100kb is faster than making 2 GET requests. Therefore we always fetch the first 100kb to
# avoid the 2nd GET in most cases.
# See https://github.com/huggingface/huggingface_hub/pull/1855#discussion_r1404286419.
response = get_session().get(url, headers={**_headers, "range": "bytes=0-100000"})
hf_raise_for_status(response) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# 2. Parse metadata size
metadata_size = struct.unpack("<Q", response.content[:8])[0]
if metadata_size > constants.SAFETENSORS_MAX_HEADER_LENGTH:
raise SafetensorsParsingError(
f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
f"'{revision or constants.DEFAULT_REVISION}'): safetensors header is too big. Maximum supported size is "
f"{constants.SAFETENSORS_MAX_HEADER_LENGTH} bytes (got {metadata_size})."
)
# 3.a. Get metadata from payload
if metadata_size <= 100000:
metadata_as_bytes = response.content[8 : 8 + metadata_size]
else: # 3.b. Request full metadata
response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size+7}"})
hf_raise_for_status(response)
metadata_as_bytes = response.content | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# 4. Parse json header
try:
metadata_as_dict = json.loads(metadata_as_bytes.decode(errors="ignore"))
except json.JSONDecodeError as e:
raise SafetensorsParsingError(
f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
f"'{revision or constants.DEFAULT_REVISION}'): header is not json-encoded string. Please make sure this is a "
"correctly formatted safetensors file."
) from e | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
try:
return SafetensorsFileMetadata(
metadata=metadata_as_dict.get("__metadata__", {}),
tensors={
key: TensorInfo(
dtype=tensor["dtype"],
shape=tensor["shape"],
data_offsets=tuple(tensor["data_offsets"]), # type: ignore
)
for key, tensor in metadata_as_dict.items()
if key != "__metadata__"
},
)
except (KeyError, IndexError) as e:
raise SafetensorsParsingError(
f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
f"'{revision or constants.DEFAULT_REVISION}'): header format not recognized. Please make sure this is a correctly"
" formatted safetensors file."
) from e | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def create_branch(
self,
repo_id: str,
*,
branch: str,
revision: Optional[str] = None,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
exist_ok: bool = False,
) -> None:
"""
Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`).
To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`].
Args:
repo_id (`str`):
The repository in which the branch will be created.
Example: `"user/my-cool-model"`.
branch (`str`):
The name of the branch to create.
revision (`str`, *optional*):
The git revision to create the branch from. It can be a branch name or
the OID/SHA of a commit, as a hexadecimal string. Defaults to the head
of the `"main"` branch. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
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`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if creating a branch on a dataset or
space, `None` or `"model"` if tagging a model. Default is `None`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if branch already exists. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.BadRequestError`]:
If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'.
[`~utils.HfHubHTTPError`]:
If the branch already exists on the repo (error 409) and `exist_ok` is
set to `False`.
"""
if repo_type is None:
repo_type = constants.REPO_TYPE_MODEL
branch = quote(branch, safe="")
# Prepare request
branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
headers = self._build_hf_headers(token=token)
payload = {}
if revision is not None:
payload["startingPoint"] = revision | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# Create branch
response = get_session().post(url=branch_url, headers=headers, json=payload)
try:
hf_raise_for_status(response)
except HfHubHTTPError as e:
if exist_ok and e.response.status_code == 409:
return
elif exist_ok and e.response.status_code == 403:
# No write permission on the namespace but branch might already exist
try:
refs = self.list_repo_refs(repo_id=repo_id, repo_type=repo_type, token=token)
for branch_ref in refs.branches:
if branch_ref.name == branch:
return # Branch already exists => do not raise
except HfHubHTTPError:
pass # We raise the original error if the branch does not exist
raise | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def delete_branch(
self,
repo_id: str,
*,
branch: str,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
) -> None:
"""
Delete a branch from a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a branch will be deleted.
Example: `"user/my-cool-model"`.
branch (`str`):
The name of the branch to delete.
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`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if creating a branch on a dataset or
space, `None` or `"model"` if tagging a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.HfHubHTTPError`]:
If trying to delete a protected branch. Ex: `main` cannot be deleted.
[`~utils.HfHubHTTPError`]:
If trying to delete a branch that does not exist.
"""
if repo_type is None:
repo_type = constants.REPO_TYPE_MODEL
branch = quote(branch, safe="")
# Prepare request
branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
headers = self._build_hf_headers(token=token) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# Delete branch
response = get_session().delete(url=branch_url, headers=headers)
hf_raise_for_status(response)
@validate_hf_hub_args
def create_tag(
self,
repo_id: str,
*,
tag: str,
tag_message: Optional[str] = None,
revision: Optional[str] = None,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
exist_ok: bool = False,
) -> None:
"""
Tag a given commit of a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a commit will be tagged.
Example: `"user/my-cool-model"`.
tag (`str`):
The name of the tag to create.
tag_message (`str`, *optional*):
The description of the tag to create. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
revision (`str`, *optional*):
The git revision to tag. It can be a branch name or the OID/SHA of a
commit, as a hexadecimal string. Shorthands (7 first characters) are
also supported. Defaults to the head of the `"main"` branch.
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`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if tagging a dataset or
space, `None` or `"model"` if tagging a model. Default is
`None`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if tag already exists. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
[`~utils.HfHubHTTPError`]:
If the branch already exists on the repo (error 409) and `exist_ok` is
set to `False`.
"""
if repo_type is None:
repo_type = constants.REPO_TYPE_MODEL
revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
# Prepare request
tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{revision}"
headers = self._build_hf_headers(token=token)
payload = {"tag": tag}
if tag_message is not None:
payload["message"] = tag_message | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# Tag
response = get_session().post(url=tag_url, headers=headers, json=payload)
try:
hf_raise_for_status(response)
except HfHubHTTPError as e:
if not (e.response.status_code == 409 and exist_ok):
raise
@validate_hf_hub_args
def delete_tag(
self,
repo_id: str,
*,
tag: str,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
) -> None:
"""
Delete a tag from a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a tag will be deleted.
Example: `"user/my-cool-model"`.
tag (`str`):
The name of the tag to delete. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
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`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or
`"model"` if tagging a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.RevisionNotFoundError`]:
If tag is not found.
"""
if repo_type is None:
repo_type = constants.REPO_TYPE_MODEL
tag = quote(tag, safe="") | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
# Prepare request
tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{tag}"
headers = self._build_hf_headers(token=token)
# Un-tag
response = get_session().delete(url=tag_url, headers=headers)
hf_raise_for_status(response)
@validate_hf_hub_args
def get_full_repo_name(
self,
model_id: str,
*,
organization: Optional[str] = None,
token: Union[bool, str, None] = None,
):
"""
Returns the repository name for a given model ID and optional
organization. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
model_id (`str`):
The name of the model.
organization (`str`, *optional*):
If passed, the repository name will be in the organization
namespace instead of the user namespace.
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`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
`str`: The repository name in the user's namespace
({username}/{model_id}) if no organization is passed, and under the
organization namespace ({organization}/{model_id}) otherwise.
"""
if organization is None:
if "/" in model_id:
username = model_id.split("/")[0]
else:
username = self.whoami(token=token)["name"] # type: ignore
return f"{username}/{model_id}"
else:
return f"{organization}/{model_id}" | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def get_repo_discussions(
self,
repo_id: str,
*,
author: Optional[str] = None,
discussion_type: Optional[constants.DiscussionTypeFilter] = None,
discussion_status: Optional[constants.DiscussionStatusFilter] = None,
repo_type: Optional[str] = None,
token: Union[bool, str, None] = None,
) -> Iterator[Discussion]:
"""
Fetches Discussions and Pull Requests for the given repo. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
author (`str`, *optional*):
Pass a value to filter by discussion author. `None` means no filter.
Default is `None`.
discussion_type (`str`, *optional*):
Set to `"pull_request"` to fetch only pull requests, `"discussion"`
to fetch only discussions. Set to `"all"` or `None` to fetch both.
Default is `None`.
discussion_status (`str`, *optional*):
Set to `"open"` (respectively `"closed"`) to fetch only open
(respectively closed) discussions. Set to `"all"` or `None`
to fetch both.
Default is `None`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if fetching from a dataset or | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
space, `None` or `"model"` if fetching from a model. Default is
`None`.
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`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
`Iterator[Discussion]`: An iterator of [`Discussion`] objects.
Example:
Collecting all discussions of a repo in a list:
```python
>>> from huggingface_hub import get_repo_discussions
>>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased"))
```
Iterating over discussions of a repo: | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
```python
>>> from huggingface_hub import get_repo_discussions
>>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
... print(discussion.num, discussion.title)
```
"""
if repo_type not in constants.REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
if repo_type is None:
repo_type = constants.REPO_TYPE_MODEL
if discussion_type is not None and discussion_type not in constants.DISCUSSION_TYPES:
raise ValueError(f"Invalid discussion_type, must be one of {constants.DISCUSSION_TYPES}")
if discussion_status is not None and discussion_status not in constants.DISCUSSION_STATUS:
raise ValueError(f"Invalid discussion_status, must be one of {constants.DISCUSSION_STATUS}")
headers = self._build_hf_headers(token=token)
path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions" | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
params: Dict[str, Union[str, int]] = {}
if discussion_type is not None:
params["type"] = discussion_type
if discussion_status is not None:
params["status"] = discussion_status
if author is not None:
params["author"] = author
def _fetch_discussion_page(page_index: int):
params["p"] = page_index
resp = get_session().get(path, headers=headers, params=params)
hf_raise_for_status(resp)
paginated_discussions = resp.json()
total = paginated_discussions["count"]
start = paginated_discussions["start"]
discussions = paginated_discussions["discussions"]
has_next = (start + len(discussions)) < total
return discussions, has_next
has_next, page_index = True, 0 | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
while has_next:
discussions, has_next = _fetch_discussion_page(page_index=page_index)
for discussion in discussions:
yield Discussion(
title=discussion["title"],
num=discussion["num"],
author=discussion.get("author", {}).get("name", "deleted"),
created_at=parse_datetime(discussion["createdAt"]),
status=discussion["status"],
repo_id=discussion["repo"]["name"],
repo_type=discussion["repo"]["type"],
is_pull_request=discussion["isPullRequest"],
endpoint=self.endpoint,
)
page_index = page_index + 1 | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def get_discussion_details(
self,
repo_id: str,
discussion_num: int,
*,
repo_type: Optional[str] = None,
token: Union[bool, str, None] = None,
) -> DiscussionWithDetails:
"""Fetches a Discussion's / Pull Request 's details from the Hub. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
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`.
Returns: [`DiscussionWithDetails`]
<Tip>
Raises the following errors: | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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.
</Tip>
"""
if not isinstance(discussion_num, int) or discussion_num <= 0:
raise ValueError("Invalid discussion_num, must be a positive integer")
if repo_type not in constants.REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
if repo_type is None:
repo_type = constants.REPO_TYPE_MODEL | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions/{discussion_num}"
headers = self._build_hf_headers(token=token)
resp = get_session().get(path, params={"diff": "1"}, headers=headers)
hf_raise_for_status(resp)
discussion_details = resp.json()
is_pull_request = discussion_details["isPullRequest"]
target_branch = discussion_details["changes"]["base"] if is_pull_request else None
conflicting_files = discussion_details["filesWithConflicts"] if is_pull_request else None
merge_commit_oid = discussion_details["changes"].get("mergeCommitId", None) if is_pull_request else None | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
return DiscussionWithDetails(
title=discussion_details["title"],
num=discussion_details["num"],
author=discussion_details.get("author", {}).get("name", "deleted"),
created_at=parse_datetime(discussion_details["createdAt"]),
status=discussion_details["status"],
repo_id=discussion_details["repo"]["name"],
repo_type=discussion_details["repo"]["type"],
is_pull_request=discussion_details["isPullRequest"],
events=[deserialize_event(evt) for evt in discussion_details["events"]],
conflicting_files=conflicting_files,
target_branch=target_branch,
merge_commit_oid=merge_commit_oid,
diff=discussion_details.get("diff"),
endpoint=self.endpoint,
) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def create_discussion(
self,
repo_id: str,
title: str,
*,
token: Union[bool, str, None] = None,
description: Optional[str] = None,
repo_type: Optional[str] = None,
pull_request: bool = False,
) -> DiscussionWithDetails:
"""Creates a Discussion or Pull Request.
Pull Requests created programmatically will be in `"draft"` status.
Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`]. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
title (`str`):
The title of the discussion. It can be up to 200 characters long,
and must be at least 3 characters long. Leading and trailing whitespaces
will be stripped.
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`.
description (`str`, *optional*):
An optional description for the Pull Request.
Defaults to `"Discussion opened with the huggingface_hub Python library"`
pull_request (`bool`, *optional*): | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Whether to create a Pull Request or discussion. If `True`, creates a Pull Request.
If `False`, creates a discussion. Defaults to `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns: [`DiscussionWithDetails`]
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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.
</Tip>"""
if repo_type not in constants.REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
if repo_type is None:
repo_type = constants.REPO_TYPE_MODEL | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
if description is not None:
description = description.strip()
description = (
description
if description
else (
f"{'Pull Request' if pull_request else 'Discussion'} opened with the"
" [huggingface_hub Python"
" library](https://huggingface.co/docs/huggingface_hub)"
)
)
headers = self._build_hf_headers(token=token)
resp = get_session().post(
f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions",
json={
"title": title.strip(),
"description": description,
"pullRequest": pull_request,
},
headers=headers,
)
hf_raise_for_status(resp)
num = resp.json()["num"]
return self.get_discussion_details(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=num,
token=token,
) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def create_pull_request(
self,
repo_id: str,
title: str,
*,
token: Union[bool, str, None] = None,
description: Optional[str] = None,
repo_type: Optional[str] = None,
) -> DiscussionWithDetails:
"""Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status.
Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`];
This is a wrapper around [`HfApi.create_discussion`]. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
title (`str`):
The title of the discussion. It can be up to 200 characters long,
and must be at least 3 characters long. Leading and trailing whitespaces
will be stripped.
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`.
description (`str`, *optional*):
An optional description for the Pull Request.
Defaults to `"Discussion opened with the huggingface_hub Python library"`
repo_type (`str`, *optional*): | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns: [`DiscussionWithDetails`]
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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.
</Tip>"""
return self.create_discussion(
repo_id=repo_id,
title=title,
token=token,
description=description,
repo_type=repo_type,
pull_request=True,
) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
def _post_discussion_changes(
self,
*,
repo_id: str,
discussion_num: int,
resource: str,
body: Optional[dict] = None,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
) -> requests.Response:
"""Internal utility to POST changes to a Discussion or Pull Request"""
if not isinstance(discussion_num, int) or discussion_num <= 0:
raise ValueError("Invalid discussion_num, must be a positive integer")
if repo_type not in constants.REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
if repo_type is None:
repo_type = constants.REPO_TYPE_MODEL
repo_id = f"{repo_type}s/{repo_id}"
path = f"{self.endpoint}/api/{repo_id}/discussions/{discussion_num}/{resource}" | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
headers = self._build_hf_headers(token=token)
resp = requests.post(path, headers=headers, json=body)
hf_raise_for_status(resp)
return resp
@validate_hf_hub_args
def comment_discussion(
self,
repo_id: str,
discussion_num: int,
comment: str,
*,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
) -> DiscussionComment:
"""Creates a new comment on the given Discussion. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment (`str`):
The content of the comment to create. Comments support markdown formatting.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
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`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
[`DiscussionComment`]: the newly created comment
Examples:
```python
>>> comment = \"\"\"
... Hello @otheruser!
...
... # This is a title
...
... **This is bold**, *this is italic* and ~this is strikethrough~
... And [this](http://url) is a link
... \"\"\"
>>> HfApi().comment_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... comment=comment
... )
# DiscussionComment(id='deadbeef0000000', type='comment', ...)
```
<Tip>
Raises the following errors: | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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.
</Tip>
"""
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource="comment",
body={"comment": comment},
)
return deserialize_event(resp.json()["newMessage"]) # type: ignore | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def rename_discussion(
self,
repo_id: str,
discussion_num: int,
new_title: str,
*,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
) -> DiscussionTitleChange:
"""Renames a Discussion. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
new_title (`str`):
The new title for the discussion
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
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`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
[`DiscussionTitleChange`]: the title change event
Examples:
```python
>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... new_title=new_title
... )
# DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)
```
<Tip>
Raises the following errors: | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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.
</Tip>
"""
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource="title",
body={"title": new_title},
)
return deserialize_event(resp.json()["newTitle"]) # type: ignore | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def change_discussion_status(
self,
repo_id: str,
discussion_num: int,
new_status: Literal["open", "closed"],
*,
token: Union[bool, str, None] = None,
comment: Optional[str] = None,
repo_type: Optional[str] = None,
) -> DiscussionStatusChange:
"""Closes or re-opens a Discussion or Pull Request. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
new_status (`str`):
The new status for the discussion, either `"open"` or `"closed"`.
comment (`str`, *optional*):
An optional comment to post with the status change.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
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 | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
[`DiscussionStatusChange`]: the status change event
Examples:
```python
>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... new_title=new_title
... )
# DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)
```
<Tip>
Raises the following errors: | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
</Tip>
"""
if new_status not in ["open", "closed"]:
raise ValueError("Invalid status, valid statuses are: 'open' and 'closed'")
body: Dict[str, str] = {"status": new_status}
if comment and comment.strip():
body["comment"] = comment.strip()
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource="status",
body=body,
)
return deserialize_event(resp.json()["newStatus"]) # type: ignore
@validate_hf_hub_args
def merge_pull_request(
self,
repo_id: str,
discussion_num: int,
*,
token: Union[bool, str, None] = None,
comment: Optional[str] = None,
repo_type: Optional[str] = None,
):
"""Merges a Pull Request. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment (`str`, *optional*):
An optional comment to post with the status change.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
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`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
[`DiscussionStatusChange`]: the status change event
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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.
</Tip>
"""
self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource="merge",
body={"comment": comment.strip()} if comment and comment.strip() else None,
) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def edit_discussion_comment(
self,
repo_id: str,
discussion_num: int,
comment_id: str,
new_content: str,
*,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
) -> DiscussionComment:
"""Edits a comment on a Discussion / Pull Request. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment_id (`str`):
The ID of the comment to edit.
new_content (`str`):
The new content of the comment. Comments support markdown formatting.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
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). | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
To disable authentication, pass `False`. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Returns:
[`DiscussionComment`]: the edited comment
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
</Tip>
"""
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource=f"comment/{comment_id.lower()}/edit",
body={"content": new_content},
)
return deserialize_event(resp.json()["updatedComment"]) # type: ignore
@validate_hf_hub_args
def hide_discussion_comment(
self,
repo_id: str,
discussion_num: int,
comment_id: str,
*,
token: Union[bool, str, None] = None,
repo_type: Optional[str] = None,
) -> DiscussionComment:
"""Hides a comment on a Discussion / Pull Request.
<Tip warning={true}>
Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.
</Tip> | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment_id (`str`):
The ID of the comment to edit.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
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`.
Returns:
[`DiscussionComment`]: the hidden comment | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~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. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
</Tip>
"""
warnings.warn(
"Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.",
UserWarning,
)
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource=f"comment/{comment_id.lower()}/hide",
)
return deserialize_event(resp.json()["updatedComment"]) # type: ignore
@validate_hf_hub_args
def add_space_secret(
self,
repo_id: str,
key: str,
value: str,
*,
description: Optional[str] = None,
token: Union[bool, str, None] = None,
) -> None:
"""Adds or updates a secret in a Space.
Secrets allow to set secret keys or tokens to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Secret key. Example: `"GITHUB_API_KEY"`
value (`str`):
Secret value. Example: `"your_github_api_key"`.
description (`str`, *optional*):
Secret description. Example: `"Github API key to access the Github API"`.
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`.
"""
payload = {"key": key, "value": value}
if description is not None:
payload["description"] = description
r = get_session().post( | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
f"{self.endpoint}/api/spaces/{repo_id}/secrets",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(r) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def delete_space_secret(self, repo_id: str, key: str, *, token: Union[bool, str, None] = None) -> None:
"""Deletes a secret from a Space.
Secrets allow to set secret keys or tokens to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Secret key. Example: `"GITHUB_API_KEY"`.
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`.
"""
r = get_session().delete(
f"{self.endpoint}/api/spaces/{repo_id}/secrets",
headers=self._build_hf_headers(token=token),
json={"key": key},
)
hf_raise_for_status(r)
@validate_hf_hub_args
def get_space_variables(self, repo_id: str, *, token: Union[bool, str, None] = None) -> Dict[str, SpaceVariable]:
"""Gets all variables from a Space. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
Args:
repo_id (`str`):
ID of the repo to query. Example: `"bigcode/in-the-stack"`.
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`.
"""
r = get_session().get(
f"{self.endpoint}/api/spaces/{repo_id}/variables",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(r)
return {k: SpaceVariable(k, v) for k, v in r.json().items()} | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def add_space_variable(
self,
repo_id: str,
key: str,
value: str,
*,
description: Optional[str] = None,
token: Union[bool, str, None] = None,
) -> Dict[str, SpaceVariable]:
"""Adds or updates a variable in a Space.
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Variable key. Example: `"MODEL_REPO_ID"`
value (`str`):
Variable value. Example: `"the_model_repo_id"`.
description (`str`):
Description of the variable. Example: `"Model Repo ID of the implemented model"`.
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`.
"""
payload = {"key": key, "value": value}
if description is not None:
payload["description"] = description
r = get_session().post( | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
f"{self.endpoint}/api/spaces/{repo_id}/variables",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(r)
return {k: SpaceVariable(k, v) for k, v in r.json().items()} | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def delete_space_variable(
self, repo_id: str, key: str, *, token: Union[bool, str, None] = None
) -> Dict[str, SpaceVariable]:
"""Deletes a variable from a Space.
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Variable key. Example: `"MODEL_REPO_ID"`
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`.
"""
r = get_session().delete(
f"{self.endpoint}/api/spaces/{repo_id}/variables",
headers=self._build_hf_headers(token=token),
json={"key": key},
)
hf_raise_for_status(r)
return {k: SpaceVariable(k, v) for k, v in r.json().items()} | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def get_space_runtime(self, repo_id: str, *, token: Union[bool, str, None] = None) -> SpaceRuntime:
"""Gets runtime information about a Space.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
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`.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
"""
r = get_session().get(
f"{self.endpoint}/api/spaces/{repo_id}/runtime", headers=self._build_hf_headers(token=token)
)
hf_raise_for_status(r)
return SpaceRuntime(r.json()) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def request_space_hardware(
self,
repo_id: str,
hardware: SpaceHardware,
*,
token: Union[bool, str, None] = None,
sleep_time: Optional[int] = None,
) -> SpaceRuntime:
"""Request new hardware for a Space. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
hardware (`str` or [`SpaceHardware`]):
Hardware on which to run the Space. Example: `"t4-medium"`.
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`.
sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity). | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
<Tip>
It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
</Tip>
"""
if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC:
warnings.warn(
"If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
" than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
" you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
UserWarning,
)
payload: Dict[str, Any] = {"flavor": hardware}
if sleep_time is not None:
payload["sleepTimeSeconds"] = sleep_time
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/hardware",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(r)
return SpaceRuntime(r.json()) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def set_space_sleep_time(
self, repo_id: str, sleep_time: int, *, token: Union[bool, str, None] = None
) -> SpaceRuntime:
"""Set a custom sleep time for a Space running on upgraded hardware..
Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep"
mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a
configurable sleep time. To know more about the sleep stage, please refer to
https://huggingface.co/docs/hub/spaces-gpus#sleep-time. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
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`.
Returns: | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
<Tip>
It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`].
</Tip>
"""
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/sleeptime",
headers=self._build_hf_headers(token=token),
json={"seconds": sleep_time},
)
hf_raise_for_status(r)
runtime = SpaceRuntime(r.json())
hardware = runtime.requested_hardware or runtime.hardware
if hardware == SpaceHardware.CPU_BASIC:
warnings.warn(
"If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
" than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
" you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
UserWarning,
)
return runtime | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def pause_space(self, repo_id: str, *, token: Union[bool, str, None] = None) -> SpaceRuntime:
"""Pause your Space.
A paused Space stops executing until manually restarted by its owner. This is different from the sleeping
state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the
hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page.
For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause). | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Args:
repo_id (`str`):
ID of the Space to pause. Example: `"Salesforce/BLIP2"`.
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`.
Returns:
[`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware. | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Raises:
[`~utils.RepositoryNotFoundError`]:
If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
are not authenticated.
[`~utils.HfHubHTTPError`]:
403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't
own, either ask the owner by opening a Discussion or duplicate the Space.
[`~utils.BadRequestError`]:
If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
a static Space, you can set it to private.
"""
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/pause", headers=self._build_hf_headers(token=token)
)
hf_raise_for_status(r)
return SpaceRuntime(r.json()) | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
@validate_hf_hub_args
def restart_space(
self, repo_id: str, *, token: Union[bool, str, None] = None, factory_reboot: bool = False
) -> SpaceRuntime:
"""Restart your Space.
This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You
must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be
billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space.
For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause). | 74 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hf_api.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.