o
    Zhԛ                    @  s<  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZm	Z	 d dl
mZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z" d d
l#m$Z$ d dl%Z%d dl&m'Z' d dl(m)Z* d dl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZE ddlFmGZGmHZHmIZImJZJ ddlKmLZLmMZMmNZNmOZOmPZPmQZQ ddlRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZf ddlgmhZhmiZimjZj ddlkmlZlmmZmmnZn ddlompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZmZmZmZ ddlom)Z ddlmZmZ ddlmZ ddlmZmZmZ e dZed ZdZedZdZeeZdfdgd&d'ZeG d(d) d)eZeG d*d+ d+eZeG d,d- d-eZeG d.d/ d/eZeG d0d1 d1eZeG d2d3 d3eZeG d4d5 d5ZG d6d7 d7eZeG d8d9 d9ZeG d:d; d;ZeG d<d= d=ZeG d>d? d?ZeG d@dA dAZeG dBdC dCZeG dDdE dEZeG dFdG dGZeG dHdI dIZeG dJdK dKZeG dLdM dMZeG dNdO dOZeG dPdQ dQZeG dRdS dSZdhdVdWZG dXdY dYZ		didjdadbZdkdddeZe ZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZej Z ejZejZejZejZejZejZejZejZej	Z	ej
Z
ej
Z
ejZejZejZejZejZejZejZdS )l    )annotationsN)FutureThreadPoolExecutor)asdict	dataclassfield)datetime)wraps)islice)Path)AnyBinaryIOCallableDictIterableIteratorListLiteralOptionalTupleTypeVarUnionoverload)quote)	HTTPError)tqdm)
thread_map   )	CommitOperationCommitOperationAddCommitOperationCopyCommitOperationDelete_fetch_files_to_copy_fetch_upload_modes_prepare_commit_payload_upload_lfs_files_warn_on_overwriting_operations)InferenceEndpointInferenceEndpointType):MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE9MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE(MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE+MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATEMultiCommitExceptionMultiCommitStepMultiCommitStrategy multi_commit_create_pull_requestmulti_commit_generate_comment!multi_commit_parse_pr_descriptionplan_multi_commits)SpaceHardwareSpaceRuntimeSpaceStorageSpaceVariable)
DiscussionDiscussionCommentDiscussionStatusChangeDiscussionTitleChangeDiscussionWithDetailsdeserialize_event)_HF_DEFAULT_ENDPOINT_HF_DEFAULT_STAGING_ENDPOINTDEFAULT_ETAG_TIMEOUTDEFAULT_REQUEST_TIMEOUTDEFAULT_REVISIONDISCUSSION_STATUSDISCUSSION_TYPESENDPOINTINFERENCE_ENDPOINTS_ENDPOINTREGEX_COMMIT_OIDREPO_TYPE_MODEL
REPO_TYPESREPO_TYPES_MAPPINGREPO_TYPES_URL_PREFIXESSAFETENSORS_INDEX_FILESAFETENSORS_MAX_HEADER_LENGTHSAFETENSORS_SINGLE_FILESPACES_SDK_TYPESDiscussionStatusFilterDiscussionTypeFilter)HfFileMetadataget_hf_file_metadata
hf_hub_url)DatasetCardDataModelCardDataSpaceCardData)IGNORE_GIT_FOLDER_PATTERNSBadRequestErrorEntryNotFoundErrorGatedRepoErrorHfFolderHfHubHTTPErrorLocalTokenNotFoundErrorNotASafetensorsRepoErrorRepositoryNotFoundErrorRevisionNotFoundErrorSafetensorsFileMetadataSafetensorsParsingErrorSafetensorsRepoMetadata
TensorInfobuild_hf_headersexperimentalfilter_repo_objectsget_sessionhf_raise_for_statusloggingpaginateparse_datetimevalidate_hf_hub_args)_deprecate_arguments_deprecate_method)	CallableT)DatasetFilterModelFilter_is_emission_within_tresholdR)modeldatasetspaceZpaperZhf_userz.*/discussions/(\d+)$z
Note: Creating a commit assumes that the repo already exists on the Huggingface Hub. Please use `create_repo` if it's not the case.hf_idstrhub_urlOptional[str]return(Tuple[Optional[str], Optional[str], str]c           
      C  s  | }t ttfvr| tt } | tt } tdd|dur|nt }|| v o(d| v}d}| |r8| t|d } | d}t|dk}|rr|dd \}}||krSd}t|d	krd||d
 vrd|d
 }	nZ|t	v rot	| }	d}nOd}	nL|rt|dkr|d
d \}	}}n:t|d	kr|d t	v rt	|d  }	d}| dd }n| ddd \}}d}	n|d }d\}}	nt
d|  |	t	v rt	|	 }	|	dkrd}	|	tvrt
d|	 d| d|	||fS )a  
    Returns the repo type and ID from a huggingface.co URL linking to a
    repository

    Args:
        hf_id (`str`):
            An URL or ID of a repository on the HF hub. Accepted values are:

            - https://huggingface.co/<repo_type>/<namespace>/<repo_id>
            - https://huggingface.co/<namespace>/<repo_id>
            - hf://<repo_type>/<namespace>/<repo_id>
            - hf://<namespace>/<repo_id>
            - <repo_type>/<namespace>/<repo_id>
            - <namespace>/<repo_id>
            - <repo_id>
        hub_url (`str`, *optional*):
            The URL of the HuggingFace Hub, defaults to https://huggingface.co

    Returns:
        A tuple with three items: repo_type (`str` or `None`), namespace (`str` or
        `None`) and repo_id (`str`).

    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.
    z	https?:// N@zhf:///      r   NNz;Unable to retrieve user and repo ID from the passed HF ID: zUnknown `repo_type`: 'z' (''))rE   r>   r?   replaceresub
startswithlensplitrJ   
ValueErrorrI   )
ry   r{   Zinput_hf_idZ	is_hf_urlZHFFS_PREFIXZurl_segmentsZis_hf_id	namespacerepo_id	repo_type r   M/var/www/html/lang_env/lib/python3.10/site-packages/huggingface_hub/hf_api.pyrepo_type_and_id_from_hf_id   sR   




r   c                   @  s.   e Zd ZU ded< ded< ded< dd ZdS )	LastCommitInforz   oidtitler   datec                 C     |  t|  d S Nupdater   selfr   r   r   __post_init__      zLastCommitInfo.__post_init__N__name__
__module____qualname____annotations__r   r   r   r   r   r      
   
 r   c                   @  s.   e Zd ZU ded< ded< ded< dd ZdS )	BlobLfsInfointsizerz   sha256pointer_sizec                 C  r   r   r   r   r   r   r   r     r   zBlobLfsInfo.__post_init__Nr   r   r   r   r   r     r   r   c                   @  s.   e Zd ZU ded< ded< ded< dd ZdS )	BlobSecurityInfoboolsafeOptional[Dict]av_scanpickle_import_scanc                 C  r   r   r   r   r   r   r   r     r   zBlobSecurityInfo.__post_init__Nr   r   r   r   r   r     r   r   c                   @  sB   e Zd ZU ded< dZded< dZded< dZded< dd	 ZdS )
TransformersInforz   Z
auto_modelNr|   custom_classpipeline_tag	processorc                 C  r   r   r   r   r   r   r   r     r   zTransformersInfo.__post_init__)r   r   r   r   r   r   r   r   r   r   r   r   r     s   
 r   c                   @  s&   e Zd ZU ded< ded< dd ZdS )SafeTensorsInfozList[Dict[str, int]]
parametersr   totalc                 C  r   r   r   r   r   r   r   r   '  r   zSafeTensorsInfo.__post_init__Nr   r   r   r   r   r   "  s   
 r   c                   @  s   e Zd ZU dZded< ded< ded< ded< dZded	< ed
dZded< ed
dZded< ed
ddZ	ded< dddddZ
dd ZdS )
CommitInfoa  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`.

        _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.
    rz   
commit_urlcommit_messagecommit_descriptionr   Nr|   pr_urlF)initpr_revisionpr_num)reprdefault_urlr   c                O  s   t | |p|S r   )rz   __new__)clsr   r   argskwargsr   r   r   r   a  s   zCommitInfo.__new__c                 C  s@   | j durt| j | _t| jdd | _dS d| _d| _dS )zPopulate pr-related fields after initialization.

        See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing.
        Nr   r   )r   _parse_revision_from_pr_urlr   r   r   r   r   r   r   r   r   d  s
   

zCommitInfo.__post_init__)r   rz   r   r|   )r   r   r   __doc__r   r   r   r   r   r   r   r   r   r   r   r   r   +  s   
 'r   c                   @  sF   e Zd ZU dZded< ded< ded< ded< ded	< d
Zded< d
S )AccessRequesta  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 (`str`):
            Email of the user who requested access.
        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.
    rz   usernamefullnameemailr   	timestampz*Literal['pending', 'accepted', 'rejected']statusNzOptional[Dict[str, Any]]fields)r   r   r   r   r   r   r   r   r   r   r   q  s   
 r   c                      s>   e Zd ZdZdd fddZdd fddZdddZ  ZS )RepoUrla  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.
    Nurlr   endpointr|   c                   s   t t| | |S r   )superr   r   )r   r   r   	__class__r   r   r     r   zRepoUrl.__new__r}   Nonec                   sh   t    |pt| _t| | jd\}}}|| _|| _|d u r |n| d| | _|p+t| _	t
| | _d S )N)r{   r   )r   __init__rE   r   r   r   	repo_namer   rH   r   rz   r   )r   r   r   r   r   r   r   r   r   r     s   


zRepoUrl.__init__rz   c              	   C  s$   d|  d| j  d| j d| j d	S )Nz	RepoUrl('z', endpoint='z', repo_type='z', repo_id='r   )r   r   r   r   r   r   r   __repr__  s   $zRepoUrl.__repr__r   )r   r   r   r|   )r   r   r   r|   r}   r   r}   rz   )r   r   r   r   r   r   r   __classcell__r   r   r   r   r     s
    'r   c                   @  s>   e Zd ZU dZded< dZded< dZded< dZd	ed
< dS )RepoSiblinga&  
    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.
    rz   	rfilenameNOptional[int]r   r|   blob_idOptional[BlobLfsInfo]lfs)r   r   r   r   r   r   r   r   r   r   r   r   r     s   
 r   c                   @  sV   e Zd ZU dZded< ded< ded< dZded	< dZd
ed< dZded< dd ZdS )RepoFilea  
    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_files_info`], [`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_files_info`], [`list_repo_tree`] and [`get_paths_info`]
            are called with `expand=True`.
    rz   pathr   r   r   Nr   r   Optional[LastCommitInfo]last_commitzOptional[BlobSecurityInfo]securityc                 K  s   | d| _| d| _| d| _| dd }|d ur)t|d |d |d d}|| _| dd p7| dd }|d urKt|d	 |d
 t|d d}|| _| dd }|d uret	|d |d |d d}|| _
| j| _| j| _d S )Nr   r   r   r   pointerSizer   r   r   
lastCommitr   idr   r   r   r   r   r   r   ZavScanZpickleImportScan)r   r   r   )popr   r   r   r   r   r   rm   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   
  s*   zRepoFile.__init__)	r   r   r   r   r   r   r   r   r   r   r   r   r   r     s   
 r   c                   @  s6   e Zd ZU dZded< ded< dZded< dd	 ZdS )

RepoFoldera  
    Contains information about a folder on the Hub.

    Attributes:
        path (str):
            folder path relative to the repo root.
        tree_id (`str`):
            The folder's git OID.
        last_commit (`LastCommitInfo`, *optional*):
            The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
            are called with `expand=True`.
    rz   r   tree_idNr   r   c                 K  s`   | d| _| d| _| dd p| dd }|d ur+t|d |d t|d d}|| _d S )	Nr   r   r   r   r   r   r   r   )r   r   r   r   rm   r   )r   r   r   r   r   r   r   7  s   
zRepoFolder.__init__)r   r   r   r   r   r   r   r   r   r   r   r   $  s   
 r   c                   @  s   e Zd ZU dZded< ded< ded< ded< ded	< d
ed< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded < d!ed"< d#ed$< d%ed&< d'd( Zd)S )*	ModelInfoau
  
    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.
        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 model.
        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.
        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.
    rz   r   r|   authorshaOptional[datetime]
created_atlast_modifiedr   private*Optional[Literal['auto', 'manual', False]]gatedOptional[bool]disabledr   	downloadslikeslibrary_name	List[str]tagsr   
mask_tokenzOptional[ModelCardData]	card_datazOptional[Any]widget_datar   model_indexconfigzOptional[TransformersInfo]transformers_infoOptional[List[RepoSibling]]siblingsOptional[List[str]]spaceszOptional[SafeTensorsInfo]safetensorsc                 K  s  | d| _| dd | _| dd | _| dd p| dd }|r&t|nd | _| dd p4| dd }|r;t|nd | _| d| _| d	d | _| d
d | _	| d| _
| d| _| dd | _| d| _| dd | _| dd | _| dd p| dd }t|trtd i |ddin|| _| dd | _| dd p| dd | _| dd | _| dd p| dd }|rtd i |nd | _| dd }|rdd |D nd | _| dd | _| dd }|rtd i |nd | _| j| _| j| _| j| _| j j!d i | d S )!Nr   r   r   lastModifiedr   	createdAtr   r   r   r   r   r   r   r  r   r  cardDatar  ignore_metadata_errorsTZ
widgetDatazmodel-indexr  r  transformersInfor  r	  c                 S  \   g | ]*}t |d  |d|d|dr(t|d d |d d |d d dnddqS 	r   r   ZblobIdr   r   r   r   N)r   r   r   r   r   getr   .0Zsiblingr   r   r   
<listcomp>      


z&ModelInfo.__init__.<locals>.<listcomp>r  r  r   )"r   r   r   r   rm   r   r   r   r   r   r   r   r   r  r   r  
isinstancedictrV   r  r  r  r  r   r  r	  r  r   r  r  r  r  __dict__r   )r   r   r   r   r  r  r	  r  r   r   r   r     sL   "zModelInfo.__init__Nr   r   r   r   r   r   r   r   r   r   r   B  s2   
 =r   c                   @  s   e Zd ZU dZded< ded< ded< ded< ded	< d
ed< ded< ded< ded< ded< ded< ded< ded< ded< dd ZdS )DatasetInfoa  
    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.
        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.
    rz   r   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   paperswithcode_idr   r  zOptional[DatasetCardData]r  r  r	  c                 K  s^  | d| _| dd | _| dd | _| dd p| dd }|r&t|nd | _| dd p4| dd }|r;t|nd | _| d| _| d	d | _| d
d | _	| d| _
| d| _| dd | _| d| _| dd pv| dd }t|trtdi |ddin|| _| dd }|rdd |D nd | _| j| _| j| _| jjdi | d S )Nr   r   r   r  r   r  r   r   r   r   r   r   r  r  r  r  r  Tr	  c                 S  r  r  r  r  r   r   r   r  $  r  z(DatasetInfo.__init__.<locals>.<listcomp>r   )r   r   r   r   rm   r   r   r   r   r   r   r   r  r  r  r  rU   r  r	  r  r  r  r   )r   r   r   r   r  r	  r   r   r   r     s6   "zDatasetInfo.__init__Nr  r   r   r   r   r    s"   
 *r  c                   @  s   e Zd ZU dZded< ded< ded< ded< ded	< d
ed< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< d d! Zd"S )#	SpaceInfoat  
    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.
    rz   r   r|   r   r   r   r   r   r   r   r   r   r   r   host	subdomainr   r   sdkr   r  r  r	  zOptional[SpaceCardData]r  zOptional[SpaceRuntime]runtimer
  modelsdatasetsc                 K  s  | d| _| dd | _| dd | _| dd p| dd }|r&t|nd | _| dd p4| dd }|r;t|nd | _| d| _| d	d | _| d
d | _	| dd | _
| dd | _| d| _| dd | _| d| _| dd p~| dd }t|trtdi |ddin|| _| dd }|rdd |D nd | _| dd }|rt|nd | _| dd | _| dd | _| j| _| j| _| jjdi | d S )Nr   r   r   r  r   r  r   r   r   r   r!  r"  r   r#  r  r  r  r  Tr	  c                 S  r  r  r  r  r   r   r   r    r  z&SpaceInfo.__init__.<locals>.<listcomp>r$  r%  r&  r   )r   r   r   r   rm   r   r   r   r   r   r!  r"  r   r#  r  r  r  rW   r  r	  r5   r$  r%  r&  r  r  r  r   )r   r   r   r   r  r	  r$  r   r   r   r     s@   "zSpaceInfo.__init__Nr  r   r   r   r   r   ?  s*   
 4r   c                   @  s2   e Zd ZU dZded< ded< ded< dd Zd	S )

MetricInfoa8  
    Contains information about a metric on the Hub.

    Attributes:
        id (`str`):
            ID of the metric. E.g. `"accuracy"`.
        space_id (`str`):
            ID of the space associated with the metric. E.g. `"Accuracy"`.
        description (`str`):
            Description of the metric.
    rz   r   space_idr|   descriptionc                 K  sD   | d| _| d| _| dd | _| j| _| jjdi | d S )Nr   spaceIdr)  r   )r   r   r(  r)  r*  r  r   )r   r   r   r   r   r     s
   zMetricInfo.__init__Nr  r   r   r   r   r'    s   
 r'  c                   @  sL   e Zd ZU dZded< ded< ded< ded< dZd	ed
< 	ddddZdS )CollectionItema  
    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.
    rz   item_object_iditem_id	item_typer   positionNr|   note_idr   typeCollectionItemType_Tr   r}   r   c                 K  s8   || _ || _|| _|| _|d ur|d | _d S d | _d S )Ntext)r,  r-  r.  r/  r0  )r   r1  r   r2  r/  r0  r   r   r   r   r     s
    zCollectionItem.__init__r   )r1  rz   r   rz   r2  r3  r/  r   r0  r   r}   r   )r   r   r   r   r   r0  r   r   r   r   r   r+    s   
 r+  c                   @  s~   e Zd ZU dZded< ded< ded< ded< ded	< d
ed< ded< ded< d
ed< dZded< dddZedddZdS )
Collectiona  
    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.
    rz   slugr   ownerzList[CollectionItem]itemsr   last_updatedr   r/  r   r   themeupvotesNr|   r)  r}   r   c                 K  s   | d| _| d| _| d| _dd | dD | _t| d| _| d| _| d	| _| d
| _	| d| _
| dd | _| dd }|d u rPt}| d| j | _d S )Nr6  r   r7  c                 S     g | ]	}t d i |qS r   )r+  r  itemr   r   r   r  (      z'Collection.__init__.<locals>.<listcomp>r8  ZlastUpdatedr/  r   r:  r;  r)  r   z/collections/)r   r6  r   r7  r8  rm   r9  r/  r   r:  r;  r)  rE   r   )r   r   r   r   r   r   r   $  s   zCollection.__init__c                 C  s   | j S )z-Returns the URL of the collection on the Hub.r   r   r   r   r   r   4  s   zCollection.url)r}   r   r   )	r   r   r   r   r   r)  r   propertyr   r   r   r   r   r5    s   
 
r5  c                   @  *   e Zd ZU dZded< ded< ded< dS )
GitRefInfoa  
    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"`)
    rz   namereftarget_commitNr   r   r   r   r   r   r   r   r   rC  :  s
   
 rC  c                   @  s6   e Zd ZU dZded< ded< ded< dZded< dS )	GitRefsa2  
    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.
    zList[GitRefInfo]branchesconvertsr  NzOptional[List[GitRefInfo]]pull_requests)r   r   r   r   r   rK  r   r   r   r   rH  M  s   
 rH  c                   @  sJ   e Zd ZU dZded< ded< ded< ded< ded	< d
ed< d
ed< dS )GitCommitInfoau  
    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.
    rz   	commit_idr   authorsr   r   r   messager|   formatted_titleformatted_messageNrG  r   r   r   r   rL  g  s   
 rL  c                   @  s:   e Zd ZU dZded< ded< ded< ded< ded	< d
S )	UserLikesa  
    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).
    rz   userr   r   r   r&  r%  r  NrG  r   r   r   r   rR    s   
 rR  c                   @  rB  )Usera  
    Contains information about a user on the Hub.

    Attributes:
        avatar_url (`str`):
            URL of the user's avatar.
        username (`str`):
            Name of the user on the Hub (unique).
        fullname (`str`):
            User's full name.
    rz   
avatar_urlr   r   NrG  r   r   r   r   rT    s
   
 rT  fnrq   c                   s<   t }t|jdd  t fdd}d|_|S )a  Wrap a method of `HfApi` to handle `run_as_future=True`.

    A method flagged as "future_compatible" will be called in a thread if `run_as_future=True` and return a
    `concurrent.futures.Future` instance. Otherwise, it will be called normally and return the result.
    r   Nc                   sv   d|v r|d }d|d< nd}t  |D ]\}}|dkr |} nq|r0| j| g|R i |S | g|R i |S )Nrun_as_futureF)ziprW  )r   r   r   rW  paramvalueZargs_paramsrV  r   r   _inner  s   
z!future_compatible.<locals>._innerT)inspect	signaturelistr   r	   Zis_future_compatible)rV  sigr\  r   r[  r   future_compatible  s   
ra  c                   @  sj  e Zd Z						ddddZdddZeddddZddddZdddZdddZ	eddddddddddddddddddd dd<d=Z
dd@dAZedddddddddddddddddBddMdNZddQdRZddTdUZeddddddddddddVdd\d]Zeddd^ddbdcZeddd^ddddeZe	dddfddidjZedddkddmdnZeddddddoddvdwZedddddxd dzd{Zedddddxd!d}d~Zeddddddd"ddZedddkd#ddZedddkd$ddZeddddd%ddZeeddd	ddddddd&ddZeddddd'ddZe	dddddddd(ddZeddddd)ddZedddddd*ddZ edddddd+ddZ!edddddd,ddZ"eddddddddddd
d-ddZ#eddddd.ddĄZ$ee%ddddȍ	d/dddddɜd0dd΄Z&dddkd1dd҄Z'e(ddddddddd՜d2ddZ)e(ddddddddd՜d3ddZ)ee*ddddddddd՜d4ddZ)e+edddddddd5ddZ,ddddddddd6ddZ-e(dddddddddd7ddZ.e(dddddddddd8ddZ.ee*dddddddddd9ddZ.e(dddddddddddddddd:dd	Z/e(dddddddddddddddd;d
d	Z/e(dddddddddddddddd<dd	Z/e(dddddddddddddddd=dd	Z/ee*dddddddddddddddd>dd	Z/eddddddddd?ddZ0eddddddddd?ddZ1edde2dd@ddZ3eddddddddde4ddddddAd-d.Z5edddddde4ddddddd/dd0dBd4d5Z6dddddCd7d8Z7dddddDd:d;Z8eddddd<dEd=d>Z9eddd^dFd?d@Z:eddddddAdGdDdEZ;eddd^dHdFdGZ<edddHdIdJdKZ=eddddddLdJdRdSZ>edddkdKdVdWZ?edddddXdLd\d]Z@edddd^dMd_d`ZAddddadNdfdgZBeddd^dOdjdkZCeddd^dPdndoZDeddddpdQdtduZEeddddpdRdvdwZFeddd^dSdzd{ZGeddd^dTd|d}ZHeddd~dUddZIeddfdVddZJeddfdWddZKeddd~dXddZLeddfdYddZMeddfdZddZNedddd[ddZOeddfd\ddZPeddfdZddZQedddd]ddZRe	ddddddddddd^ddZSeddfd_ddZTeddfdZddZU	dddfd`ddZVddddddeWjXddd	daddZYddddbddZZdddddddddddddcdÐdĄZ[ddddddŐdƄZ\ddddbdǐdȄZ]ddddbdɐdʄZ^ddddbdːd̄Z_dded͐d΄Z`eddddddϜdfdԐdՄZaddfdgdؐdلZbddddddڜdhdܐd݄ZcdddddddޜdiddZdddddjddZedddddkddZfdddddlddZgddddmddZhedddkdnddZiedddkdnddZjedddkdnddZk		dodpddZledddkdqddZmedddkdqd dZnedddkdqddZoe		dodrddZpedddkdqddZq					dsdtd
dZrduddZsdS (v  HfApiNr   r|   tokenUnion[str, bool, None]r   library_version
user_agentUnion[Dict, str, None]headersOptional[Dict[str, str]]r}   r   c                 C  s:   |dur|nt | _|| _|| _|| _|| _|| _d| _dS )a  Create a HF client to interact with the 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:
            token (`str` or `bool`, *optional*):
                Hugging Face token. 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.
            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.
        N)rE   r   rc  r   re  rf  rh  _thread_pool)r   r   rc  r   re  rf  rh  r   r   r   r     s   !
zHfApi.__init__rV  Callable[..., R]	Future[R]c                 O  s6   | j du rtdd| _ | j  | j j|g|R i |S )a  
        Run a method in the background and return a Future instance.

        The main goal is to run methods without blocking the main thread (e.g. to push data during a training).
        Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts
        by parallelizing lots of call to the API, you must setup and use your own [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor).

        Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool`
        argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them
        but less verbose.

        Args:
            fn (`Callable`):
                The method to run in the background.
            *args, **kwargs:
                Arguments with which the method will be called.

        Return:
            `Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to
            get the result of the task.

        Example:
            ```py
            >>> from huggingface_hub import HfApi
            >>> api = HfApi()
            >>> future = api.run_as_future(api.whoami) # instant
            >>> future.done()
            False
            >>> future.result() # wait until complete and return result
            (...)
            >>> future.done()
            True
            ```
        Nr   )max_workers)rj  r   submit)r   rV  r   r   r   r   r   rW    s   
#zHfApi.run_as_futurer   c              
   C  sj   t  j| j d| j|p| jpddd}z	t| W |	 S  ty4 } z
td|j|jd|d}~ww )z
        Call HF API to know "whoami".

        Args:
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if
                not provided.
        z/api/whoami-v2Trc  rh  zInvalid user token. If you didn't pass a user token, make sure you are properly logged in by executing `huggingface-cli login`, and if you did pass a user token, double-check it's correct.)requestresponseN)
ri   r  r   _build_hf_headersrc  rj   r   rq  rr  json)r   rc  rer   r   r   whoami+  s&   


	zHfApi.whoamiLiteral['read', 'write', None]c              	   C  s4   z| j |dd d d W S  ttfy   Y dS w )a  
        Check if a given `token` is valid and return its permissions.

        For more details about tokens, please refer to https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens.

        Args:
            token (`str`, *optional*):
                The token to check for validity. Defaults to the one saved locally.

        Returns:
            `Literal["read", "write", None]`: Permission granted by the token ("read" or "write"). Returns `None` if no
            token passed or token is invalid.
        ro  authZaccessTokenZroleN)rw  r^   r   )r   rc  r   r   r   get_token_permissionI  s
   zHfApi.get_token_permissionc                 C  (   | j  d}t |}t| | S )zH
        List all valid model tags as a nested namespace object
        z/api/models-tags-by-typer   ri   r  rj   rt  r   r   ru  r   r   r   get_model_tags\     zHfApi.get_model_tagsc                 C  r{  )zK
        List all valid dataset tags as a nested namespace object.
        z/api/datasets-tags-by-typer|  r}  r   r   r   get_dataset_tagse  r  zHfApi.get_dataset_tagsF)filterr   librarylanguage
model_nametasktrained_datasetr  searchemissions_thresholdssort	directionlimitfullr  fetch_configrc  r   r  ,Union[ModelFilter, str, Iterable[str], None]r   r  Optional[Union[str, List[str]]]r  r  r  r  r  r  r  Optional[Tuple[float, float]]r  *Union[Literal['last_modified'], str, None]r  Optional[Literal[-1]]r  r   r  r   r  r   r  Optional[Union[bool, str]]r   Iterable[ModelInfo]c                c  s   |
dur|du rt d| j d}| j|d}i }g }|dur:t|tr,| |}n|d|i |ddi |rC|d|i |rL|d	|i |r[|t|trX|gn| |rj|t|trg|gn| |rt|t	t
fsv|g}|D ]}|d
sd
| }|| qx|r|t|tr|gn| |r|t|tr|gn| |	r|d	|	i |dur|d|dkrdn|i |dur|d|i |dur|d|i |dur|r|ddi nd|v r|d= |r|ddi |r|ddi |r	|d|i |dg }|r"|t|tr|gnt	| |d|i t|||d}|dur:t||}|D ]$}d|vrGd|d< tdi |}|
du s\t|g|
R  r_|V  q<dS )a  
        List models hosted on the Huggingface Hub, given some filters.

        Args:
            filter ([`ModelFilter`] or `str` or `Iterable`, *optional*):
                A string or [`ModelFilter`] which can be used to identify models
                on the Hub.
            author (`str`, *optional*):
                A string which identify the author (user or organization) of the
                returned models
            library (`str` or `List`, *optional*):
                A string or list of strings of foundational libraries models were
                originally trained from, such as pytorch, tensorflow, or allennlp.
            language (`str` or `List`, *optional*):
                A string or list of strings of languages, both by name and country
                code, such as "en" or "English"
            model_name (`str`, *optional*):
                A string that contain complete or partial names for models on the
                Hub, such as "bert" or "bert-base-cased"
            task (`str` or `List`, *optional*):
                A string or list of strings of tasks models were designed for, such
                as: "fill-mask" or "automatic-speech-recognition"
            trained_dataset (`str` or `List`, *optional*):
                A string tag or a list of string tags of the trained dataset for a
                model on the Hub.
            tags (`str` or `List`, *optional*):
                A string tag or a list of tags to filter models on the Hub by, such
                as `text-generation` or `spacy`.
            search (`str`, *optional*):
                A string that will be contained in the returned model ids.
            emissions_thresholds (`Tuple`, *optional*):
                A tuple of two ints or floats representing a minimum and maximum
                carbon footprint to filter the resulting models with in grams.
            sort (`Literal["last_modified"]` or `str`, *optional*):
                The key with which to sort the resulting models. Possible values
                are the properties of the [`huggingface_hub.hf_api.ModelInfo`] class.
            direction (`Literal[-1]` or `int`, *optional*):
                Direction in which to sort. The value `-1` sorts by descending
                order while all other values sort by ascending order.
            limit (`int`, *optional*):
                The limit on the number of models fetched. Leaving this option
                to `None` fetches all models.
            full (`bool`, *optional*):
                Whether to fetch all model data, including the `last_modified`,
                the `sha`, the files and the `tags`. This is set to `True` by
                default when using a filter.
            cardData (`bool`, *optional*):
                Whether to grab the metadata for the model as well. Can contain
                useful information such as carbon emissions, metrics, and
                datasets trained on.
            fetch_config (`bool`, *optional*):
                Whether to fetch the model configs as well. This is not included
                in `full` due to its size.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.
            pipeline_tag (`str`, *optional*):
                A string pipeline tag to filter models on the Hub by, such as `summarization`


        Returns:
            `Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects.

        Example usage with the `filter` argument:

        ```python
        >>> from huggingface_hub import HfApi

        >>> api = HfApi()

        >>> # List all models
        >>> api.list_models()

        >>> # List only the text classification models
        >>> api.list_models(filter="text-classification")

        >>> # List only models from the AllenNLP library
        >>> api.list_models(filter="allennlp")
        ```

        Example usage with the `search` argument:

        ```python
        >>> from huggingface_hub import HfApi

        >>> api = HfApi()

        >>> # List all models with "bert" in their name
        >>> api.list_models(search="bert")

        >>> # List all models with "bert" in their name made by google
        >>> api.list_models(search="bert", author="google")
        ```
        NzC`emissions_thresholds` were passed without setting `cardData=True`.z/api/modelsro  r  r  Tr   r  dataset:r  r   r  r  r  r  r  r   paramsrh  r	  r   )r   r   rs  r  rs   _unpack_model_filterr   extendrz   r_  tupler   appendr  rl   r
   r   rt   )r   r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  rc  r   r   rh  r  filter_listrw   filter_valuer8  r?  
model_infor   r   r   list_modelsn  s   w


 


zHfApi.list_modelsmodel_filterrs   c                 C  s6  d}|j r|j  d}|jr||j7 }g }|jr(|t|jtr$|jgn|j |jrLt|jttfs8|jg|_|jD ]}d|vrFd| }|	| q;|j
r_|t|j
tr[|j
gn|j
 |jrr|t|jtrn|jgn|j i }|rz||d< t|jtr||j nt|jtr|	|j t||d< |S )zU
        Unpacks a [`ModelFilter`] into something readable for `list_models`
        r   r   r  r  r  )r   r  r  r  r  rz   r  r_  r  r  r  r  r  )r   r  Z	model_strr  rw   
query_dictr   r   r   r  .  s<   
 


 zHfApi._unpack_model_filter)r  r   	benchmarkdataset_namelanguage_creatorsr  multilingualitysize_categoriestask_categoriestask_idsr  r  r  r  r  rc  .Union[DatasetFilter, str, Iterable[str], None]r  r  r  r  r  r  r  .Optional[Union[Literal['last_modified'], str]]Iterable[DatasetInfo]c                c  s   | j  d}| j|d}i }g }|dur't|tr | |}n|d|i |r0|d|i |r9|d|i ||||||	|
fD ]'}|rit|ttfsP|g}|D ]}|| dsc| d| }|	| qRqB|rs|d|i |dur|d|d	krd
n|i |dur|d|i |dur|d|i |r|ddi |
dg }|r|t|tr|gnt| |d|i t|||d}|durt||}|D ]}d|vrd|d< tdi |V  qdS )a2  
        List datasets hosted on the Huggingface Hub, given some filters.

        Args:
            filter ([`DatasetFilter`] or `str` or `Iterable`, *optional*):
                A string or [`DatasetFilter`] which can be used to identify
                datasets on the hub.
            author (`str`, *optional*):
                A string which identify the author of the returned datasets.
            benchmark (`str` or `List`, *optional*):
                A string or list of strings that can be used to identify datasets on
                the Hub by their official benchmark.
            dataset_name (`str`, *optional*):
                A string or list of strings that can be used to identify datasets on
                the Hub by its name, such as `SQAC` or `wikineural`
            language_creators (`str` or `List`, *optional*):
                A string or list of strings that can be used to identify datasets on
                the Hub with how the data was curated, such as `crowdsourced` or
                `machine_generated`.
            language (`str` or `List`, *optional*):
                A string or list of strings representing a two-character language to
                filter datasets by on the Hub.
            multilinguality (`str` or `List`, *optional*):
                A string or list of strings representing a filter for datasets that
                contain multiple languages.
            size_categories (`str` or `List`, *optional*):
                A string or list of strings that can be used to identify datasets on
                the Hub by the size of the dataset such as `100K<n<1M` or
                `1M<n<10M`.
            task_categories (`str` or `List`, *optional*):
                A string or list of strings that can be used to identify datasets on
                the Hub by the designed task, such as `audio_classification` or
                `named_entity_recognition`.
            task_ids (`str` or `List`, *optional*):
                A string or list of strings that can be used to identify datasets on
                the Hub by the specific task such as `speech_emotion_recognition` or
                `paraphrase`.
            search (`str`, *optional*):
                A string that will be contained in the returned datasets.
            sort (`Literal["last_modified"]` or `str`, *optional*):
                The key with which to sort the resulting datasets. Possible
                values are the properties of the [`huggingface_hub.hf_api.DatasetInfo`] class.
            direction (`Literal[-1]` or `int`, *optional*):
                Direction in which to sort. The value `-1` sorts by descending
                order while all other values sort by ascending order.
            limit (`int`, *optional*):
                The limit on the number of datasets fetched. Leaving this option
                to `None` fetches all datasets.
            full (`bool`, *optional*):
                Whether to fetch all dataset data, including the `last_modified`,
                the `card_data` and  the files. Can contain useful information such as the
                PapersWithCode ID.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            `Iterable[DatasetInfo]`: an iterable of [`huggingface_hub.hf_api.DatasetInfo`] objects.

        Example usage with the `filter` argument:

        ```python
        >>> from huggingface_hub import HfApi

        >>> api = HfApi()

        >>> # List all datasets
        >>> api.list_datasets()


        >>> # List only the text classification datasets
        >>> api.list_datasets(filter="task_categories:text-classification")


        >>> # List only the datasets in russian for language modeling
        >>> api.list_datasets(
        ...     filter=("language:ru", "task_ids:language-modeling")
        ... )

        >>> api.list_datasets(filter=filt)
        ```

        Example usage with the `search` argument:

        ```python
        >>> from huggingface_hub import HfApi

        >>> api = HfApi()

        >>> # List all datasets with "text" in their name
        >>> api.list_datasets(search="text")

        >>> # List all datasets with "text" in their name made by google
        >>> api.list_datasets(search="text", author="google")
        ```
        z/api/datasetsro  Nr  r   r  :r  r   r  r  r  r  Tr  r	  r   )r   rs  r  rr   _unpack_dataset_filterr   r_  r  r   r  r  r  rz   rl   r
   r  )r   r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  rc  r   rh  r  r  attrdatar  r8  r?  r   r   r   list_datasets_  sf   w
	
zHfApi.list_datasetsdataset_filterrr   c           	      C  s   d}|j r|j  d}|jr||j7 }g }g d}|D ]-}t||}|durHt|ttfs0|g}|D ]}| d|vrB| d| }|| q2qi }|durS||d< t||d< |S )zY
        Unpacks a [`DatasetFilter`] into something readable for `list_datasets`
        r   r   )r  r  r  r  r  r  r  Nr  r  r  )r   r  getattrr  r_  r  r  )	r   r  Zdataset_strr  Zdata_attributesr  Z	curr_attrr  r  r   r   r   r    s,   


zHfApi._unpack_dataset_filterList[MetricInfo]c                 C  s6   | j  d}t |}t| | }dd |D S )z
        Get the public list of all the metrics on huggingface.co

        Returns:
            `List[MetricInfo]`: a list of [`MetricInfo`] objects which.
        z/api/metricsc                 S  r<  r=  )r'  )r  xr   r   r   r  D  r@  z&HfApi.list_metrics.<locals>.<listcomp>r|  )r   r   ru  dr   r   r   list_metrics9  s
   zHfApi.list_metrics)r  r   r  r  r  r  r&  r%  linkedr  rc  Union[str, Iterable[str], None]r&  r%  r  Iterable[SpaceInfo]c                c  sL   | j  d}| j|d}i }|dur|d|i |dur%|d|i |dur0|d|i |durA|d|dkr=d	n|i |durL|d
|i |durW|d|i |
r`|ddi |	ri|ddi |durt|d|i |dur|d|i t|||d}|durt||}|D ]}d|vrd|d< tdi |V  qdS )a  
        List spaces hosted on the Huggingface Hub, given some filters.

        Args:
            filter (`str` or `Iterable`, *optional*):
                A string tag or list of tags that can be used to identify Spaces on the Hub.
            author (`str`, *optional*):
                A string which identify the author of the returned Spaces.
            search (`str`, *optional*):
                A string that will be contained in the returned Spaces.
            sort (`Literal["last_modified"]` or `str`, *optional*):
                The key with which to sort the resulting Spaces. Possible
                values are the properties of the [`huggingface_hub.hf_api.SpaceInfo`]` class.
            direction (`Literal[-1]` or `int`, *optional*):
                Direction in which to sort. The value `-1` sorts by descending
                order while all other values sort by ascending order.
            limit (`int`, *optional*):
                The limit on the number of Spaces fetched. Leaving this option
                to `None` fetches all Spaces.
            datasets (`str` or `Iterable`, *optional*):
                Whether to return Spaces that make use of a dataset.
                The name of a specific dataset can be passed as a string.
            models (`str` or `Iterable`, *optional*):
                Whether to return Spaces that make use of a model.
                The name of a specific model can be passed as a string.
            linked (`bool`, *optional*):
                Whether to return Spaces that make use of either a model or a dataset.
            full (`bool`, *optional*):
                Whether to fetch all Spaces data, including the `last_modified`, `siblings`
                and `card_data` fields.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            `Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects.
        z/api/spacesro  Nr  r   r  r  r   r  r  r  r  Tr  r&  r%  r  r	  r   )r   rs  r   rl   r
   r   )r   r  r   r  r  r  r  r&  r%  r  r  rc  r   rh  r  r8  r?  r   r   r   list_spacesF  s@   7
zHfApi.list_spaces)rc  r   r   rz   r   c                C  D   |du rt }t j| j d| d| d| j|dd}t| dS )a$  
        Like a given repo on the Hub (e.g. set as favorite).

        See also [`unlike`] and [`list_liked_repos`].

        Args:
            repo_id (`str`):
                The repository to like. Example: `"user/my-cool-model"`.

            token (`str`, *optional*):
                Authentication token. Will default to the stored token.

            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if liking a dataset or space, `None` or
                `"model"` if liking 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.

        Example:
        ```python
        >>> from huggingface_hub import like, list_liked_repos, unlike
        >>> like("gpt2")
        >>> "gpt2" in list_liked_repos().models
        True
        >>> unlike("gpt2")
        >>> "gpt2" in list_liked_repos().models
        False
        ```
        N/api/s//likero  r   rh  )rH   ri   postr   rs  rj   r   r   rc  r   rr  r   r   r   like  s   (
z
HfApi.likec                C  r  )a4  
        Unlike a given repo on the Hub (e.g. remove from favorite list).

        See also [`like`] and [`list_liked_repos`].

        Args:
            repo_id (`str`):
                The repository to unlike. Example: `"user/my-cool-model"`.

            token (`str`, *optional*):
                Authentication token. Will default to the stored token.

            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or
                `"model"` if unliking 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.

        Example:
        ```python
        >>> from huggingface_hub import like, list_liked_repos, unlike
        >>> like("gpt2")
        >>> "gpt2" in list_liked_repos().models
        True
        >>> unlike("gpt2")
        >>> "gpt2" in list_liked_repos().models
        False
        ```
        Nr  r  r  ro  r  )rH   ri   deleter   rs  rj   r  r   r   r   unlike  s   ( zHfApi.unlikero  rS  rR  c                C  s   |du r| j |d}|d dkr|d }ntd| j d| d}| j|d}tt|i |d	}t|t|d
d |D dd |D dd |D dS )a  
        List all public repos liked by a user on huggingface.co.

        This list is public so token is optional. If `user` is not passed, it defaults to
        the logged in user.

        See also [`like`] and [`unlike`].

        Args:
            user (`str`, *optional*):
                Name of the user for which you want to fetch the likes.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                Used only if `user` is not passed to implicitly determine the current
                user name.

        Returns:
            [`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for
            models, 1 for datasets and 1 for Spaces).

        Raises:
            [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
                If `user` is not passed and no token found (either from argument or from machine).

        Example:
        ```python
        >>> from huggingface_hub import list_liked_repos

        >>> likes = list_liked_repos("julien-c")

        >>> likes.user
        "julien-c"

        >>> likes.models
        ["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...]
        ```
        Nro  r2  rS  rD  zVCannot list liked repos. You must provide a 'user' as input or be logged in as a user.z/api/users/z/likesr  c                 S  (   g | ]}|d  d dkr|d  d qS )repor2  rv   rD  r   r  r  r   r   r   r  B     ( z*HfApi.list_liked_repos.<locals>.<listcomp>c                 S  r  )r  r2  rw   rD  r   r  r   r   r   r  C  r  c                 S  r  )r  r2  rx   rD  r   r  r   r   r   r  D  r  )rS  r   r%  r&  r  )rw  r   r   rs  r_  rl   rR  r   )r   rS  rc  mer   rh  r   r   r   r   list_liked_repos  s"   -

zHfApi.list_liked_reposr   rc  
List[User]c                C  s^   |du rt }| j d| d| d}| j|d}t j||d}t| | }dd |D S )	a  
        List all users who liked a given repo on the hugging Face Hub.

        See also [`like`] and [`list_liked_repos`].

        Args:
            repo_id (`str`):
                The repository to retrieve . Example: `"user/my-cool-model"`.

            token (`str`, *optional*):
                Authentication token. Will default to the stored token.

            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`.

        Returns:
            `List[User]`: a list of [`User`] objects.
        Nr  r  z/likersro  rp  c                 S  s&   g | ]}t |d  |d |d dqS )rS  r   Z	avatarUrl)r   r   rU  )rT  )r  	user_datar   r   r   r  p  s    z*HfApi.list_repo_likers.<locals>.<listcomp>)rH   r   rs  ri   r  rj   rt  )r   r   r   rc  r   rh  rr  Zlikers_datar   r   r   list_repo_likersG  s   zHfApi.list_repo_likers)revisiontimeoutsecurityStatusfiles_metadatarc  r  r  Optional[float]r  r  r   c                C  s   | j |d}|du r| j d| n| j d| dt|dd }i }	|r)d|	d< |r/d|	d	< t j||||	d
}
t|
 |
 }tdi |S )a  
        Get info on one specific model on huggingface.co

        Model can be private if you pass an acceptable token or are logged in.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            revision (`str`, *optional*):
                The revision of the model repository from which to get the
                information.
            timeout (`float`, *optional*):
                Whether to set a timeout for the request to the Hub.
            securityStatus (`bool`, *optional*):
                Whether to retrieve the security status from the model
                repository as well.
            files_metadata (`bool`, *optional*):
                Whether or not to retrieve metadata for files in the repository
                (size, LFS metadata, etc). Defaults to `False`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            [`huggingface_hub.hf_api.ModelInfo`]: The model repository information.

        <Tip>

        Raises the following errors:

            - [`~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.

        </Tip>
        ro  N/api/models/
/revision/r   r   Tr  blobsrh  r  r  r   )rs  r   r   ri   r  rj   rt  r   )r   r   r  r  r  r  rc  rh  r   r  ru  r  r   r   r   r  y  s   4zHfApi.model_info)r  r  r  rc  r  c                C     | j |d}|du r| j d| n| j d| dt|dd }i }|r)d|d< t j||||d	}	t|	 |	 }
td
i |
S )a[  
        Get info on one specific dataset on huggingface.co.

        Dataset can be private if you pass an acceptable token.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            revision (`str`, *optional*):
                The revision of the dataset repository from which to get the
                information.
            timeout (`float`, *optional*):
                Whether to set a timeout for the request to the Hub.
            files_metadata (`bool`, *optional*):
                Whether or not to retrieve metadata for files in the repository
                (size, LFS metadata, etc). Defaults to `False`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            [`hf_api.DatasetInfo`]: The dataset repository information.

        <Tip>

        Raises the following errors:

            - [`~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.

        </Tip>
        ro  Nz/api/datasets/r  r   r  Tr  r  r   )rs  r   r   ri   r  rj   rt  r  r   r   r  r  r  rc  rh  r   r  ru  r  r   r   r   dataset_info     0zHfApi.dataset_infor   c                C  r  )aR  
        Get info on one specific Space on huggingface.co.

        Space can be private if you pass an acceptable token.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            revision (`str`, *optional*):
                The revision of the space repository from which to get the
                information.
            timeout (`float`, *optional*):
                Whether to set a timeout for the request to the Hub.
            files_metadata (`bool`, *optional*):
                Whether or not to retrieve metadata for files in the repository
                (size, LFS metadata, etc). Defaults to `False`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            [`~hf_api.SpaceInfo`]: The space repository information.

        <Tip>

        Raises the following errors:

            - [`~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.

        </Tip>
        ro  N/api/spaces/r  r   r  Tr  r  r   )rs  r   r   ri   r  rj   rt  r   r  r   r   r   
space_info  r  zHfApi.space_info)r  r   r  r  rc  (Union[ModelInfo, DatasetInfo, SpaceInfo]c                C  sR   |du s|dkr| j }n|dkr| j}n|dkr| j}ntd||||||dS )a  
        Get the info object for a given repo of a given type.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            revision (`str`, *optional*):
                The revision of the repository from which to get the
                information.
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
                `None` or `"model"` if getting repository info from a model. Default is `None`.
            timeout (`float`, *optional*):
                Whether to set a timeout for the request to the Hub.
            files_metadata (`bool`, *optional*):
                Whether or not to retrieve metadata for files in the repository
                (size, LFS metadata, etc). Defaults to `False`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            `Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a
            [`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`]
            or [`huggingface_hub.hf_api.SpaceInfo`] object.

        <Tip>

        Raises the following errors:

            - [`~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.

        </Tip>
        Nrv   rw   rx   zUnsupported repo type.)r  rc  r  r  )r  r  r  r   )r   r   r  r   r  r  rc  methodr   r   r   	repo_info;	  s   4zHfApi.repo_infoc                C  s>   z| j |||d W dS  ty   Y dS  ty   Y dS w )a  
        Checks if a repository exists on the Hugging Face Hub.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
                `None` or `"model"` if getting repository info from a model. Default is `None`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            True if the repository exists, False otherwise.

        Examples:
            ```py
            >>> from huggingface_hub import repo_exists
            >>> repo_exists("google/gemma-7b")
            True
            >>> repo_exists("google/not-a-repo")
            False
            ```
        r   r   rc  TF)r  r[   r`   r   r   r   rc  r   r   r   repo_exists	  s   $zHfApi.repo_existsc                C  s@   z| j ||||d W dS  ty   Y dS  ty   Y dS w )a3  
        Checks if a specific revision exists on a repo on the Hugging Face Hub.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            revision (`str`):
                The revision of the repository to check.
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
                `None` or `"model"` if getting repository info from a model. Default is `None`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            True if the repository and the revision exists, False otherwise.

        Examples:
            ```py
            >>> from huggingface_hub import revision_exists
            >>> revision_exists("google/gemma-7b", "float16")
            True
            >>> revision_exists("google/gemma-7b", "not-a-revision")
            False
            ```
        r   r  r   rc  TF)r  ra   r`   r   r   r  r   rc  r   r   r   revision_exists	  s   'zHfApi.revision_exists)r   r  rc  filenamec             
   C  s^   t ||||| jd}z|du r| j}t||d W dS  ty"     tttfy.   Y dS w )a  
        Checks if a file exists in a repository on the Hugging Face Hub.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            filename (`str`):
                The name of the file to check, for example:
                `"config.json"`
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
                `None` or `"model"` if getting repository info from a model. Default is `None`.
            revision (`str`, *optional*):
                The revision of the repository from which to get the information. Defaults to `"main"` branch.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Returns:
            True if the file exists, False otherwise.

        Examples:
            ```py
            >>> from huggingface_hub import file_exists
            >>> file_exists("bigcode/starcoder", "config.json")
            True
            >>> file_exists("bigcode/starcoder", "not-a-file")
            False
            >>> file_exists("bigcode/not-a-repo", "config.json")
            False
            ```
        )r   r   r  r  r   Nro  TF)rT   r   rc  rS   r[   r`   rZ   ra   )r   r   r  r   r  rc  r   r   r   r   file_exists	  s   -zHfApi.file_existsz0.23z2Use `list_repo_tree` and `get_paths_info` instead.)versionrO  )expandr  r   rc  pathsUnion[List[str], str, None]r  Iterable[RepoFile]c             	   c  sT   |pt }|durt|ddnt}| j|d}g }|du r#|d nI|g kr)dS t j| j d| d| d| t|t	r@|n|g|d|d	}	t
|	 |	 }
|
D ]}|d
 dkrdtdi |V  qS||d  qS|D ]9}|rzdt|dd nd}| j d| d| d| | }t||d|ddD ]}|d
 dkrtdi |V  qqndS )a  
        List files on a repo and get information about them.

        Takes as input a list of paths. Those paths can be either files or folders. Two server endpoints are called:
        1. POST "/paths-info" to get information about the provided paths. Called once.
        2. GET  "/tree?recursive=True" to paginate over the input folders. Called only if a folder path is provided as
           input. Will be called multiple times to follow pagination.
        If no path is provided as input, step 1. is ignored and all files from the repo are listed.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated by a `/`.
            paths (`Union[List[str], str, None]`, *optional*):
                The paths to get information about. Paths to files are directly resolved. Paths to folders are resolved
                recursively which means that information is returned about all files in the folder and its subfolders.
                If `None`, all files are returned (the default). If a path do not exist, it is ignored without raising
                an exception.
            expand (`bool`, *optional*, defaults to `False`):
                Whether to fetch more information about the files (e.g. last commit and security scan results). This
                operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
                As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
                takes to get the results.
            revision (`str`, *optional*):
                The revision of the repository from which to get the information. Defaults to `"main"` branch.
            repo_type (`str`, *optional*):
                The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
                Defaults to `"model"`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
                machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
                retrieved from the cache. If `False`, token is not sent in the request header.

        Returns:
            `Iterable[RepoFile]`:
                The information about the files, as an iterable of [`RepoFile`] objects. The order of the files is
                not guaranteed.

        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.

        Examples:

            Get information about files on a repo.
            ```py
            >>> from huggingface_hub import list_files_info
            >>> files_info = list_files_info("lysandre/arxiv-nlp", ["README.md", "config.json"])
            >>> files_info
            <generator object HfApi.list_files_info at 0x7f93b848e730>
            >>> list(files_info)
            [
                RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
                RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None)
            ]
            ```

            Get even more information about files on a repo (last commit and security scan results)
            ```py
            >>> from huggingface_hub import list_files_info
            >>> files_info = list_files_info("prompthero/openjourney-v4", expand=True)
            >>> list(files_info)
            [
                RepoFile(
                    path='safety_checker/pytorch_model.bin',
                    size=1216064769,
                    blob_id='c8835557a0d3af583cb06c7c154b7e54a069c41d',
                    lfs={
                        'size': 1216064769,
                        'sha256': '16d28f2b37109f222cdc33620fdd262102ac32112be0352a7f77e9614b35a394',
                        'pointer_size': 135
                    },
                    last_commit={
                        'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
                        'title': 'Upload diffusers weights (#48)',
                        'date': datetime.datetime(2023, 3, 21, 10, 5, 27, tzinfo=datetime.timezone.utc)
                    },
                    security={
                        'safe': True,
                        'av_scan': {
                            'virusFound': False,
                            'virusNames': None
                        },
                        'pickle_import_scan': {
                            'highestSafetyLevel': 'innocuous',
                            'imports': [
                                {'module': 'torch', 'name': 'FloatStorage', 'safety': 'innocuous'},
                                {'module': 'collections', 'name': 'OrderedDict', 'safety': 'innocuous'},
                                {'module': 'torch', 'name': 'LongStorage', 'safety': 'innocuous'},
                                {'module': 'torch._utils', 'name': '_rebuild_tensor_v2', 'safety': 'innocuous'}
                            ]
                        }
                    }
                ),
                RepoFile(
                    path='scheduler/scheduler_config.json',
                    size=465,
                    blob_id='70d55e3e9679f41cbc66222831b38d5abce683dd',
                    lfs=None,
                    last_commit={
                        'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
                        'title': 'Upload diffusers weights (#48)',
                        'date': datetime.datetime(2023, 3, 21, 10, 5, 27, tzinfo=datetime.timezone.utc)},
                        security={
                            'safe': True,
                            'av_scan': {
                                'virusFound': False,
                                'virusNames': None
                            },
                            'pickle_import_scan': None
                        }
                ),
                ...
            ]
            ```

            List LFS files from the "vae/" folder in "stabilityai/stable-diffusion-2" repository.

            ```py
            >>> from huggingface_hub import list_files_info
            >>> [info.path for info in list_files_info("stabilityai/stable-diffusion-2", "vae") if info.lfs is not None]
            ['vae/diffusion_pytorch_model.bin', 'vae/diffusion_pytorch_model.safetensors']
            ```

            List all files on a repo.
            ```py
            >>> from huggingface_hub import list_files_info
            >>> [info.path for info in list_files_info("glue", repo_type="dataset")]
            ['.gitattributes', 'README.md', 'dataset_infos.json', 'glue.py']
            ```
        Nr   r  ro  r  r  /paths-info/r  r  r  rh  r2  filer   r   /tree/T	recursiver  r   rh  r  r   )rH   r   rB   rs  r  ri   r  r   r  r_  rj   rt  r   rl   )r   r   r  r  r  r   rc  rh  Zfolder_pathsrr  
paths_info	path_infor   Zencoded_pathtree_urlZsubpath_infor   r   r   list_files_info
  s@     zHfApi.list_files_info)r  r   rc  r   c                C  s   dd | j |d|||dD S )a  
        Get the list of files in a given repo.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated by a `/`.
            revision (`str`, *optional*):
                The revision of the model repository from which to get the information.
            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 (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
                machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
                retrieved from the cache. If `False`, token is not sent in the request header.

        Returns:
            `List[str]`: the list of files in a given repository.
        c                 S  s   g | ]
}t |tr|jqS r   )r  r   r   )r  fr   r   r   r  
  s    z)HfApi.list_repo_files.<locals>.<listcomp>T)r   r  r  r   rc  )list_repo_treer  r   r   r   list_repo_files
  s
   
zHfApi.list_repo_files)r  r  r  r   rc  path_in_repor  %Iterable[Union[RepoFile, RepoFolder]]c                c  s    |pt }|durt|ddnt}| j|d}|r!dt|dd nd}	| j d| d| d| |	 }
t|
|||d	d
D ]}|d dkrLtdi |ntdi |V  q=dS )a  
        List a repo tree's files and folders and get information about them.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated by a `/`.
            path_in_repo (`str`, *optional*):
                Relative path of the tree (folder) in the repo, for example:
                `"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository.
            recursive (`bool`, *optional*, defaults to `False`):
                Whether to list tree's files and folders recursively.
            expand (`bool`, *optional*, defaults to `False`):
                Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This
                operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
                As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
                takes to get the results.
            revision (`str`, *optional*):
                The revision of the repository from which to get the tree. Defaults to `"main"` branch.
            repo_type (`str`, *optional*):
                The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`.
                Defaults to `"model"`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
                machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
                retrieved from the cache. If `False`, token is not sent in the request header.

        Returns:
            `Iterable[Union[RepoFile, RepoFolder]]`:
                The information about the tree's files and folders, as an iterable of [`RepoFile`] and [`RepoFolder`] objects. The order of the files and folders is
                not guaranteed.

        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.EntryNotFoundError`]:
                If the tree (folder) does not exist (error 404) on the repo.

        Examples:

            Get information about a repo's tree.
            ```py
            >>> from huggingface_hub import list_repo_tree
            >>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
            >>> repo_tree
            <generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
            >>> list(repo_tree)
            [
                RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
                RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
                RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
                RepoFile(
                    path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
                    lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
                ),
                RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
                RepoFile(
                    path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
                    lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
                ),
                RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
            ]
            ```

            Get even more information about a repo's tree (last commit and files' security scan results)
            ```py
            >>> from huggingface_hub import list_repo_tree
            >>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
            >>> list(repo_tree)
            [
                RepoFolder(
                    path='feature_extractor',
                    tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
                    last_commit={
                        'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
                        'title': 'Upload diffusers weights (#48)',
                        'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
                    }
                ),
                RepoFolder(
                    path='safety_checker',
                    tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
                    last_commit={
                        'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
                        'title': 'Upload diffusers weights (#48)',
                        'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
                    }
                ),
                RepoFile(
                    path='model_index.json',
                    size=582,
                    blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
                    lfs=None,
                    last_commit={
                        'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
                        'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
                        'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
                    },
                    security={
                        'safe': True,
                        'av_scan': {'virusFound': False, 'virusNames': None},
                        'pickle_import_scan': None
                    }
                )
                ...
            ]
            ```
        Nr   r  ro  r   r  r  r  r  r  r2  r  r   )rH   r   rB   rs  r   rl   r   r   )r   r   r  r  r  r  r   rc  rh  Zencoded_path_in_repor  r  r   r   r   r  
  s   z ,zHfApi.list_repo_tree)r   include_pull_requestsrc  r   rH  c                  s   |pt }t j| j d| d| d| j|d|rddini d}t| | }ddd t fdd|d D  fdd|d D  fdd|d D |r\ fdd|d D dS ddS )a  
        Get the list of refs of a given repo (both tags and branches).

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if listing refs from a dataset or a Space,
                `None` or `"model"` if listing from a model. Default is `None`.
            include_pull_requests (`bool`, *optional*):
                Whether to include refs from pull requests in the list. Defaults to `False`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        Example:
        ```py
        >>> from huggingface_hub import HfApi
        >>> api = HfApi()
        >>> api.list_repo_refs("gpt2")
        GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])

        >>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset')
        GitRefs(
            branches=[
                GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'),
                GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714')
            ],
            converts=[],
            tags=[
                GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da')
            ]
        )
        ```

        Returns:
            [`GitRefs`]: object containing all information about branches and tags for a
            repo on the Hub.
        r  r  z/refsro  Zinclude_prsr   rh  r  r?  r   r}   rC  c                 S  s   t | d | d | d dS )NrD  rE  ZtargetCommit)rD  rE  rF  )rC  r?  r   r   r   _format_as_git_ref_info  s   z5HfApi.list_repo_refs.<locals>._format_as_git_ref_infoc                      g | ]} |qS r   r   r>  r  r   r   r        z(HfApi.list_repo_refs.<locals>.<listcomp>rI  c                   r  r   r   r>  r  r   r   r    r  rJ  c                   r  r   r   r>  r  r   r   r    r  r  c                   r  r   r   r>  r  r   r   r    r  ZpullRequestsN)rI  rJ  r  rK  )r?  r   r}   rC  )rH   ri   r  r   rs  rj   rt  rH  )r   r   r   r   rc  rr  r  r   r  r   list_repo_refss  s$   3

zHfApi.list_repo_refs)r   rc  r  	formattedr  List[GitCommitInfo]c             	   C  sd   |pt }|durt|ddnt}dd t| j d| d| d| | j|d	|r,d
dini dD S )a	  
        Get the list of commits of a given revision for a repo on the Hub.

        Commits are sorted by date (last commit first).

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated by a `/`.
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
                listing from a model. Default is `None`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.
            revision (`str`, *optional*):
                The git revision to commit from. Defaults to the head of the `"main"` branch.
            formatted (`bool`):
                Whether to return the HTML-formatted title and description of the commits. Defaults to False.

        Example:
        ```py
        >>> from huggingface_hub import HfApi
        >>> api = HfApi()

        # Commits are sorted by date (last commit first)
        >>> initial_commit = api.list_repo_commits("gpt2")[-1]

        # Initial commit is always a system commit containing the `.gitattributes` file.
        >>> initial_commit
        GitCommitInfo(
            commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
            authors=['system'],
            created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
            title='initial commit',
            message='',
            formatted_title=None,
            formatted_message=None
        )

        # Create an empty branch by deriving from initial commit
        >>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)
        ```

        Returns:
            List[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub.

        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.
        Nr   r  c                 S  s`   g | ],}t |d  dd |d D t|d |d |d |di d|di ddqS )	r   c                 S  s   g | ]}|d  qS )rS  r   )r  r   r   r   r   r    r  z6HfApi.list_repo_commits.<locals>.<listcomp>.<listcomp>rN  r   r   rO  r  )rM  rN  r   r   rO  rP  rQ  )rL  rm   r  r>  r   r   r   r     s    

z+HfApi.list_repo_commits.<locals>.<listcomp>r  r  z	/commits/ro  zexpand[]r  r  )rH   r   rB   rl   r   rs  )r   r   r   rc  r  r  r   r   r   list_repo_commits  s   A

zHfApi.list_repo_commitsUnion[List[str], str]!List[Union[RepoFile, RepoFolder]]c          
      C  s   |pt }|durt|ddnt}| j|d}t j| j d| d| d| t|tr-|n|g|d|d	}t	| |
 }	d
d |	D S )a	  
        Get information about a repo's paths.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated by a `/`.
            paths (`Union[List[str], str]`, *optional*):
                The paths to get information about. If a path do not exist, it is ignored without raising
                an exception.
            expand (`bool`, *optional*, defaults to `False`):
                Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This
                operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
                As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
                takes to get the results.
            revision (`str`, *optional*):
                The revision of the repository from which to get the information. Defaults to `"main"` branch.
            repo_type (`str`, *optional*):
                The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
                Defaults to `"model"`.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
                machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
                retrieved from the cache. If `False`, token is not sent in the request header.

        Returns:
            `List[Union[RepoFile, RepoFolder]]`:
                The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects.

        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.

        Example:
        ```py
        >>> from huggingface_hub import get_paths_info
        >>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
        >>> paths_info
        [
            RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
            RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
        ]
        ```
        Nr   r  ro  r  r  r  r  r  c                 S  s4   g | ]}|d  dkrt di |ntdi |qS )r2  r  r   )r   r   )r  r  r   r   r   r  X  s    &z(HfApi.get_paths_info.<locals>.<listcomp>)rH   r   rB   rs  ri   r  r   r  r_  rj   rt  )
r   r   r  r  r  r   rc  rh  rr  r  r   r   r   get_paths_info  s   9zHfApi.get_paths_info)branchr   r   rc  r  r   c          	      C  s   |du rt }|tvrtd|du rt}| j d| d| d| }| j|d}|p/d| d}t j||d	|id
}t| dS )a
  Squash commit history on a branch for a repo on the Hub.

        Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to
        clutter the history. Squashing commits can only be performed from the head of a branch.

        <Tip warning={true}>

        Once squashed, the commit history cannot be retrieved. This is a non-revertible operation.

        </Tip>

        <Tip warning={true}>

        Once the history of a branch has been squashed, it is not possible to merge it back into another branch since
        their history will have diverged.

        </Tip>

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated by a `/`.
            branch (`str`, *optional*):
                The branch to squash. Defaults to the head of the `"main"` branch.
            commit_message (`str`, *optional*):
                The commit message to use for the squashed commit.
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
                listing from a model. Default is `None`.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token). If the machine is logged in
                (through `huggingface-cli login` or [`~huggingface_hub.login`]), token can be automatically retrieved
                from the cache.

        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 the branch to squash cannot be found.
            [`~utils.BadRequestError`]:
                If invalid reference for a branch. You cannot squash history on tags.

        Example:
        ```py
        >>> from huggingface_hub import HfApi
        >>> api = HfApi()

        # Create repo
        >>> repo_id = api.create_repo("test-squash").repo_id

        # Make a lot of commits.
        >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
        >>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
        >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")

        # Squash history
        >>> api.super_squash_history(repo_id=repo_id)
        ```
        NInvalid repo typer  r  z/super-squash/ro  zSuper-squash branch 'z' using huggingface_hubrO  r   rh  rt  )	rH   rI   r   rB   r   rs  ri   r  rj   )	r   r   r  r   r   rc  r   rh  rr  r   r   r   super_squash_history]  s   EzHfApi.super_squash_history)
rc  r   r   exist_ok	space_sdkspace_hardwarespace_storagespace_sleep_timespace_secretsspace_variablesr   r  r  r  Optional[SpaceHardware]r  Optional[SpaceStorage]r  r  Optional[List[Dict[str, str]]]r  r   c       
         C  sp  d|v r	| dnd|f\}}| j d}|tvrtd|||d}|dur+||d< |dkrK|du r;tdt d	|tvrGtd
t d||d< |durX|dkrXtd g d}g d}|||	|
|g}|dkry|dd t||D  ndd t||D }|rtdd	| d t
| ddr| j|d< | j|d}	 t j|||d}|jdkrd|jv rtd q	 zt| W ng ty* } zZ|r|jjdkrnK|r|jjdkrz6| j|||d  |du s|tkrt| j d| W W  Y d}~S t| j d| d| W W  Y d}~S  ty    w  W Y d}~nd}~ww | }t|d! | jd"S )#ab
  Create an empty repo on the HuggingFace Hub.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)
            private (`bool`, *optional*, defaults to `False`):
                Whether the model repo should be private.
            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`.
            exist_ok (`bool`, *optional*, defaults to `False`):
                If `True`, do not raise an error if repo already exists.
            space_sdk (`str`, *optional*):
                Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static".
            space_hardware (`SpaceHardware` or `str`, *optional*):
                Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list.
            space_storage (`SpaceStorage` or `str`, *optional*):
                Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
            space_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).
                See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
            space_secrets (`List[Dict[str, str]]`, *optional*):
                A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
                For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
            space_variables (`List[Dict[str, str]]`, *optional*):
                A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
                For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.

        Returns:
            [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
            attributes like `endpoint`, `repo_type` and `repo_id`.
        r   Nz/api/repos/creater  )rD  organizationr   r2  rx   zDNo space_sdk provided. `create_repo` expects space_sdk to be one of z when repo_type is 'space'`z(Invalid space_sdk. Please choose one of .r#  z=Ignoring provided space_sdk because repo_type is not 'space'.)r  r  r  r  r  )hardwarestorageTiersleepTimeSecondssecrets	variablesc                 S     i | ]\}}|d ur||qS r   r   r  kvr   r   r   
<dictcomp>
      z%HfApi.create_repo.<locals>.<dictcomp>c                 S  s   g | ]
\}}|d ur|qS r   r   r  keyrZ  r   r   r   r        z%HfApi.create_repo.<locals>.<listcomp>zIgnoring provided , z" because repo_type is not 'space'._lfsmultipartthreshZlfsmultipartthreshro  Trh  rt    z@Cannot create repo: another conflicting operation is in progressz:Create repo failed due to a concurrency issue. Retrying...i  r  r   r   )r   r   rI   r   rO   warningswarnr   rX  joinr  r-  rs  ri   r  status_coder4  loggerdebugrj   r   rr  r  rH   r   r]   rt  )r   r   rc  r   r   r  r  r  r  r  r  r  r  rD  r   rt  Zfunction_argsZ	json_keysvaluesZprovided_space_argsrh  ru  errr  r   r   r   create_repo  sp   6


"(zHfApi.create_repo)rc  r   
missing_okr:  c                C  s   d|v r	| dnd|f\}}| j d}|tvrtd||d}|dur*||d< | j|d}	t j||	|d}
zt|
 W dS  tyM   |sJ Y dS w )	a]  
        Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if uploading to a dataset or
                space, `None` or `"model"` if uploading to a model.
            missing_ok (`bool`, *optional*, defaults to `False`):
                If `True`, do not raise an error if repo does not exist.

        Raises:
            - [`~utils.RepositoryNotFoundError`]
              If the repository to delete from cannot be found and `missing_ok` is set to False (default).
        r   Nz/api/repos/deleter  )rD  r  r2  ro  r.  )	r   r   rI   r   rs  ri   r  rj   r`   )r   r   rc  r   r:  r  rD  r   rt  rh  ru  r   r   r   delete_repo9  s    
zHfApi.delete_repoz0.24.0)r  rD  zUse `repo_id` instead.)r  Zdeprecated_argsZcustom_message)rc  r  r   rD  r  rD  Dict[str, bool]c          	   	   C  s   |t vrtdd|v r|dnd|f\}}|du r#| |d }n|}|du r+t}t j| j d| d| d| d| j|dd	|id
}t	| |
 S )a  Update the visibility setting of a repository.

        Args:
            repo_id (`str`, *optional*):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            private (`bool`, *optional*, defaults to `False`):
                Whether the model repo should be private.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)
            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`.

        Returns:
            The HTTP response in json.

        <Tip>

        Raises the following errors:

            - [`~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>
        r  r   NrD  r  r  z	/settingsro  r   r  )rI   r   r   rw  rH   ri   putr   rs  rj   rt  )	r   r   r   rc  r  r   rD  r   ru  r   r   r   update_repo_visibilityh  s   *
zHfApi.update_repo_visibilityfrom_idto_idc          
   
   C  s   t |ddkrtd| dt |ddkr"td| d|du r(t}|||d}| j d}| j|d}t j|||d	}zt| W dS  t	y\ }	 z|	
d
  d}	~	ww )a  
        Moving a repository from namespace1/repo_name1 to namespace2/repo_name2

        Note there are certain limitations. For more information about moving
        repositories, please see
        https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.

        Args:
            from_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`. Original repository identifier.
            to_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`. Final repository identifier.
            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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)

        <Tip>

        Raises the following errors:

            - [`~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>
        r   r   zInvalid repo_id: z6. It should have a namespace (:namespace:/:repo_name:)N)ZfromRepoZtoRepor2  z/api/repos/movero  r.  zv
For additional documentation please see https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.)r   r   r   rH   r   rs  ri   r  rj   r]   append_to_message)
r   r?  r@  r   rc  rt  r   rh  ru  rv  r   r   r   	move_repo  s&   'zHfApi.move_repo   .)r   rc  r   r  	create_prnum_threadsparent_commitrW  
operationsIterable[CommitOperation]r   rD  rE  r   rF  rW  Literal[False]r   c       	         C     d S r   r   r   r   rG  r   r   rc  r   r  rD  rE  rF  rW  r   r   r   create_commit     zHfApi.create_commitLiteral[True]Future[CommitInfo]c       	         C  rJ  r   r   rK  r   r   r   rL    rM  %Union[CommitInfo, Future[CommitInfo]]c       	   !        s  |
durt |
stdt  |du st|dkrtd|dur$|nd}|dur,|nt}|tvr9tdt |p<t}t|dd}|durI|nd}| j|d	}t	|}d
d |D }dd |D }t|}t|}t|| | }|D ]}|j
rtd| dqutdt| dt| d| d |D ]w}|jdkr| b}t jt d|  |d|d}| }ddd |dg D }|rtd|  zt| W n$ ty } z|dg }ddd |D }td| |d}~ww W d   n	1 s
w   Y  qt| | j|||||||	dd t|||||| jd}t|||||
d  | j d!| d"| d#| }d7 fd&d'}d(d)i|}d*| }|r]d+d,ind}zt j||||d-}t|d.d/ W n1 t y } z|!t"  d}~w t#y } z|dkrd0t$|v r|!d1  d}~ww |D ]}d2|_
q| } t%| d3 ||| d4 |r| d5 d6S dd6S )8aJ  
        Creates a commit in the given repo, deleting & uploading files as needed.

        <Tip warning={true}>

        The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects
        for multiple commits.

        </Tip>

        <Tip warning={true}>

        `create_commit` assumes that the repo already exists on the Hub. If you get a
        Client error 404, please make sure you are authenticated and that `repo_id` and
        `repo_type` are set correctly. If repo does not exist, create it first using
        [`~hf_api.create_repo`].

        </Tip>

        <Tip warning={true}>

        `create_commit` is limited to 25k LFS files and a 1GB payload for regular files.

        </Tip>

        Args:
            repo_id (`str`):
                The repository in which the commit will be created, for example:
                `"username/custom_transformers"`

            operations (`Iterable` of [`~hf_api.CommitOperation`]):
                An iterable of operations to include in the commit, either:

                    - [`~hf_api.CommitOperationAdd`] to upload a file
                    - [`~hf_api.CommitOperationDelete`] to delete a file
                    - [`~hf_api.CommitOperationCopy`] to copy a file

                Operation objects will be mutated to include information relative to the upload. Do not reuse the
                same objects for multiple commits.

            commit_message (`str`):
                The summary (first line) of the commit that will be created.

            commit_description (`str`, *optional*):
                The description of the commit that will be created

            token (`str`, *optional*):
                Authentication token, obtained with `HfApi.login` method. Will
                default to the stored token.

            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`.

            revision (`str`, *optional*):
                The git revision to commit from. Defaults to the head of the `"main"` branch.

            create_pr (`boolean`, *optional*):
                Whether or not to create a Pull Request with that commit. Defaults to `False`.
                If `revision` is not set, PR is opened against the `"main"` branch. If
                `revision` is set and is a branch, PR is opened against this branch. If
                `revision` is set and is not a branch name (example: a commit oid), an
                `RevisionNotFoundError` is returned by the server.

            num_threads (`int`, *optional*):
                Number of concurrent threads for uploading files. Defaults to 5.
                Setting it to 2 means at most 2 files will be uploaded concurrently.

            parent_commit (`str`, *optional*):
                The OID / SHA of the parent commit, as a hexadecimal string.
                Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`,
                the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr`
                is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit`
                ensures the repo has not changed before committing the changes, and can be especially useful
                if the repo is updated / committed to concurrently.
            run_as_future (`bool`, *optional*):
                Whether or not to run this method in the background. Background jobs are run sequentially without
                blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
                object. Defaults to `False`.

        Returns:
            [`CommitInfo`] or `Future`:
                Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
                url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
                contain the result when executed.

        Raises:
            [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
                If commit message is empty.
            [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
                If parent commit is not a valid commit OID.
            [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
                If a README.md file with an invalid metadata section is committed. In this case, the commit will fail
                early, before trying to upload any file.
            [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
                If `create_pr` is `True` and revision is neither `None` nor `"main"`.
            [`~utils.RepositoryNotFoundError`]:
                If repository is not found (error 404): wrong repo_id/repo_type, private
                but not authenticated or repo does not exist.
        NzN`parent_commit` is not a valid commit OID. It must match the following regex: r   z5`commit_message` can't be empty, please pass a value.r   "Invalid repo type, must be one of r  Fro  c                 S     g | ]	}t |tr|qS r   )r  r   r  opr   r   r   r    r@  z'HfApi.create_commit.<locals>.<listcomp>c                 S  rR  r   )r  r    rS  r   r   r   r    r@  zCommitOperationAdd z has already being committed and cannot be reused. Please create a new CommitOperationAdd object if you want to create a new commit.zAbout to commit to the hub: z addition(s), z copie(s) and z deletion(s).z	README.mdz/api/validate-yaml)contentZrepoTypert  rh  
c                 S     g | ]
}d | d qS z- rO  r  )r  warningr   r   r   r    r+  r1  z1Warnings while validating metadata in README.md:
errorsc                 S  rX  rY  rZ  )r  errorr   r   r   r    r+  zInvalid metadata in README.md.
)r   	additionsrc  r   r  rD  rE  free_memory)copiesr   r   rh  r  r   )rG  files_to_copyr   r   rF  r  r  z/commit/r}   Iterable[bytes]c                  3  s&     D ]} t |  V  dV  qd S )N   
)rt  dumpsencoder  Zcommit_payloadr   r   _payload_as_ndjson  s
   z/HfApi.create_commit.<locals>._payload_as_ndjsonzContent-Typezapplication/x-ndjson    rD  1)r   rh  r  r  commit)Zendpoint_namez#A file with this name doesn't existz{
Make sure to differentiate file and folder paths in delete operations with a trailing '/' or using `is_folder=True/False`.TZ	commitUrlZ	commitOidZpullRequestUrl)r   r   r   r   r   )r}   rb  )&rG   	fullmatchr   r   rH   rI   rB   r   rs  r_  Z_is_committedr5  r6  r  as_fileri   r  rE   readdecodert  r3  r  r1  r2  rj   rY   r&   preupload_lfs_filesr"   r   r$   r`   rA  $_CREATE_COMMIT_NO_REPO_ERROR_MESSAGErZ   rz   r   )!r   r   rG  r   r   rc  r   r  rD  rE  rF  rW  Zunquoted_revisionrh  r^  r`  Znb_additionsZ	nb_copiesZnb_deletionsadditionr  rr  Zresponse_contentrO  rv  r\  ra  r   rg  r  r  Zcommit_respZcommit_datar   rf  r   rL    s   v



	
T)r   rc  r   merge_prrE  verboseaddition_commitsList[List[CommitOperationAdd]]deletion_commits!List[List[CommitOperationDelete]]rr  rs  c       
           s  t td }|
r|d |dt| dt| dtdd || D  d td	d
 |D dd
 |D d}|d|j d | j	|||dD ]&}|j
rr|jdkrr|j|jv rr| j||j||d}|d|j d  nqLt| ||||||d}|d|j  |jD ]}t|tr|} n
qtd|j dt|j}t|t|jkrtd|j dt| dt|j d|jD ]}||vrtd|j d| dd| dqd d! | j|||td"D   fd#d
| j||||jd"D }t|d$kr|d%t| d& t|t|jkr,td|j d't|j d(t| d)d*d+ |jD }d,d+ |jD }|D ]#}|j|v rQ||j}d-|_q>|j|v r`||j}d-|_q>t|d$kr|t|t|jk r|td|j d.t|t| }t|d$kr|| d/t| d0t| d1 t |! t |!  D ]9}| j"||||j|j|	|j#d2d3 d-|_|d48 }|d5|j d6| d7 | j$||||j|jt%|||d8d9 q|d: | j&||||j|d; | j'||||jd<t(d= |d> |rhz| j)||||jt*d? |d@ W |jS  t+yg } z?|j,dAurBdB|j,v rB| j'||||jt-dCdD |.dE n| j/||||jt0j1|j,dFd? tdG|j, |W Y dA}~|jS dA}~ww |jS )Ha&  Push changes to the Hub in multiple commits.

        Commits are pushed to a draft PR branch. If the upload fails or gets interrupted, it can be resumed. Progress
        is tracked in the PR description. At the end of the process, the PR is set as open and the title is updated to
        match the initial commit message. If `merge_pr=True` is passed, the PR is merged automatically.

        All deletion commits are pushed first, followed by the addition commits. The order of the commits is not
        guaranteed as we might implement parallel commits in the future. Be sure that your are not updating several
        times the same file.

        <Tip warning={true}>

        `create_commits_on_pr` is experimental.  Its API and behavior is subject to change in the future without prior notice.

        </Tip>

        <Tip warning={true}>

        `create_commits_on_pr` assumes that the repo already exists on the Hub. If you get a Client error 404, please
        make sure you are authenticated and that `repo_id` and `repo_type` are set correctly. If repo does not exist,
        create it first using [`~hf_api.create_repo`].

        </Tip>

        Args:
            repo_id (`str`):
                The repository in which the commits will be pushed. Example: `"username/my-cool-model"`.

            addition_commits (`List` of `List` of [`~hf_api.CommitOperationAdd`]):
                A list containing lists of [`~hf_api.CommitOperationAdd`]. Each sublist will result in a commit on the
                PR.

            deletion_commits
                A list containing lists of [`~hf_api.CommitOperationDelete`]. Each sublist will result in a commit on
                the PR. Deletion commits are pushed before addition commits.

            commit_message (`str`):
                The summary (first line) of the commit that will be created. Will also be the title of the PR.

            commit_description (`str`, *optional*):
                The description of the commit that will be created. The description will be added to the PR.

            token (`str`, *optional*):
                Authentication token, obtained with `HfApi.login` method. Will default to the stored token.

            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`.

            merge_pr (`bool`):
                If set to `True`, the Pull Request is merged at the end of the process. Defaults to `True`.

            num_threads (`int`, *optional*):
                Number of concurrent threads for uploading files. Defaults to 5.

            verbose (`bool`):
                If set to `True`, process will run on verbose mode i.e. print information about the ongoing tasks.
                Defaults to `False`.

        Returns:
            `str`: URL to the created PR.

        Example:
        ```python
        >>> from huggingface_hub import HfApi, plan_multi_commits
        >>> addition_commits, deletion_commits = plan_multi_commits(
        ...     operations=[
        ...          CommitOperationAdd(...),
        ...          CommitOperationAdd(...),
        ...          CommitOperationDelete(...),
        ...          CommitOperationDelete(...),
        ...          CommitOperationAdd(...),
        ...     ],
        ... )
        >>> HfApi().create_commits_on_pr(
        ...     repo_id="my-cool-model",
        ...     addition_commits=addition_commits,
        ...     deletion_commits=deletion_commits,
        ...     (...)
        ...     verbose=True,
        ... )
        ```

        Raises:
            [`MultiCommitException`]:
                If an unexpected issue occur in the process: empty commits, unexpected commits in a PR, unexpected PR
                description, etc.
        z.create_commits_on_prINFOzWill create z deletion commit(s) and z addition commit(s), totalling c                 s  s    | ]}t |V  qd S r   )r   )r  opsr   r   r   	<genexpr>q      z-HfApi.create_commits_on_pr.<locals>.<genexpr>z atomic operations.c                 S     g | ]}t |d qS rG  r.   r  rG  r   r   r   r  t      z.HfApi.create_commits_on_pr.<locals>.<listcomp>c                 S  r|  r}  r  r  r   r   r   r  u  r  )rt  rv  zMulti-commits strategy with ID r  r  Zdraft)r   discussion_numr   rc  zPR already exists: z'. Will resume process where it stopped.)r   r   r   strategyrc  r   zNew PR created: zPR #z must have at least 1 commentzCorrupted multi-commit PR #z: got z steps in description but z in strategy.z: expected step z but didn't find it (have r,  ).c                 S  s   h | ]}|j qS r   rM  r  rj  r   r   r   	<setcomp>  s    z-HfApi.create_commits_on_pr.<locals>.<setcomp>)r   r   rc  r  c                      g | ]	}|j  vr|qS r   r  r  Zcommits_on_main_branchr   r   r    s
    
r   zFound z existing commits on the PR.z: scheduled z steps but z, commits have already been pushed to the PR.c                 S     i | ]}|j |qS r   r   r  stepr   r   r   r'    r  z.HfApi.create_commits_on_pr.<locals>.<dictcomp>c                 S  r  r   r  r  r   r   r   r'    r  Tzj: some addition commits have already been pushed to the PR but deletion commits are not all completed yet.z commits remaining (z deletion commits and z addition commits)F)r   r   rc  r   r  rE  rG  rD  r   z  step z completed (still z to go).)r   r   r  )r   r   rc  r  
comment_idnew_contentzAll commits have been pushed.)r   r   rc  r  	new_titleopen)r   r   rc  r  
new_statuscommentzPR is now open for reviews.)r   r   rc  r  r  z>PR has been automatically merged (`merge_pr=True` was passed).Nzno associated changesclosed)r   r   rc  r  r  r  z-Couldn't merge the PR: no associated changes.)error_messagez-Couldn't merge Pull Request in multi-commit: )2rk   
get_loggerr   setLevelinfor   sumr/   r   get_repo_discussionsis_pull_requestr   r   get_discussion_detailsnumr   r0   eventsr  r9   r-   r2   rU  Z	all_stepsr3  r
  rB   Zgit_referencert  rv  r   	completedr_  r7  rL  rG  edit_discussion_commentr1   rename_discussionchange_discussion_statusr,   merge_pull_requestr+   rY   Zserver_messager*   r[  comment_discussionr)   format)r   r   rt  rv  r   r   rc  r   rr  rE  rs  r5  r  
discussionpreventZ
pr_commentZdescription_commitsZstep_idZ
pr_commitsZremaining_additionsZremaining_deletionsrj  r  Znb_remainingr]  r   r  r   create_commits_on_pr  sZ  h

	






"




	

zHfApi.create_commits_on_pr)rc  r   r  rD  rE  r_  gitignore_contentr^  Iterable[CommitOperationAdd]r_  r  c             
   C  s  |dur|nt }|tvrtdt |durt|ddnt}|dur%|nd}| j|d}
t|}|	du r[|D ]#}|jdkrZ| }|	 
 }		 W d    n	1 sUw   Y  q7dd	 |D }zt||||
|| j|pnd|	d
 W n ty } z|t  d}~ww dd	 |D }g }|D ]}|jrtd|j d q|| qt|t|krtdt|t|  d t||||
| j||s|ndd |D ]
}d|_|rd|_qdS )a  Pre-upload LFS files to S3 in preparation on a future commit.

        This method is useful if you are generating the files to upload on-the-fly and you don't want to store them
        in memory before uploading them all at once.

        <Tip warning={true}>

        This is a power-user method. You shouldn't need to call it directly to make a normal commit.
        Use [`create_commit`] directly instead.

        </Tip>

        <Tip warning={true}>

        Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be
        removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same
        objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the
        commit operation object, pass `free_memory=False`.

        </Tip>

        Args:
            repo_id (`str`):
                The repository in which you will commit the files, for example: `"username/custom_transformers"`.

            operations (`Iterable` of [`CommitOperationAdd`]):
                The list of files to upload. Warning: the objects in this list will be mutated to include information
                relative to the upload. Do not reuse the same objects for multiple commits.

            token (`str`, *optional*):
                Authentication token. Will default to the stored token.

            repo_type (`str`, *optional*):
                The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`).

            revision (`str`, *optional*):
                The git revision to commit from. Defaults to the head of the `"main"` branch.

            create_pr (`boolean`, *optional*):
                Whether or not you plan to create a Pull Request with that commit. Defaults to `False`.

            num_threads (`int`, *optional*):
                Number of concurrent threads for uploading files. Defaults to 5.
                Setting it to 2 means at most 2 files will be uploaded concurrently.

            gitignore_content (`str`, *optional*):
                The content of the `.gitignore` file to know which files should be ignored. The order of priority
                is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
                in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
                (if any).

        Example:
        ```py
        >>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo

        >>> repo_id = create_repo("test_preupload").repo_id

        # Generate and preupload LFS files one by one
        >>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
        >>> for i in range(5):
        ...     content = ... # generate binary content
        ...     addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
        ...     preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
        ...     operations.append(addition)

        # Create commit
        >>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")
        ```
        NrQ  r   r  Fro  z
.gitignorec                 S  s   g | ]}|j s|qS r   )_is_uploadedr  rq  r   r   r   r    r  z-HfApi.preupload_lfs_files.<locals>.<listcomp>)r^  r   r   rh  r  r   rD  r  c                 S  s   g | ]	}|j d kr|qS )r   )Z_upload_moder  r   r   r   r    r@  zSkipping upload for LFS file 'z' (ignored by gitignore file).zSkipped upload for z) LFS file(s) (ignored by gitignore file).)r^  r   r   rh  r   rE  r  Trh  )rH   rI   r   r   rB   rs  r_  r  rl  rm  rn  r#   r   r`   rA  rp  Z_should_ignorer5  r6  r  r   r  r%   r  path_or_fileobj)r   r   r^  rc  r   r  rD  rE  r_  r  rh  rq  r  Znew_additionsrv  Znew_lfs_additionsZnew_lfs_additions_to_uploadr   r   r   ro  .  sr   R

 



zHfApi.preupload_lfs_files)rc  r   r  r   r   rD  rF  rW  r  !Union[str, Path, bytes, BinaryIO]c                C  rJ  r   r   r   r  r  r   rc  r   r  r   r   rD  rF  rW  r   r   r   upload_file  rM  zHfApi.upload_filec                C  rJ  r   r   r  r   r   r   r    rM  c                C  s   |t vrtdt  |dur|nd| d}t||d}| j|||g|||||	|
d	}|jdur:tt|jdd}|tv rDt| | }|durJ|nt}t	|j
|j|j|j|j| j d	| d
| d	| dS )aT  
        Upload a local file (up to 50 GB) to the given repo. The upload is done
        through a HTTP post request, and doesn't require git or git-lfs to be
        installed.

        Args:
            path_or_fileobj (`str`, `Path`, `bytes`, or `IO`):
                Path to a file on the local machine or binary data stream /
                fileobj / buffer.
            path_in_repo (`str`):
                Relative filepath in the repo, for example:
                `"checkpoints/1fec34a/weights.bin"`
            repo_id (`str`):
                The repository to which the file will be uploaded, for example:
                `"username/custom_transformers"`
            token (`str`, *optional*):
                Authentication token, obtained with `HfApi.login` method. Will
                default to the stored token.
            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`.
            revision (`str`, *optional*):
                The git revision to commit from. Defaults to the head of the `"main"` branch.
            commit_message (`str`, *optional*):
                The summary / title / first line of the generated commit
            commit_description (`str` *optional*)
                The description of the generated commit
            create_pr (`boolean`, *optional*):
                Whether or not to create a Pull Request with that commit. Defaults to `False`.
                If `revision` is not set, PR is opened against the `"main"` branch. If
                `revision` is set and is a branch, PR is opened against this branch. If
                `revision` is set and is not a branch name (example: a commit oid), an
                `RevisionNotFoundError` is returned by the server.
            parent_commit (`str`, *optional*):
                The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
                If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
                If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
                Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
                especially useful if the repo is updated / committed to concurrently.
            run_as_future (`bool`, *optional*):
                Whether or not to run this method in the background. Background jobs are run sequentially without
                blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
                object. Defaults to `False`.


        Returns:
            [`CommitInfo`] or `Future`:
                Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
                url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
                contain the result when executed.
        <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.
            - [`~utils.RevisionNotFoundError`]
              If the revision to download from cannot be found.

        </Tip>

        <Tip warning={true}>

        `upload_file` assumes that the repo already exists on the Hub. If you get a
        Client error 404, please make sure you are authenticated and that `repo_id` and
        `repo_type` are set correctly. If repo does not exist, create it first using
        [`~hf_api.create_repo`].

        </Tip>

        Example:

        ```python
        >>> from huggingface_hub import upload_file

        >>> with open("./local/filepath", "rb") as fobj:
        ...     upload_file(
        ...         path_or_fileobj=fileobj,
        ...         path_in_repo="remote/file/path.h5",
        ...         repo_id="username/my-dataset",
        ...         repo_type="dataset",
        ...         token="my_token",
        ...     )
        "https://huggingface.co/datasets/username/my-dataset/blob/main/remote/file/path.h5"

        >>> upload_file(
        ...     path_or_fileobj=".\\local\\file\\path",
        ...     path_in_repo="remote/file/path.h5",
        ...     repo_id="username/my-model",
        ...     token="my_token",
        ... )
        "https://huggingface.co/username/my-model/blob/main/remote/file/path.h5"

        >>> upload_file(
        ...     path_or_fileobj=".\\local\\file\\path",
        ...     path_in_repo="remote/file/path.h5",
        ...     repo_id="username/my-model",
        ...     token="my_token",
        ...     create_pr=True,
        ... )
        "https://huggingface.co/username/my-model/blob/refs%2Fpr%2F1/remote/file/path.h5"
        ```
        rQ  NzUpload  with huggingface_hubr  r  )	r   r   rG  r   r   rc  r  rD  rF  r   r  r   z/blob/r   r   r   r   r   r   )rI   r   r   rL  r   r   r   rK   rB   r   r   r   r   r   r   )r   r  r  r   rc  r   r  r   r   rD  rF  rW  Z	operationcommit_infor   r   r   r    s@   ~
)r  r   r   rc  r   r  rD  rF  allow_patternsignore_patternsdelete_patternsmulti_commitsmulti_commits_verboserW  folder_pathUnion[str, Path]r  Optional[Union[List[str], str]]r  r  r  r  c                C  rJ  r   r   r   r   r  r  r   r   rc  r   r  rD  rF  r  r  r  r  r  rW  r   r   r   upload_folder     zHfApi.upload_folderc                C  rJ  r   r   r  r   r   r   r       c                C  rJ  r   r   r  r   r   r   r    r  Future[str]c                C  rJ  r   r   r  r   r   r   r    r  7Union[CommitInfo, str, Future[CommitInfo], Future[str]]c                  s  |t vrtdt  |r|dur|tkrtd|du rd}|du r&g }nt|tr.|g}|t7 }| j|||	r:tn||||d}t||||d}t|dkrat	dd	 |D   fd
d|D }|| }|phd}|rt
|d\}}| j||||||||	 |d	}|S | j||||||||	|
d	}|	r|jdurtt|jdd}|tv rt| | }|dur|nt}t|j|j|j|j|j| j d| d| d| dS )a!  
        Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or
        git-lfs to be installed.

        The structure of the folder will be preserved. Files with the same name already present in the repository will
        be overwritten. Others will be left untouched.

        Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters
        accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as
        documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and
        `ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded.

        Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for
        `allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths
        relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")`
        will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted
        even if it matches the patterns.

        Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore`
        file is not taken into account.

        Uses `HfApi.create_commit` under the hood.

        Args:
            repo_id (`str`):
                The repository to which the file will be uploaded, for example:
                `"username/custom_transformers"`
            folder_path (`str` or `Path`):
                Path to the folder to upload on the local file system
            path_in_repo (`str`, *optional*):
                Relative path of the directory in the repo, for example:
                `"checkpoints/1fec34a/results"`. Will default to the root folder of the repository.
            token (`str`, *optional*):
                Authentication token, obtained with `HfApi.login` method. Will
                default to the stored token.
            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`.
            revision (`str`, *optional*):
                The git revision to commit from. Defaults to the head of the `"main"` branch.
            commit_message (`str`, *optional*):
                The summary / title / first line of the generated commit. Defaults to:
                `f"Upload {path_in_repo} with huggingface_hub"`
            commit_description (`str` *optional*):
                The description of the generated commit
            create_pr (`boolean`, *optional*):
                Whether or not to create a Pull Request with that commit. Defaults to `False`. If `revision` is not
                set, PR is opened against the `"main"` branch. If `revision` is set and is a branch, PR is opened
                against this branch. If `revision` is set and is not a branch name (example: a commit oid), an
                `RevisionNotFoundError` is returned by the server. If both `multi_commits` and `create_pr` are True,
                the PR created in the multi-commit process is kept opened.
            parent_commit (`str`, *optional*):
                The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
                If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
                If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
                Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
                especially useful if the repo is updated / committed to concurrently.
            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.
            delete_patterns (`List[str]` or `str`, *optional*):
                If provided, remote files matching any of the patterns will be deleted from the repo while committing
                new files. This is useful if you don't know which files have already been uploaded.
                Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern.
            multi_commits (`bool`):
                If True, changes are pushed to a PR using a multi-commit process. Defaults to `False`.
            multi_commits_verbose (`bool`):
                If True and `multi_commits` is used, more information will be displayed to the user.
            run_as_future (`bool`, *optional*):
                Whether or not to run this method in the background. Background jobs are run sequentially without
                blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
                object. Defaults to `False`.

        Returns:
            [`CommitInfo`] or `Future`:
                Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
                url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
                contain the result when executed.
            [`str`] or `Future`:
                If `multi_commits=True`, returns the url of the PR created to push the changes. If `run_as_future=True`
                is passed, returns a Future object which will contain the result when executed.

        <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

        </Tip>

        <Tip warning={true}>

        `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make
        sure you are authenticated and that `repo_id` and `repo_type` are set correctly. If repo does not exist, create
        it first using [`~hf_api.create_repo`].

        </Tip>

        <Tip warning={true}>

        `multi_commits` is experimental. Its API and behavior is subject to change in the future without prior notice.

        </Tip>

        Example:

        ```python
        # Upload checkpoints folder except the log files
        >>> upload_folder(
        ...     folder_path="local/checkpoints",
        ...     path_in_repo="remote/experiment/checkpoints",
        ...     repo_id="username/my-dataset",
        ...     repo_type="datasets",
        ...     token="my_token",
        ...     ignore_patterns="**/logs/*.txt",
        ... )
        # "https://huggingface.co/datasets/username/my-dataset/tree/main/remote/experiment/checkpoints"

        # Upload checkpoints folder including logs while deleting existing logs from the repo
        # Useful if you don't know exactly which log files have already being pushed
        >>> upload_folder(
        ...     folder_path="local/checkpoints",
        ...     path_in_repo="remote/experiment/checkpoints",
        ...     repo_id="username/my-dataset",
        ...     repo_type="datasets",
        ...     token="my_token",
        ...     delete_patterns="**/logs/*.txt",
        ... )
        "https://huggingface.co/datasets/username/my-dataset/tree/main/remote/experiment/checkpoints"

        # Upload checkpoints folder while creating a PR
        >>> upload_folder(
        ...     folder_path="local/checkpoints",
        ...     path_in_repo="remote/experiment/checkpoints",
        ...     repo_id="username/my-dataset",
        ...     repo_type="datasets",
        ...     token="my_token",
        ...     create_pr=True,
        ... )
        "https://huggingface.co/datasets/username/my-dataset/tree/refs%2Fpr%2F1/remote/experiment/checkpoints"

        ```
        rQ  NzGCannot use `multi_commit` to commit changes other than the main branch.r   )r   r   r  rc  r  r  r  r  r   c                 s  s    | ]}|j V  qd S r   r  rS  r   r   r   rz    s    z&HfApi.upload_folder.<locals>.<genexpr>c                   r  r   r  )r  Z	delete_opZadded_pathsr   r   r    s    z'HfApi.upload_folder.<locals>.<listcomp>z#Upload folder using huggingface_hubr~  )	r   r   rt  rv  r   r   rc  rr  rs  )	r   r   rG  r   r   rc  r  rD  rF  r  r   r  r  )rI   r   rB   r  rz   rX    _prepare_upload_folder_deletions _prepare_upload_folder_additionsr   setr3   r  rL  r   r   r   rK   r   r   r   r   r   r   )r   r   r  r  r   r   rc  r   r  rD  rF  r  r  r  r  r  rW  Zdelete_operationsZadd_operationsZcommit_operationsrt  rv  r   r  r   r  r   r    s    +


)rc  r   r  r   r   rD  rF  c                C  s@   |dur|nd| d}t |dg}
| j||||
|||||	d	S )a  
        Deletes a file in the given repo.

        Args:
            path_in_repo (`str`):
                Relative filepath in the repo, for example:
                `"checkpoints/1fec34a/weights.bin"`
            repo_id (`str`):
                The repository from which the file will be deleted, for example:
                `"username/custom_transformers"`
            token (`str`, *optional*):
                Authentication token, obtained with `HfApi.login` method. Will
                default to the stored token.
            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 commit from. Defaults to the head of the `"main"` branch.
            commit_message (`str`, *optional*):
                The summary / title / first line of the generated commit. Defaults to
                `f"Delete {path_in_repo} with huggingface_hub"`.
            commit_description (`str` *optional*)
                The description of the generated commit
            create_pr (`boolean`, *optional*):
                Whether or not to create a Pull Request with that commit. Defaults to `False`.
                If `revision` is not set, PR is opened against the `"main"` branch. If
                `revision` is set and is a branch, PR is opened against this branch. If
                `revision` is set and is not a branch name (example: a commit oid), an
                `RevisionNotFoundError` is returned by the server.
            parent_commit (`str`, *optional*):
                The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
                If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
                If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
                Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
                especially useful if the repo is updated / committed to concurrently.


        <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.
            - [`~utils.RevisionNotFoundError`]
              If the revision to download from cannot be found.
            - [`~utils.EntryNotFoundError`]
              If the file to download cannot be found.

        </Tip>

        NzDelete r  r  	r   r   rc  rG  r  r   r   rD  rF  )r!   rL  )r   r  r   rc  r   r  r   r   rD  rF  rG  r   r   r   delete_file  s   GzHfApi.delete_filec          
      C  s:   | j |||t|ddg||dur|nd| d|||	d	S )a	  
        Deletes a folder in the given repo.

        Simple wrapper around [`create_commit`] method.

        Args:
            path_in_repo (`str`):
                Relative folder path in the repo, for example: `"checkpoints/1fec34a"`.
            repo_id (`str`):
                The repository from which the folder will be deleted, for example:
                `"username/custom_transformers"`
            token (`str`, *optional*):
                Authentication token, obtained with `HfApi.login` method. Will default
                to the stored token.
            repo_type (`str`, *optional*):
                Set to `"dataset"` or `"space"` if the folder is in a dataset or
                space, `None` or `"model"` if in a model. Default is `None`.
            revision (`str`, *optional*):
                The git revision to commit from. Defaults to the head of the `"main"` branch.
            commit_message (`str`, *optional*):
                The summary / title / first line of the generated commit. Defaults to
                `f"Delete folder {path_in_repo} with huggingface_hub"`.
            commit_description (`str` *optional*)
                The description of the generated commit.
            create_pr (`boolean`, *optional*):
                Whether or not to create a Pull Request with that commit. Defaults to `False`.
                If `revision` is not set, PR is opened against the `"main"` branch. If
                `revision` is set and is a branch, PR is opened against this branch. If
                `revision` is set and is not a branch name (example: a commit oid), an
                `RevisionNotFoundError` is returned by the server.
            parent_commit (`str`, *optional*):
                The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
                If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
                If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
                Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
                especially useful if the repo is updated / committed to concurrently.
        Tr  Z	is_folderNzDelete folder r  r  )rL  r!   )
r   r  r   rc  r   r  r   r   rD  rF  r   r   r   delete_folderB  s   3zHfApi.delete_folder)rc  proxiesr  r   Union[bool, str, None]r  r   rR   c             	   C  s*   |du r| j }t||||| j| j| jdS )a  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.

        Returns:
            A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash.
        N)r   rc  r  r  r   re  rf  )rc  rS   r   re  rf  )r   r   rc  r  r  r   r   r   rS     s   zHfApi.get_hf_file_metadataauto)	subfolderr   r  	cache_dir	local_dirlocal_dir_use_symlinksforce_downloadforce_filenamer  etag_timeoutresume_downloadrc  local_files_onlylegacy_cache_layoutr  r  Union[str, Path, None]r  r  Union[bool, Literal['auto']]r  r  r  floatr  Optional[Union[str, bool]]r  r  c                C  s   ddl m} |du r| j}|di d|d|d|d|d|d	| jd
| jd| jd|d|d|d| jd|	d|
d|d|d|d|d| jd|d|S )u  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.

        If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure
        how you want to move those files:
        - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob
            files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal
            is to be able to manually edit and save small files without corrupting the cache while saving disk space for
            binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD`
            environment variable.
        - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`.
            This is optimal in term of disk usage but files must not be manually edited.
        - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the
            local dir. This means disk usage is not optimized.
        - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the
            files are downloaded and directly placed under `local_dir`. This means if you need to download them again later,
            they will be re-downloaded entirely.

        ```
        [  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
        ```

        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.
            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, either as a symlink (default) or
                a regular file (see description for more details).
            local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`):
                To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either
                duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be
                created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if
                already exists) or downloaded from the Hub and not cached. See description for more details.
            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`.
            resume_download (`bool`, *optional*, defaults to `False`):
                If `True`, resume a previously interrupted download.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.
            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.
            legacy_cache_layout (`bool`, *optional*, defaults to `False`):
                If `True`, uses the legacy file cache layout i.e. just call [`hf_hub_url`]
                then `cached_download`. This is deprecated as the new cache layout is
                more powerful.

        Returns:
            Local path (string) of file or if networking is off, last version of
            file cached on disk.

        <Tip>

        Raises the following errors:

            - [`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
            - [`~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.

        </Tip>
        r   )hf_hub_downloadNr   r  r  r   r  r   r   re  r  r  r  rf  r  r  r  r  r  rc  rh  r  r  r   )file_downloadr  rc  r   r   re  rf  rh  )r   r   r  r  r   r  r  r  r  r  r  r  r  r  rc  r  r  r  r   r   r   r    s^    	
zHfApi.hf_hub_download   )r   r  r  r  r  r  r  r  r  rc  r  r  r  rm  
tqdm_classrm  r  Optional[base_tqdm]c                C  s   ddl m} |du r| j}|di d|d|d|d| jd|d	|d
|d| jd| jd| jd|d|d|	d|
d|d|d|d|d|d|S )a7  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. You can configure
        how you want to move those files:
        - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob
            files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal
            is to be able to manually edit and save small files without corrupting the cache while saving disk space for
            binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD`
            environment variable.
        - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`.
            This is optimal in term of disk usage but files must not be manually edited.
        - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the
            local dir. This means disk usage is not optimized.
        - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the
            files are downloaded and directly placed under `local_dir`. This means if you need to download them again later,
            they will be re-downloaded entirely.

        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, either as symlinks (default) or
                regular files (see description for more details).
            local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`):
                To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either
                duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be
                created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if
                already exists) or downloaded from the Hub and not cached. See description for more details.
            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`.
            resume_download (`bool`, *optional*, defaults to `False):
                If `True`, resume a previously interrupted download.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether the file should be downloaded even if it already exists in the local cache.
            token (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.
            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:
            Local folder path (string) of repo snapshot

        <Tip>

        Raises the following errors:

        - [`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

        </Tip>
        r   )snapshot_downloadNr   r   r  r   r  r  r  r   re  rf  r  r  r  r  rc  r  r  r  rm  r  r   )Z_snapshot_downloadr  rc  r   r   re  rf  )r   r   r   r  r  r  r  r  r  r  r  rc  r  r  r  rm  r  r  r   r   r   r  V  sX   q	
zHfApi.snapshot_downloadrd   c                  s  j tdr&jtd}tdddd |j D t|idS j tdrjtd}t|}t	
|}W d   n1 sNw   Y  |di }	i  d fdd}
t|
t|	 dtd t|ddd|	 dS td dt dt d)ur  
        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.

        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 (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
                machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
                retrieved from the cache. If `False`, token is not sent in the request header.

        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'}

            # 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

            # 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.
            ```
        r   r  r   r  rc  NFc                 S  s   i | ]}|t qS r   )rN   )r  Ztensor_namer   r   r   r'  3      z2HfApi.get_safetensors_metadata.<locals>.<dictcomp>)metadataZsharded
weight_mapr  r  r  rz   r}   r   c                   s   j | d | < d S )Nr  )parse_safetensors_file_metadata)r  r  r   r   r  r   rc  r   r   _parseE  s   
z.HfApi.get_safetensors_metadata.<locals>._parsezParse safetensors files)Zdescr  r  T'z,' is not a safetensors repo. Couldn't find 'z' or 'z' files.)r  rz   r}   r   )r  rN   r  rd   tensorskeysrL   r  r  rt  loadr  r   r  r7  hf_tqdmr_   )r   r   r   r  rc  Zfile_metadataZ
index_filer  indexr  r  r   r  r   get_safetensors_metadata  sN   F






zHfApi.get_safetensors_metadatarb   c                C  s  t ||||| jd}| j|d}t j|i |ddid}t| td|jdd d	 }	|	t	krIt
d
| d| d|p>t dt	 d|	 d|	dkrW|jdd|	  }
nt j|i |dd|	d  id}t| |j}
zt|
jdd}W n tjy } zt
d
| d| d|pt d|d}~ww zt|di dd | D dW S  ttfy } zt
d
| d| d|pt d|d}~ww )a  
        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`].

        For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.

        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 (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
                machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
                retrieved from the cache. If `False`, token is not sent in the request header.

        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.
        )r   r  r   r  r   ro  rangezbytes=0-100000rp  z<QNr  r   z(Failed to parse safetensors header for 'z	' (repo 'z', revision 'z='): safetensors header is too big. Maximum supported size is z bytes (got r  i zbytes=8-   ignore)r\  zg'): header is not json-encoded string. Please make sure this is a correctly formatted safetensors file.__metadata__c              	   S  s8   i | ]\}}|d kr|t |d |d t|d dqS )r  dtypeshapedata_offsets)r  r  r  )re   r  )r  r*  Ztensorr   r   r   r'    s    
z9HfApi.parse_safetensors_file_metadata.<locals>.<dictcomp>)r  r  zb'): header format not recognized. Please make sure this is a correctly formatted safetensors file.)rT   r   rs  ri   r  rj   structunpackrU  rM   rc   rB   rt  loadsrn  JSONDecodeErrorrb   r8  KeyError
IndexError)r   r   r  r   r  rc  r   _headersrr  Zmetadata_sizeZmetadata_as_bytesZmetadata_as_dictrv  r   r   r   r  ]  sf   (&
z%HfApi.parse_safetensors_file_metadata)r  rc  r   r  c             
   C  s   |du rt }t|dd}| j d| d| d| }| j|d}i }	|dur*||	d< t j|||	d	}
zt|
 W dS  tyV } z|jj	d
krJ|sK W Y d}~dS d}~ww )a  
        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.

            token (`str`, *optional*):
                Authentication token. Will default to the stored token.

            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.

        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`.
        Nr   r  r  r  /branch/ro  ZstartingPointr  r/  )
rH   r   r   rs  ri   r  rj   r]   rr  r4  )r   r   r  r  rc  r   r  
branch_urlrh  payloadrr  rv  r   r   r   create_branch  s"   0zHfApi.create_branchc                C  \   |du rt }t|dd}| j d| d| d| }| j|d}t j||d}t| dS )	a)  
        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 (`str`, *optional*):
                Authentication token. Will default to the stored token.

            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.

        Nr   r  r  r  r  ro  r  rH   r   r   rs  ri   r  rj   )r   r   r  rc  r   r  rh  rr  r   r   r   delete_branch  s   %zHfApi.delete_branch)tag_messager  rc  r   r  tagr  c             
   C  s   |du rt }|durt|ddnt}| j d| d| d| }| j|d}	d|i}
|dur2||
d	< t j||	|
d
}zt| W dS  ty^ } z|j	j
dkrR|sS W Y d}~dS d}~ww )a\  
        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.

            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 (`str`, *optional*):
                Authentication token. Will default to the stored token.

            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.

        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`.
        Nr   r  r  r  /tag/ro  r	  rO  r  r/  )rH   r   rB   r   rs  ri   r  rj   r]   rr  r4  )r   r   r	  r  r  rc  r   r  tag_urlrh  r  rr  rv  r   r   r   
create_tag5  s"   4zHfApi.create_tagc                C  r  )	a|  
        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.

            token (`str`, *optional*):
                Authentication token. Will default to the stored token.

            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.
        Nr   r  r  r  r
  ro  r  r  )r   r   r	  rc  r   r  rh  rr  r   r   r   
delete_tag|  s   "zHfApi.delete_tag)r  rc  model_idc                C  sL   |du rd|v r| dd }n| j|dd }| d| S | d| S )a  
        Returns the repository name for a given model ID and optional
        organization.

        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 (`bool` or `str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).
                If `None` or `True` and machine is logged in (through `huggingface-cli login`
                or [`~huggingface_hub.login`]), token will be retrieved from the cache.
                If `False`, token is not sent in the request header.

        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.
        Nr   r   ro  rD  )r   rw  )r   r  r  rc  r   r   r   r   get_full_repo_name  s   zHfApi.get_full_repo_name)r   discussion_typediscussion_statusr   rc  r  Optional[DiscussionTypeFilter]r   Optional[DiscussionStatusFilter]Iterator[Discussion]c                #  sX   |t vrtdt  |du rt}|dur!|tvr!tdt |dur0|tvr0tdt | j|d | j d| d| di |durL|d	< |durT|d
< |dur\|d< d fdd}d\}}	|r||	d\}
}|
D ]-}t|d |d |di ddt	|d |d
 |d d |d d	 |d | jd	V  qt|	d }	|skdS dS )a  
        Fetches Discussions and Pull Requests for the given repo.

        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
                space, `None` or `"model"` if fetching from a model. Default is
                `None`.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).

        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:

            ```python
            >>> from huggingface_hub import get_repo_discussions
            >>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
            ...     print(discussion.num, discussion.title)
            ```
        rQ  Nz(Invalid discussion_type, must be one of z*Invalid discussion_status, must be one of ro  r  r  /discussionsr2  r   r   
page_indexr   c                   sZ   | d< t  j d}t| | }|d }|d }|d }|t| |k }||fS )Npr  countstartdiscussions)ri   r  rj   rt  r   )r  respZpaginated_discussionsr   r  r  has_nextrh  r  r   r   r   _fetch_discussion_page  s   z:HfApi.get_repo_discussions.<locals>._fetch_discussion_page)Tr   )r  r   r  rD  deletedr  r  isPullRequest)	r   r  r   r   r   r   r   r  r   r   )r  r   )
rI   r   rH   rD   rC   rs  r   r8   r  rm   )r   r   r   r  r  r   rc  r  r  r  r  r  r   r  r   r    sH   8



zHfApi.get_repo_discussionsr  r<   c                C  s@  t |tr	|dkrtd|tvrtdt |du rt}| j d| d| d| }| j|d}t j|d	d
i|d}t	| |
 }|d }	|	rQ|d d nd}
|	rY|d nd}|	re|d ddnd}t|d |d |di ddt|d |d |d d |d d |d dd |d D ||
||d	| jdS )a8  Fetches a Discussion's / Pull Request 's details from the Hub.

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)

        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>
        r   2Invalid discussion_num, must be a positive integerrQ  Nr  r  /discussions/ro  diffri  r  r   changesbaseZfilesWithConflictsZmergeCommitIdr   r  r   rD  r  r  r   r  r2  c                 S  s   g | ]}t |qS r   )r=   )r  Zevtr   r   r   r  }  r  z0HfApi.get_discussion_details.<locals>.<listcomp>r  )r   r  r   r   r   r   r   r  r  conflicting_filestarget_branchmerge_commit_oidr#  r   )r  r   r   rI   rH   r   rs  ri   r  rj   rt  r<   rm   )r   r   r  r   rc  r   rh  r  Zdiscussion_detailsr  r'  r&  r(  r   r   r   r  9  s>   (


zHfApi.get_discussion_details)rc  r)  r   pull_requestr   r)  r)  c          
      C  s   |t vrtdt  |du rt}|dur| }|r|n|r!dnd d}| j|d}t j| j d| d| d	| ||d
|d}t| |	 d }	| j
|||	|dS )a  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`].

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)
            description (`str`, *optional*):
                An optional description for the Pull Request.
                Defaults to `"Discussion opened with the huggingface_hub Python library"`
            pull_request (`bool`, *optional*):
                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`.

        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>rQ  NzPull Requestr8   z^ opened with the [huggingface_hub Python library](https://huggingface.co/docs/huggingface_hub)ro  r  r  r  )r   r)  ZpullRequestrV  r  )r   r   r  rc  )rI   r   rH   striprs  ri   r  r   rj   rt  r  )
r   r   r   rc  r)  r   r)  rh  r  r  r   r   r   create_discussion  s6   5
	zHfApi.create_discussion)rc  r)  r   c                C  s   | j |||||ddS )a  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`].

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)
            description (`str`, *optional*):
                An optional description for the Pull Request.
                Defaults to `"Discussion opened with the huggingface_hub Python library"`
            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`.

        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>T)r   r   rc  r)  r   r)  )r+  )r   r   r   rc  r)  r   r   r   r   create_pull_request  s   1zHfApi.create_pull_request)bodyrc  r   resourcer-  Optional[dict]requests.Responsec          
      C  s   t |tr	|dkrtd|tvrtdt |du rt}| d| }| j d| d| d| }| j|d	}tj|||d
}	t	|	 |	S )z@Internal utility to POST changes to a Discussion or Pull Requestr   r!  rQ  Nr  r  r"  r   ro  r.  )
r  r   r   rI   rH   r   rs  requestsr  rj   )
r   r   r  r.  r-  rc  r   r   rh  r  r   r   r   _post_discussion_changes  s   zHfApi._post_discussion_changesr  r9   c                C  *   | j ||||dd|id}t| d S )a  Creates a new comment on the given Discussion.

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)

        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:

            - [`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>
        r  r   r   r  rc  r.  r-  Z
newMessager2  r=   rt  )r   r   r  r  rc  r   r  r   r   r   r  2  s   BzHfApi.comment_discussionr  r;   c                C  r3  )a  Renames a Discussion.

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)

        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:

            - [`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>
        r   r4  ZnewTitler5  )r   r   r  r  rc  r   r  r   r   r   r  ~  s   9zHfApi.rename_discussion)rc  r  r   r  Literal['open', 'closed']r:   c          	      C  sV   |dvrt dd|i}|r| r| |d< | j||||d|d}t| d S )a  Closes or re-opens a Discussion or Pull Request.

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)

        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:

            - [`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>
        )r  r  z7Invalid status, valid statuses are: 'open' and 'closed'r   r  r4  Z	newStatus)r   r*  r2  r=   rt  )	r   r   r  r  rc  r  r   r-  r  r   r   r   r    s   <zHfApi.change_discussion_statusc             	   C  s2   | j ||||d|r| rd| indd dS )a  Merges a Pull Request.

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)

        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>
        merger  Nr4  )r2  r*  )r   r   r  rc  r  r   r   r   r   r    s   ,
zHfApi.merge_pull_requestr  r  c                C  s6   | j ||||d|  dd|id}t| d S )a  Edits a comment on a Discussion / Pull Request.

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)

        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.

        </Tip>
        comment/z/editrU  r4  updatedComment)r2  lowerr=   rt  )r   r   r  r  r  rc  r   r  r   r   r   r  A  s   /zHfApi.edit_discussion_commentc                C  s<   t dt | j||||d|  dd}t| d S )a!  Hides a comment on a Discussion / Pull Request.

        <Tip warning={true}>
        Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.
        </Tip>

        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 (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token)

        Returns:
            [`DiscussionComment`]: the hidden 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.

        </Tip>
        zWHidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.r8  z/hide)r   r   r  rc  r.  r9  )r1  r2  UserWarningr2  r:  r=   rt  )r   r   r  r  rc  r   r  r   r   r   hide_discussion_commentz  s   0zHfApi.hide_discussion_comment)r)  rc  r*  rZ  c                C  sN   ||d}|dur||d< t  j| j d| d| j|d|d}t| dS )a  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.

        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 (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
        r*  rZ  Nr)  r  /secretsro  r.  )ri   r  r   rs  rj   r   r   r*  rZ  r)  rc  r  ru  r   r   r   add_space_secret  s   

zHfApi.add_space_secretc                C  s8   t  j| j d| d| j|dd|id}t| dS )a.  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.

        Args:
            repo_id (`str`):
                ID of the repo to update. Example: `"bigcode/in-the-stack"`.
            key (`str`):
                Secret key. Example: `"GITHUB_API_KEY"`.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
        r  r>  ro  r*  r.  N)ri   r  r   rs  rj   r   r   r*  rc  ru  r   r   r   delete_space_secret  s   
zHfApi.delete_space_secretDict[str, SpaceVariable]c                C  sD   t  j| j d| d| j|dd}t| dd |  D S )a  Gets all variables 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

        Args:
            repo_id (`str`):
                ID of the repo to query. Example: `"bigcode/in-the-stack"`.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
        r  
/variablesro  rp  c                 S     i | ]
\}}|t ||qS r   r7   r$  r   r   r   r'    r+  z-HfApi.get_space_variables.<locals>.<dictcomp>)ri   r  r   rs  rj   rt  r8  r   r   rc  ru  r   r   r   get_space_variables  s   
zHfApi.get_space_variablesc                C  s`   ||d}|dur||d< t  j| j d| d| j|d|d}t| dd	 |  D S )
a/  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

        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 (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
        r=  Nr)  r  rD  ro  r.  c                 S  rE  r   rF  r$  r   r   r   r'    r+  z,HfApi.add_space_variable.<locals>.<dictcomp>)ri   r  r   rs  rj   rt  r8  r?  r   r   r   add_space_variable   s   

zHfApi.add_space_variablec                C  sJ   t  j| j d| d| j|dd|id}t| dd |  D S )aK  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

        Args:
            repo_id (`str`):
                ID of the repo to update. Example: `"bigcode/in-the-stack"`.
            key (`str`):
                Variable key. Example: `"MODEL_REPO_ID"`
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
        r  rD  ro  r*  r.  c                 S  rE  r   rF  r$  r   r   r   r'  7  r+  z/HfApi.delete_space_variable.<locals>.<dictcomp>)ri   r  r   rs  rj   rt  r8  rA  r   r   r   delete_space_variable   s   
zHfApi.delete_space_variabler5   c                C  :   t  j| j d| d| j|dd}t| t| S )a  Gets runtime information about a Space.

        Args:
            repo_id (`str`):
                ID of the repo to update. Example: `"bigcode/in-the-stack"`.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if
                not provided.
        Returns:
            [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
        r  z/runtimero  rp  )ri   r  r   rs  rj   r5   rt  rG  r   r   r   get_space_runtime9  s
   zHfApi.get_space_runtime)rc  
sleep_timer  r4   rM  c                C  sr   |dur|t jkrtdt d|i}|dur||d< t j| j d| d| j|d|d}t	| t
| S )	ar  Request new hardware for a Space.

        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 (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
            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).
                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.

        <Tip>

        It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details.

        </Tip>
        N  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.Zflavorr   r  z	/hardwarero  r.  )r4   	CPU_BASICr1  r2  r;  ri   r  r   rs  rj   r5   rt  )r   r   r  rc  rM  r  ru  r   r   r   request_space_hardwareL  s    
zHfApi.request_space_hardwarec                C  sf   t  j| j d| d| j|dd|id}t| t| }|jp%|j}|t	j
kr1tdt |S )a  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.

        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 (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
        Returns:
            [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.

        <Tip>

        It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`].

        </Tip>
        r  z
/sleeptimero  secondsr.  rN  )ri   r  r   rs  rj   r5   rt  Zrequested_hardwarer  r4   rO  r1  r2  r;  )r   r   rM  rc  ru  r$  r  r   r   r   set_space_sleep_time~  s   

zHfApi.set_space_sleep_timec                C  rK  )a  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).

        Args:
            repo_id (`str`):
                ID of the Space to pause. Example: `"Salesforce/BLIP2"`.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.

        Returns:
            [`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware.

        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  /pausero  rp  ri   r  r   rs  rj   r5   rt  rG  r   r   r   pause_space  s
   zHfApi.pause_space)rc  factory_rebootrV  c                C  sL   i }|rd|d< t  j| j d| d| j|d|d}t| t| S )av  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).

        Args:
            repo_id (`str`):
                ID of the Space to restart. Example: `"Salesforce/BLIP2"`.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
            factory_reboot (`bool`, *optional*):
                If `True`, the Space will be rebuilt from scratch without caching any requirements.

        Returns:
            [`SpaceRuntime`]: Runtime information about your Space.

        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 restart it. If you want to restart 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.
        truefactoryr  z/restartro  r  rT  )r   r   rc  rV  r  ru  r   r   r   restart_space  s   "zHfApi.restart_space)r   rc  r  r  storagerM  r!  r"  rZ  r!  r"  c             
   C  s8  |durt |nd}|dur|jdur|jn| |d }|dur$|jnt |j}d| d| i}g d}|||||	|
g}|dd t||D  |durZ|tjkrZt	dt
 t j| j d	| d
| j|d|d}zt| W n ty } z|r|jjdkrn W Y d}~nd}~ww t | d | jdS )a5  Duplicate a Space.

        Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state
        as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space.

        Args:
            from_id (`str`):
                ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`.
            to_id (`str`, *optional*):
                ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same
                name as the original Space, but in your account.
            private (`bool`, *optional*):
                Whether the new Space should be private or not. Defaults to the same privacy as the original Space.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
            exist_ok (`bool`, *optional*, defaults to `False`):
                If `True`, do not raise an error if repo already exists.
            hardware (`SpaceHardware` or `str`, *optional*):
                Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list.
            storage (`SpaceStorage` or `str`, *optional*):
                Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
            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).
                See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
            secrets (`List[Dict[str, str]]`, *optional*):
                A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
                For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
            variables (`List[Dict[str, str]]`, *optional*):
                A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
                For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.

        Returns:
            [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
            attributes like `endpoint`, `repo_type` and `repo_id`.

        Raises:
            - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
              if the HuggingFace API returned an error
            - [`~utils.RepositoryNotFoundError`]
              If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
              or because it is set to `private` and you do not have access.

        Example:
        ```python
        >>> from huggingface_hub import duplicate_space

        # Duplicate a Space to your account
        >>> duplicate_space("multimodalart/dreambooth-training")
        RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)

        # Can set custom destination id and visibility flag.
        >>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", private=True)
        RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)
        ```
        NrD  
repositoryr   )r   r  r  r   r!  r"  c                 S  r#  r   r   r$  r   r   r   r'  S  r(  z)HfApi.duplicate_space.<locals>.<dictcomp>rN  r  z
/duplicatero  r.  r/  r   r0  )r   r   rw  r   r   rX  r4   rO  r1  r2  r;  ri   r  r   rs  rj   r   rr  r4  rt  )r   r?  r@  r   rc  r  r  rZ  rM  r!  r"  Zparsed_to_idZto_namespaceZto_repo_namer  r  r7  ru  r8  r   r   r   duplicate_space  s<   I
zHfApi.duplicate_spacer6   c                C  sD   d|i}t  j| j d| d| j|d|d}t| t| S )a  Request persistent storage for a Space.

        Args:
            repo_id (`str`):
                ID of the Space to update. Example: `"HuggingFaceH4/open_llm_leaderboard"`.
            storage (`str` or [`SpaceStorage`]):
               Storage tier. Either 'small', 'medium', or 'large'.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
        Returns:
            [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.

        <Tip>

        It is not possible to decrease persistent storage after its granted. To do so, you must delete it
        via [`delete_space_storage`].

        </Tip>
        Ztierr  /storagero  r.  rT  )r   r   rZ  rc  r  ru  r   r   r   request_space_storagen  s   
zHfApi.request_space_storagec                C  rK  )a  Delete persistent storage for a Space.

        Args:
            repo_id (`str`):
                ID of the Space to update. Example: `"HuggingFaceH4/open_llm_leaderboard"`.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.
        Returns:
            [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
        Raises:
            [`BadRequestError`]
                If space has no persistent storage.

        r  r]  ro  rp  )ri   r  r   rs  rj   r5   rt  rG  r   r   r   delete_space_storage  s   
zHfApi.delete_space_storager   List[InferenceEndpoint]c                  s    dkrK| j d}t| jdd}|dg D ]/}z|t|d d7 }W q tyH } z|jjdkr>td|d | W Y d	}~qd	}~ww |S  pR| jd t	 jt
 d
  | jdd}t|  fdd| d D S )a  Lists all inference endpoints for the given namespace.

        Args:
            namespace (`str`, *optional*):
                The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints
                from all namespaces (i.e. personal namespace and all orgs the user belongs to).
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).

        Returns:
            List[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace.

        Example:
        ```python
        >>> from huggingface_hub import HfApi
        >>> api = HfApi()
        >>> api.list_inference_endpoints()
        [InferenceEndpoint(name='my-endpoint', ...), ...]
        ```
        *ro  )r   ZorgsrD  r   rc  i  z0Cannot list Inference Endpoints for org '%s': %sN
/endpoint/rp  c                   s   g | ]
}t j| d qS )rb  )r'   from_raw)r  r   rb  r   r   r    s    z2HfApi.list_inference_endpoints.<locals>.<listcomp>r8  )rw  list_inference_endpoints_get_namespacer  r]   rr  r4  r5  r6  ri   rF   rs  rj   rt  )r   r   rc  rS  Z	endpointsorgr]  rr  r   rb  r   re    s,   

zHfApi.list_inference_endpointsr   r   )	
account_idmin_replicamax_replicar  r  custom_imager2  r   rc  r[  	frameworkacceleratorinstance_sizeinstance_typeregionvendorrh  ri  rj  rk  r2  r(   r'   c                C  s   |p| j |d}|durd|indi i}|	|||||
dd|||||d|||d|d	}t jt d
| | j|d|d}t| tj| ||dS )a*  Create a new Inference Endpoint.

        Args:
            name (`str`):
                The unique name for the new Inference Endpoint.
            repository (`str`):
                The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
            framework (`str`):
                The machine learning framework used for the model (e.g. `"custom"`).
            accelerator (`str`):
                The hardware accelerator to be used for inference (e.g. `"cpu"`).
            instance_size (`str`):
                The size or type of the instance to be used for hosting the model (e.g. `"large"`).
            instance_type (`str`):
                The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`).
            region (`str`):
                The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`).
            vendor (`str`):
                The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`).
            account_id (`str`, *optional*):
                The account ID used to link a VPC to a private Inference Endpoint (if applicable).
            min_replica (`int`, *optional*):
                The minimum number of replicas (instances) to keep running for the Inference Endpoint. Defaults to 0.
            max_replica (`int`, *optional*):
                The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.
            revision (`str`, *optional*):
                The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
            task (`str`, *optional*):
                The task on which to deploy the model (e.g. `"text-classification"`).
            custom_image (`Dict`, *optional*):
                A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
                Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
            type ([`InferenceEndpointType]`, *optional*):
                The type of the Inference Endpoint, which can be `"protected"` (default), `"public"` or `"private"`.
            namespace (`str`, *optional*):
                The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).

            Returns:
                [`InferenceEndpoint`]: information about the updated Inference Endpoint.

            Example:
            ```python
            >>> from huggingface_hub import HfApi
            >>> api = HfApi()
            >>> create_inference_endpoint(
            ...     "my-endpoint-name",
            ...     repository="gpt2",
            ...     framework="pytorch",
            ...     task="text-generation",
            ...     accelerator="cpu",
            ...     vendor="aws",
            ...     region="us-east-1",
            ...     type="protected",
            ...     instance_size="medium",
            ...     instance_type="c6i",
            ... )
            >>> endpoint
            InferenceEndpoint(name='my-endpoint-name', status="pending",...)

            # Run inference on the endpoint
            >>> endpoint.client.text_generation(...)
            "..."
            ```

            ```python
            # Start an Inference Endpoint running Zephyr-7b-beta on TGI
            >>> from huggingface_hub import HfApi
            >>> api = HfApi()
            >>> create_inference_endpoint(
            ...     "aws-zephyr-7b-beta-0486",
            ...     repository="HuggingFaceH4/zephyr-7b-beta",
            ...     framework="pytorch",
            ...     task="text-generation",
            ...     accelerator="gpu",
            ...     vendor="aws",
            ...     region="us-east-1",
            ...     type="protected",
            ...     instance_size="medium",
            ...     instance_type="g5.2xlarge",
            ...     custom_image={
            ...         "health_route": "/health",
            ...         "env": {
            ...             "MAX_BATCH_PREFILL_TOKENS": "2048",
            ...             "MAX_INPUT_LENGTH": "1024",
            ...             "MAX_TOTAL_TOKENS": "1512",
            ...             "MODEL_ID": "/repository"
            ...         },
            ...         "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
            ...     },
            ... )

            ```
        ro  NZcustomhuggingfaceZ
maxReplicaZ
minReplicarm  ZinstanceSizeZinstanceTypeZscalingrl  r[  r  r  image)rp  rq  )Z	accountIdcomputerv   rD  providerr2  rc  r.  rb  	rf  ri   r  rF   rs  rj   r'   rd  rt  )r   rD  r[  rl  rm  rn  ro  rp  rq  rh  ri  rj  r  r  rk  r2  r   rc  rv  r  rr  r   r   r   create_inference_endpoint  s:   t

zHfApi.create_inference_endpointrb  c                C  sT   |p| j |d}t jt d| d| | j|dd}t| tj| ||dS )a%  Get information about an Inference Endpoint.

        Args:
            name (`str`):
                The name of the Inference Endpoint to retrieve information about.
            namespace (`str`, *optional*):
                The namespace in which the Inference Endpoint is located. Defaults to the current user.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).

        Returns:
            [`InferenceEndpoint`]: information about the requested Inference Endpoint.

        Example:
        ```python
        >>> from huggingface_hub import HfApi
        >>> api = HfApi()
        >>> endpoint = api.get_inference_endpoint("my-text-to-image")
        >>> endpoint
        InferenceEndpoint(name='my-text-to-image', ...)

        # Get status
        >>> endpoint.status
        'running'
        >>> endpoint.url
        'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'

        # Run inference
        >>> endpoint.client.text_to_image(...)
        ```
        ro  rc  r   rp  rb  )	rf  ri   r  rF   rs  rj   r'   rd  rt  r   rD  r   rc  rr  r   r   r   get_inference_endpoint  s   "
zHfApi.get_inference_endpoint)rm  rn  ro  ri  rj  r[  rl  r  r  r   rc  c                C  s   |p| j |d}i }tdd |||||fD r$|||||dd|d< tdd |||	|
fD r=|||	|
di id	|d
< t jt d| d| | j|d|d}t| tj|	 ||dS )a6  Update an Inference Endpoint.

        This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
        optional but at least one must be provided.

        For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`].

        Args:
            name (`str`):
                The name of the Inference Endpoint to update.

            accelerator (`str`, *optional*):
                The hardware accelerator to be used for inference (e.g. `"cpu"`).
            instance_size (`str`, *optional*):
                The size or type of the instance to be used for hosting the model (e.g. `"large"`).
            instance_type (`str`, *optional*):
                The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`).
            min_replica (`int`, *optional*):
                The minimum number of replicas (instances) to keep running for the Inference Endpoint.
            max_replica (`int`, *optional*):
                The maximum number of replicas (instances) to scale to for the Inference Endpoint.

            repository (`str`, *optional*):
                The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
            framework (`str`, *optional*):
                The machine learning framework used for the model (e.g. `"custom"`).
            revision (`str`, *optional*):
                The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
            task (`str`, *optional*):
                The task on which to deploy the model (e.g. `"text-classification"`).

            namespace (`str`, *optional*):
                The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).

        Returns:
            [`InferenceEndpoint`]: information about the updated Inference Endpoint.
        ro  c                 s      | ]}|d uV  qd S r   r   r  rZ  r   r   r   rz    r{  z2HfApi.update_inference_endpoint.<locals>.<genexpr>rs  rt  rw  c                 s  r}  r   r   r~  r   r   r   rz    r{  rr  ru  rv   rc  r   r.  rb  )
rf  anyri   r=  rF   rs  rj   r'   rd  rt  )r   rD  rm  rn  ro  ri  rj  r[  rl  r  r  r   rc  r  rr  r   r   r   update_inference_endpoint  s0   :
	

zHfApi.update_inference_endpointc                C  sD   |p| j |d}t jt d| d| | j|dd}t| dS )a  Delete an Inference Endpoint.

        This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
        to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`].

        For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`].

        Args:
            name (`str`):
                The name of the Inference Endpoint to delete.
            namespace (`str`, *optional*):
                The namespace in which the Inference Endpoint is located. Defaults to the current user.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).
        ro  rc  r   rp  N)rf  ri   r  rF   rs  rj   r{  r   r   r   delete_inference_endpoint  s   
zHfApi.delete_inference_endpointc                C  V   |p| j |d}t jt d| d| d| j|dd}t| tj| ||dS )a  Pause an Inference Endpoint.

        A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`].
        This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which
        would be automatically restarted when a request is made to it.

        For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`].

        Args:
            name (`str`):
                The name of the Inference Endpoint to pause.
            namespace (`str`, *optional*):
                The namespace in which the Inference Endpoint is located. Defaults to the current user.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).

        Returns:
            [`InferenceEndpoint`]: information about the paused Inference Endpoint.
        ro  rc  r   rS  rp  rb  ry  r{  r   r   r   pause_inference_endpoint!     
zHfApi.pause_inference_endpointc                C  r  )ak  Resume an Inference Endpoint.

        For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`].

        Args:
            name (`str`):
                The name of the Inference Endpoint to resume.
            namespace (`str`, *optional*):
                The namespace in which the Inference Endpoint is located. Defaults to the current user.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).

        Returns:
            [`InferenceEndpoint`]: information about the resumed Inference Endpoint.
        ro  rc  r   z/resumerp  rb  ry  r{  r   r   r   resume_inference_endpointA  s   
zHfApi.resume_inference_endpointc                C  r  )a  Scale Inference Endpoint to zero.

        An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
        cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which
        would require a manual resume with [`resume_inference_endpoint`].

        For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`].

        Args:
            name (`str`):
                The name of the Inference Endpoint to scale to zero.
            namespace (`str`, *optional*):
                The namespace in which the Inference Endpoint is located. Defaults to the current user.
            token (`str`, *optional*):
                An authentication token (See https://huggingface.co/settings/token).

        Returns:
            [`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint.
        ro  rc  r   z/scale-to-zerorp  rb  ry  r{  r   r   r    scale_to_zero_inference_endpoint]  r  z&HfApi.scale_to_zero_inference_endpointc                 C  s(   | j |d}|d dkr|d S td)z/Get the default namespace for the current user.ro  r2  rS  rD  zfCannot determine default namespace. You must provide a 'namespace' as input or be logged in as a user.)rw  r   )r   rc  r  r   r   r   rf  }  s   zHfApi._get_namespace)r7  r?  r  r  rc  r7  r?  8Optional[Literal['lastModified', 'trending', 'upvotes']]Iterable[Collection]c                c  s    | j  d}| j|d}i }|dur|d|i |dur%|d|i |dur0|d|i |dur;|d|i t|||d}	|durKt|	|}	t|	D ]\}
}td
d	|
i|V  qOdS )aS  List collections on the Huggingface Hub, given some filters.

        <Tip warning={true}>

        When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items
        from a collection, you must use [`get_collection`].

        </Tip>

        Args:
            owner (`List[str]` or `str`, *optional*):
                Filter by owner's username.
            item (`List[str]` or `str`, *optional*):
                Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`.
            sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*):
                Sort collections by last modified, trending or upvotes.
            limit (`int`, *optional*):
                Maximum number of collections to be returned.
            token (`bool` or `str`, *optional*):
                An authentication token (see https://huggingface.co/settings/token).

        Returns:
            `Iterable[Collection]`: an iterable of [`Collection`] objects.
        /api/collectionsro  Nr7  r?  r  r  r  r/  r   )r   rs  r   rl   r
   	enumerater5  )r   r7  r?  r  r  rc  r   rh  r  r8  r/  Zcollection_datar   r   r   list_collections  s$   #
zHfApi.list_collectionscollection_slugr5  c                C  sL   t  j| j d| | j|dd}t| tdi i | d| jiS )a  Gets information about a Collection on the Hub.

        Args:
            collection_slug (`str`):
                Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.

        Returns: [`Collection`]

        Example:

        ```py
        >>> from huggingface_hub import get_collection
        >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
        >>> collection.title
        'Recent models'
        >>> len(collection.items)
        37
        >>> collection.items[0]
        CollectionItem(
            item_object_id='651446103cd773a050bf64c2',
            item_id='TheBloke/U-Amethyst-20B-AWQ',
            item_type='model',
            position=88,
            note=None
        )
        ```
        /api/collections/ro  rp  r   Nr   )ri   r  r   rs  rj   r5  rt  )r   r  rc  ru  r   r   r   get_collection  s
    zHfApi.get_collection)r   r)  r   	exists_okrc  r  c             
   C  s   |du r|  |d }|||d}|dur||d< t j| j d| j|d|d}zt| W n( tyX }	 z|rS|	jjdkrS|	 d	 }
| j
|
|dW  Y d}	~	S  d}	~	ww tdi i |	 d
| jiS )a  Create a new Collection on the Hub.

        Args:
            title (`str`):
                Title of the collection to create. Example: `"Recent models"`.
            namespace (`str`, *optional*):
                Namespace of the collection to create (username or org). Will default to the owner name.
            description (`str`, *optional*):
                Description of the collection to create.
            private (`bool`, *optional*):
                Whether the collection should be private or not. Defaults to `False` (i.e. public collection).
            exists_ok (`bool`, *optional*):
                If `True`, do not raise an error if collection already exists.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.

        Returns: [`Collection`]

        Example:

        ```py
        >>> from huggingface_hub import create_collection
        >>> collection = create_collection(
        ...     title="ICCV 2023",
        ...     description="Portfolio of models, papers and demos I presented at ICCV 2023",
        ... )
        >>> collection.slug
        "username/iccv-2023-64f9a55bb3115b4f513ec026"
        ```
        NrD  )r   r   r   r)  r  ro  r.  r/  r6  r   r   )rw  ri   r  r   rs  rj   r   rr  r4  rt  r  r5  )r   r   r   r)  r   r  rc  r  ru  r8  r6  r   r   r   create_collection  s*   ( zHfApi.create_collection)r   r)  r/  r   r:  rc  r/  r:  c          
      C  sp   |||||d}t  j| j d| | j|ddd | D d}	t|	 td
i i |	 d d| jiS )a-  Update metadata of a collection on the Hub.

        All arguments are optional. Only provided metadata will be updated.

        Args:
            collection_slug (`str`):
                Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
            title (`str`):
                Title of the collection to update.
            description (`str`, *optional*):
                Description of the collection to update.
            position (`int`, *optional*):
                New position of the collection in the list of collections of the user.
            private (`bool`, *optional*):
                Whether the collection should be private or not.
            theme (`str`, *optional*):
                Theme of the collection on the Hub.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.

        Returns: [`Collection`]

        Example:

        ```py
        >>> from huggingface_hub import update_collection_metadata
        >>> collection = update_collection_metadata(
        ...     collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
        ...     title="ICCV Oct. 2023"
        ...     description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
        ...     private=False,
        ...     theme="pink",
        ... )
        >>> collection.slug
        "username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
        # ^collection slug got updated but not the trailing ID
        ```
        )r/  r   r:  r   r)  r  ro  c                 S  r#  r   r   r)  r   r   r   r'  d  r(  z4HfApi.update_collection_metadata.<locals>.<dictcomp>r.  r  r   Nr   )ri   patchr   rs  r8  rj   r5  rt  )
r   r  r   r)  r/  r   r:  rc  r  ru  r   r   r   update_collection_metadata(  s   2
$z HfApi.update_collection_metadata)r:  rc  c             
   C  sl   t  j| j d| | j|dd}zt| W dS  ty5 } z|r0|jjdkr0W Y d}~dS  d}~ww )a(  Delete a collection on the Hub.

        Args:
            collection_slug (`str`):
                Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
            missing_ok (`bool`, *optional*):
                If `True`, do not raise an error if collection doesn't exists.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.

        Example:

        ```py
        >>> from huggingface_hub import delete_collection
        >>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)
        ```

        <Tip warning={true}>

        This is a non-revertible action. A deleted collection cannot be restored.

        </Tip>
        r  ro  rp    Nri   r  r   rs  rj   r   rr  r4  )r   r  r:  rc  ru  r8  r   r   r   delete_collectioni  s   zHfApi.delete_collection)r0  r  rc  r-  r.  r3  r0  c          
   
   C  s   d||di}|dur||d< t  j| j d| d| j|d|d}zt| W n" tyK }	 z|rF|	jjd	krF| j||dW  Y d}	~	S  d}	~	ww t	di i |
 d
| jiS )a}	  Add an item to a collection on the Hub.

        Args:
            collection_slug (`str`):
                Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
            item_id (`str`):
                ID of the item to add to the collection. It can be the ID of a repo on the Hub (e.g. `"facebook/bart-large-mnli"`)
                or a paper id (e.g. `"2307.09288"`).
            item_type (`str`):
                Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"` or `"paper"`.
            note (`str`, *optional*):
                A note to attach to the item in the collection. The maximum size for a note is 500 characters.
            exists_ok (`bool`, *optional*):
                If `True`, do not raise an error if item already exists.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.

        Returns: [`Collection`]

        Raises:
            `HTTPError`:
                HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
                or `admin` role in the organization the repo belongs to or if you passed a `read` token.
            `HTTPError`:
                HTTP 404 if the item you try to add to the collection does not exist on the Hub.
            `HTTPError`:
                HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False)

        Example:

        ```py
        >>> from huggingface_hub import add_collection_item
        >>> collection = add_collection_item(
        ...     collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
        ...     item_id="pierre-loic/climate-news-articles",
        ...     item_type="dataset"
        ... )
        >>> collection.items[-1].item_id
        "pierre-loic/climate-news-articles"
        # ^item got added to the collection on last position

        # Add item with a note
        >>> add_collection_item(
        ...     collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
        ...     item_id="datasets/climate_fever",
        ...     item_type="dataset"
        ...     note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
        ... )
        (...)
        ```
        r?  )r   r2  Nr0  r  z/itemsro  r.  r/  r   r   )ri   r  r   rs  rj   r   rr  r4  r  r5  rt  )
r   r  r-  r.  r0  r  rc  r  ru  r8  r   r   r   add_collection_item  s"   =
 zHfApi.add_collection_item)r0  r/  rc  r,  c                C  sP   ||d}t  j| j d| d| | j|ddd | D d}t| dS )	a  Update an item in a collection.

        Args:
            collection_slug (`str`):
                Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
            item_object_id (`str`):
                ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
                It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
            note (`str`, *optional*):
                A note to attach to the item in the collection. The maximum size for a note is 500 characters.
            position (`int`, *optional*):
                New position of the item in the collection.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.

        Example:

        ```py
        >>> from huggingface_hub import get_collection, update_collection_item

        # Get collection first
        >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")

        # Update item based on its ID (add note + update position)
        >>> update_collection_item(
        ...     collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
        ...     item_object_id=collection.items[-1].item_object_id,
        ...     note="Newly updated model!"
        ...     position=0,
        ... )
        ```
        )r/  r0  r  /items/ro  c                 S  r#  r   r   r)  r   r   r   r'    r(  z0HfApi.update_collection_item.<locals>.<dictcomp>r.  N)ri   r  r   rs  r8  rj   )r   r  r,  r0  r/  rc  r  ru  r   r   r   update_collection_item  s   
)
zHfApi.update_collection_itemc             
   C  sr   t  j| j d| d| | j|dd}zt| W dS  ty8 } z|r3|jjdkr3W Y d}~dS  d}~ww )a  Delete an item from a collection.

        Args:
            collection_slug (`str`):
                Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
            item_object_id (`str`):
                ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
                It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0]._id`.
            missing_ok (`bool`, *optional*):
                If `True`, do not raise an error if item doesn't exists.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if not provided.

        Example:

        ```py
        >>> from huggingface_hub import get_collection, delete_collection_item

        # Get collection first
        >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")

        # Delete item based on its ID
        >>> delete_collection_item(
        ...     collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
        ...     item_object_id=collection.items[-1].item_object_id,
        ... )
        ```
        r  r  ro  rp  r  Nr  )r   r  r,  r:  rc  ru  r8  r   r   r   delete_collection_item  s   $
zHfApi.delete_collection_itemList[AccessRequest]c                C     | j |d||dS )u  
        Get pending access requests for a given gated repo.

        A pending request means the user has requested access to the repo but the request has not been processed yet.
        If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected
        using [`accept_access_request`] and [`reject_access_request`].

        For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

        Args:
            repo_id (`str`):
                The id of the repo to get access requests for.
            repo_type (`str`, *optional*):
                The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
                Defaults to `model`.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).

        Returns:
            `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
            `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
            be populated with user's answers.

        Raises:
            `HTTPError`:
                HTTP 400 if the repo is not gated.
            `HTTPError`:
                HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
                or `admin` role in the organization the repo belongs to or if you passed a `read` token.

        Example:
        ```py
        >>> from huggingface_hub import list_pending_access_requests, accept_access_request

        # List pending requests
        >>> requests = list_pending_access_requests("meta-llama/Llama-2-7b")
        >>> len(requests)
        411
        >>> requests[0]
        [
            AccessRequest(
                username='clem',
                fullname='Clem 🤗',
                email='***',
                timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
                status='pending',
                fields=None,
            ),
            ...
        ]

        # Accept Clem's request
        >>> accept_access_request("meta-llama/Llama-2-7b", "clem")
        ```
        pendingr  _list_access_requestsr  r   r   r   list_pending_access_requestsE  s   ;z"HfApi.list_pending_access_requestsc                C  r  )uQ	  
        Get accepted access requests for a given gated repo.

        An accepted request means the user has requested access to the repo and the request has been accepted. The user
        can download any file of the repo. If the approval mode is automatic, this list should contains by default all
        requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and
        [`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will
        go to the rejected list. In both cases, the user will lose access to the repo.

        For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

        Args:
            repo_id (`str`):
                The id of the repo to get access requests for.
            repo_type (`str`, *optional*):
                The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
                Defaults to `model`.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).

        Returns:
            `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
            `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
            be populated with user's answers.

        Raises:
            `HTTPError`:
                HTTP 400 if the repo is not gated.
            `HTTPError`:
                HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
                or `admin` role in the organization the repo belongs to or if you passed a `read` token.

        Example:
        ```py
        >>> from huggingface_hub import list_accepted_access_requests

        >>> requests = list_accepted_access_requests("meta-llama/Llama-2-7b")
        >>> len(requests)
        411
        >>> requests[0]
        [
            AccessRequest(
                username='clem',
                fullname='Clem 🤗',
                email='***',
                timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
                status='accepted',
                fields=None,
            ),
            ...
        ]
        ```
        acceptedr  r  r  r   r   r   list_accepted_access_requests     9z#HfApi.list_accepted_access_requestsc                C  r  )u	  
        Get rejected access requests for a given gated repo.

        A rejected request means the user has requested access to the repo and the request has been explicitly rejected
        by a repo owner (either you or another user from your organization). The user cannot download any file of the
        repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and
        [`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will
        go to the accepted list.

        For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

        Args:
            repo_id (`str`):
                The id of the repo to get access requests for.
            repo_type (`str`, *optional*):
                The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
                Defaults to `model`.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).

        Returns:
            `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
            `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
            be populated with user's answers.

        Raises:
            `HTTPError`:
                HTTP 400 if the repo is not gated.
            `HTTPError`:
                HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
                or `admin` role in the organization the repo belongs to or if you passed a `read` token.

        Example:
        ```py
        >>> from huggingface_hub import list_rejected_access_requests

        >>> requests = list_rejected_access_requests("meta-llama/Llama-2-7b")
        >>> len(requests)
        411
        >>> requests[0]
        [
            AccessRequest(
                username='clem',
                fullname='Clem 🤗',
                email='***',
                timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
                status='rejected',
                fields=None,
            ),
            ...
        ]
        ```
        rejectedr  r  r  r   r   r   list_rejected_access_requests  r  z#HfApi.list_rejected_access_requestsr   *Literal['accepted', 'rejected', 'pending']c                 C  sj   |t vrtdt  |d u rt}t jt d| d| d| | j|dd}t| dd | D S )	NrQ  r  r  z/user-access-request/ro  rp  c                 S  sJ   g | ]!}t |d  d  |d  d |d  d |d t|d |ddqS )rS  r   r   r   r   r   )r   r   r   r   r   r   )r   rm   r  )r  rq  r   r   r   r  	   s    	



z/HfApi._list_access_requests.<locals>.<listcomp>)	rI   r   rH   ri   r  rE   rs  rj   rt  )r   r   r   r   rc  rr  r   r   r   r    s   
	zHfApi._list_access_requestsc                C     | j ||d||d dS )a  
        Cancel an access request from a user for a given gated repo.

        A cancelled request will go back to the pending list and the user will lose access to the repo.

        For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

        Args:
            repo_id (`str`):
                The id of the repo to cancel access request for.
            user (`str`):
                The username of the user which access request should be cancelled.
            repo_type (`str`, *optional*):
                The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`.
                Defaults to `model`.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).

        Raises:
            `HTTPError`:
                HTTP 400 if the repo is not gated.
            `HTTPError`:
                HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
                or `admin` role in the organization the repo belongs to or if you passed a `read` token.
            `HTTPError`:
                HTTP 404 if the user does not exist on the Hub.
            `HTTPError`:
                HTTP 404 if the user access request cannot be found.
            `HTTPError`:
                HTTP 404 if the user access request is already in the pending list.
        r  r  N_handle_access_requestr   r   rS  r   rc  r   r   r   cancel_access_request   s   #zHfApi.cancel_access_requestc                C  r  )a  
        Accept an access request from a user for a given gated repo.

        Once the request is accepted, the user will be able to download any file of the repo and access the community
        tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be
        cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`].

        For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

        Args:
            repo_id (`str`):
                The id of the repo to accept access request for.
            user (`str`):
                The username of the user which access request should be accepted.
            repo_type (`str`, *optional*):
                The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`.
                Defaults to `model`.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).

        Raises:
            `HTTPError`:
                HTTP 400 if the repo is not gated.
            `HTTPError`:
                HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
                or `admin` role in the organization the repo belongs to or if you passed a `read` token.
            `HTTPError`:
                HTTP 404 if the user does not exist on the Hub.
            `HTTPError`:
                HTTP 404 if the user access request cannot be found.
            `HTTPError`:
                HTTP 404 if the user access request is already in the accepted list.
        r  r  Nr  r  r   r   r   accept_access_request:      %zHfApi.accept_access_requestc                C  r  )a  
        Reject an access request from a user for a given gated repo.

        A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected
        requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`].
        A cancelled request will go back to the pending list while an accepted request will go to the accepted list.

        For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

        Args:
            repo_id (`str`):
                The id of the repo to reject access request for.
            user (`str`):
                The username of the user which access request should be rejected.
            repo_type (`str`, *optional*):
                The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
                Defaults to `model`.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).

        Raises:
            `HTTPError`:
                HTTP 400 if the repo is not gated.
            `HTTPError`:
                HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
                or `admin` role in the organization the repo belongs to or if you passed a `read` token.
            `HTTPError`:
                HTTP 404 if the user does not exist on the Hub.
            `HTTPError`:
                HTTP 404 if the user access request cannot be found.
            `HTTPError`:
                HTTP 404 if the user access request is already in the rejected list.
        r  r  Nr  r  r   r   r   reject_access_requesta   r  zHfApi.reject_access_requestc                 C  s`   |t vrtdt  |d u rt}t jt d| d| d| j|d||dd}t| d S )NrQ  r  r  z/user-access-request/handlero  )rS  r   r.  )rI   r   rH   ri   r  rE   rs  rj   )r   r   rS  r   r   rc  rr  r   r   r   r     s   	
zHfApi._handle_access_requestc                C  s\   |t vrtdt  |du rt}t jt d| d| j|dd|id}t| | S )a  
        Grant access to a user for a given gated repo.

        Granting access don't require for the user to send an access request by themselves. The user is automatically
        added to the accepted list meaning they can download the files You can revoke the granted access at any time
        using [`cancel_access_request`] or [`reject_access_request`].

        For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

        Args:
            repo_id (`str`):
                The id of the repo to grant access to.
            user (`str`):
                The username of the user to grant access.
            repo_type (`str`, *optional*):
                The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
                Defaults to `model`.
            token (`str`, *optional*):
                A valid authentication token (see https://huggingface.co/settings/token).

        Raises:
            `HTTPError`:
                HTTP 400 if the repo is not gated.
            `HTTPError`:
                HTTP 400 if the user already has access to the repo.
            `HTTPError`:
                HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
                or `admin` role in the organization the repo belongs to or if you passed a `read` token.
            `HTTPError`:
                HTTP 404 if the user does not exist on the Hub.
        rQ  Nr  z/user-access-request/grantro  rS  r.  )	rI   r   rH   ri   r  rE   rs  rj   rt  )r   r   rS  r   rc  rr  r   r   r   grant_access   s   #
zHfApi.grant_accessis_write_actionDict[str, str]c                 C  s6   |du r| j }t|||p| j|p| j|p| j| jdS )z
        Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client
        when `token` is not provided.
        N)rc  r  r   re  rf  rh  )rc  rf   r   re  rf  rh  )r   rc  r  r   re  rf  r   r   r   rs     s   zHfApi._build_hf_headersList[CommitOperationDelete]c                   sx   |du rg S | j ||||d} r& dvr& dd   fdd|D ndd |D fdd	t |d
D S )a  Generate the list of Delete operations for a commit to delete files from a repo.

        List remote files and match them against the `delete_patterns` constraints. Returns a list of [`CommitOperationDelete`]
        with the matching items.

        Note: `.gitattributes` file is essential to make a repo work properly on the Hub. This file will always be
              kept even if it matches the `delete_patterns` constraints.
        Nr  )r  z./r   c                   s(   i | ]}|  r|t d  |qS r   )r   r   r  r  r  r   r   r'  !  s
    
z:HfApi._prepare_upload_folder_deletions.<locals>.<dictcomp>c                 S  s   i | ]}||qS r   r   r  r   r   r   r'  !  r  c                   s(   g | ]} | d krt  | ddqS )z.gitattributesFr  )r!   r  relpath)relpath_to_abspathr   r   r  !  s
    z:HfApi._prepare_upload_folder_deletions.<locals>.<listcomp>)r  )r  r*  rh   r  )r   r   r   r  rc  r  r  	filenamesr   )r  r  r   r     s   

z&HfApi._prepare_upload_folder_deletions)NNNNNN)r   r|   rc  rd  r   r|   re  r|   rf  rg  rh  ri  r}   r   )rV  rk  r}   rl  r   )rc  r|   r}   r   )rc  r|   r}   rx  )r}   r   )&r  r  r   r|   r  r  r  r  r  r|   r  r  r  r  r  r  r  r|   r  r  r  r  r  r  r  r   r  r   r  r   r  r   rc  r  r   r|   r}   r  )r  rs   )"r  r  r   r|   r  r  r  r|   r  r  r  r  r  r  r  r  r  r  r  r  r  r|   r  r  r  r  r  r   r  r   rc  r|   r}   r  )r  rr   )r}   r  )r  r  r   r|   r  r|   r  r  r  r  r  r   r&  r  r%  r  r  r   r  r   rc  r|   r}   r  )r   rz   rc  r|   r   r|   r}   r   )rS  r|   rc  r|   r}   rR  )r   rz   r   r|   rc  r|   r}   r  )r   rz   r  r|   r  r  r  r   r  r   rc  r  r}   r   )r   rz   r  r|   r  r  r  r   rc  r  r}   r  )r   rz   r  r|   r  r  r  r   rc  r  r}   r   )r   rz   r  r|   r   r|   r  r  r  r   rc  r  r}   r  )r   rz   r   r|   rc  r|   r}   r   )
r   rz   r  rz   r   r|   rc  r|   r}   r   )r   rz   r  rz   r   r|   r  r|   rc  rd  r}   r   )r   rz   r  r  r  r   r  r|   r   r|   rc  r  r}   r  )
r   rz   r  r|   r   r|   rc  r  r}   r   )r   rz   r  r|   r  r   r  r   r  r|   r   r|   rc  r  r}   r  )
r   rz   r   r|   r   r   rc  r  r}   rH  )r   rz   r   r|   rc  r  r  r|   r  r   r}   r	  )r   rz   r  r  r  r   r  r|   r   r|   rc  r  r}   r  )r   rz   r  r|   r   r|   r   r|   rc  r|   r}   r   )r   rz   rc  r|   r   r   r   r|   r  r   r  r|   r  r  r  r  r  r   r  r  r  r  r}   r   )
r   rz   rc  r|   r   r|   r:  r   r}   r   )F)r   rz   r   r   rc  r|   r  r|   r   r|   rD  r|   r}   r<  )r?  rz   r@  rz   r   r|   rc  r|   )r   rz   rG  rH  r   rz   r   r|   rc  r|   r   r|   r  r|   rD  r   rE  r   rF  r|   rW  rI  r}   r   )r   rz   rG  rH  r   rz   r   r|   rc  r|   r   r|   r  r|   rD  r   rE  r   rF  r|   rW  rN  r}   rO  )r   rz   rG  rH  r   rz   r   r|   rc  r|   r   r|   r  r|   rD  r   rE  r   rF  r|   rW  r   r}   rP  )r   rz   rt  ru  rv  rw  r   rz   r   r|   rc  r|   r   r|   rr  r   rE  r   rs  r   r}   rz   )r   rz   r^  r  rc  r|   r   r|   r  r|   rD  r   rE  r   r_  r   r  r|   )r  r  r  rz   r   rz   rc  r|   r   r|   r  r|   r   r|   r   r|   rD  r   rF  r|   rW  rI  r}   r   )r  r  r  rz   r   rz   rc  r|   r   r|   r  r|   r   r|   r   r|   rD  r   rF  r|   rW  rN  r}   rO  )r  r  r  rz   r   rz   rc  r|   r   r|   r  r|   r   r|   r   r|   rD  r   rF  r|   rW  r   r}   rP  )"r   rz   r  r  r  r|   r   r|   r   r|   rc  r|   r   r|   r  r|   rD  r   rF  r|   r  r  r  r  r  r  r  rI  r  r   rW  rI  r}   r   )"r   rz   r  r  r  r|   r   r|   r   r|   rc  r|   r   r|   r  r|   rD  r   rF  r|   r  r  r  r  r  r  r  rN  r  r   rW  rI  r}   rz   )"r   rz   r  r  r  r|   r   r|   r   r|   rc  r|   r   r|   r  r|   rD  r   rF  r|   r  r  r  r  r  r  r  rI  r  r   rW  rN  r}   rO  )"r   rz   r  r  r  r|   r   r|   r   r|   rc  r|   r   r|   r  r|   rD  r   rF  r|   r  r  r  r  r  r  r  rN  r  r   rW  rN  r}   r  )"r   rz   r  r  r  r|   r   r|   r   r|   rc  r|   r   r|   r  r|   rD  r   rF  r|   r  r  r  r  r  r  r  r   r  r   rW  r   r}   r  )r  rz   r   rz   rc  r|   r   r|   r  r|   r   r|   r   r|   rD  r   rF  r|   r}   r   )
r   rz   rc  r  r  r   r  r  r}   rR   )"r   rz   r  rz   r  r|   r   r|   r  r|   r  r  r  r  r  r  r  r   r  r|   r  r   r  r  r  r   rc  r  r  r   r  r   r}   rz   )"r   rz   r   r|   r  r|   r  r  r  r  r  r  r  r   r  r  r  r   r  r   rc  r  r  r   r  r  r  r  rm  r   r  r  r}   rz   )
r   rz   r   r|   r  r|   rc  r|   r}   rd   )r   rz   r  rz   r   r|   r  r|   rc  r|   r}   rb   )r   rz   r  rz   r  r|   rc  r|   r   r|   r  r   r}   r   )
r   rz   r  rz   rc  r|   r   r|   r}   r   )r   rz   r	  rz   r  r|   r  r|   rc  r|   r   r|   r  r   r}   r   )
r   rz   r	  rz   rc  r|   r   r|   r}   r   )r  rz   r  r|   rc  r  )r   rz   r   r|   r  r  r  r  r   r|   rc  r|   r}   r  )
r   rz   r  r   r   r|   rc  r|   r}   r<   )r   rz   r   rz   rc  r|   r)  r|   r   r|   r)  r   r}   r<   )r   rz   r   rz   rc  r|   r)  r|   r   r|   r}   r<   )r   rz   r  r   r.  rz   r-  r/  rc  r|   r   r|   r}   r0  )r   rz   r  r   r  rz   rc  r|   r   r|   r}   r9   )r   rz   r  r   r  rz   rc  r|   r   r|   r}   r;   )r   rz   r  r   r  r6  rc  r|   r  r|   r   r|   r}   r:   )
r   rz   r  r   rc  r|   r  r|   r   r|   )r   rz   r  r   r  rz   r  rz   rc  r|   r   r|   r}   r9   )r   rz   r  r   r  rz   rc  r|   r   r|   r}   r9   )r   rz   r*  rz   rZ  rz   r)  r|   rc  r|   r}   r   )r   rz   r*  rz   rc  r|   r}   r   )r   rz   rc  r|   r}   rC  )r   rz   r*  rz   rZ  rz   r)  r|   rc  r|   r}   rC  )r   rz   r*  rz   rc  r|   r}   rC  )r   rz   rc  r|   r}   r5   )
r   rz   r  r4   rc  r|   rM  r   r}   r5   )r   rz   rM  r   rc  r|   r}   r5   )r   rz   rc  r|   rV  r   r}   r5   )r?  rz   r@  r|   r   r   rc  r|   r  r   r  r  rZ  r  rM  r   r!  r  r"  r  r}   r   )r   rz   rZ  r6   rc  r|   r}   r5   )r   r|   rc  r|   r}   r`  )$rD  rz   r[  rz   rl  rz   rm  rz   rn  rz   ro  rz   rp  rz   rq  rz   rh  r|   ri  r   rj  r   r  r|   r  r|   rk  r   r2  r(   r   r|   rc  r|   r}   r'   )rD  rz   r   r|   rc  r|   r}   r'   )rD  rz   rm  r|   rn  r|   ro  r|   ri  r   rj  r   r[  r|   rl  r|   r  r|   r  r|   r   r|   rc  r|   r}   r'   )rD  rz   r   r|   rc  r|   r}   r   )rc  r|   r}   rz   )r7  r  r?  r  r  r  r  r   rc  r  r}   r  )r  rz   rc  r|   r}   r5  )r   rz   r   r|   r)  r|   r   r   r  r   rc  r|   r}   r5  )r  rz   r   r|   r)  r|   r/  r   r   r   r:  r|   rc  r|   r}   r5  )r  rz   r:  r   rc  r|   r}   r   )r  rz   r-  rz   r.  r3  r0  r|   r  r   rc  r|   r}   r5  )r  rz   r,  rz   r0  r|   r/  r   rc  r|   r}   r   )
r  rz   r,  rz   r:  r   rc  r|   r}   r   )r   rz   r   r|   rc  r|   r}   r  r   )
r   rz   r   r  r   r|   rc  r|   r}   r  )
r   rz   rS  rz   r   r|   rc  r|   r}   r   )r   rz   rS  rz   r   r  r   r|   rc  r|   r}   r   )NFNNN)rc  r  r  r   r   r|   re  r|   rf  rg  r}   r  )r   rz   r   r|   r  r|   rc  r|   r  rz   r  r  r}   r  )tr   r   r   r   rW  rn   rw  rz  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rp   r  r  r  r  r
  r  r  r9  r;  ro   r>  rB  r   rL  ra  rg   r  ro  r  r  r  r  rA   rS   r@   r  r  r  r  r  r  r  r  r  r  r  r+  r,  r2  r  r  r  r  r  r<  r@  rB  rH  rI  rJ  rL  rP  rR  rU  rY  r\  r^  r_  re  r(   Z	PROTECTEDrz  r|  r  r  r  r  r  rf  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rs  r  r   r   r   r   rb    s6   )(		 @1 1)V/.J1C>>C+.9
 7# GUKT .@> z  1  %  W@) ) ~dB0F-%hKX?KBJ48<1-#*r# B 1Z! 7(EB,T75<:>$&&5rb  r  r  r  r  r  r  List[CommitOperationAdd]c                   s~   t       std  d fddt dD |r,|d dndfdd	t	 ||d
D S )zGenerate the list of Add operations for a commit to upload a folder.

    Files not matching the `allow_patterns` (allowlist) and `ignore_patterns` (denylist)
    constraints are discarded.
    zProvided path: 'z' is not a directoryc                   s$   i | ]}|  r|  |qS r   )is_filerelative_toas_posix)r  r   )r  r   r   r'  "!  s    z4_prepare_upload_folder_additions.<locals>.<dictcomp>z**/*r   r   c                   s    g | ]}t |  | d qS )r  )r   r  )prefixr  r   r   r  +!  s    z4_prepare_upload_folder_additions.<locals>.<listcomp>r  )
r   
expanduserresolveis_dirr   sortedglobr*  rh   r  )r  r  r  r  r   )r  r  r  r   r  !  s   

r  r   c                 C  s2   t t| }|du rtd|  dd|d  S )zSafely parse revision number from a PR url.

    Example:
    ```py
    >>> _parse_revision_from_pr_url("https://huggingface.co/bigscience/bloom/discussions/2")
    "refs/pr/2"
    ```
    NzHUnexpected response from the hub, expected a Pull Request URL but got: 'r  zrefs/pr/r   )r   match_REGEX_DISCUSSION_URLRuntimeError)r   re_matchr   r   r   r   6!  s   	r   r   )ry   rz   r{   r|   r}   r~   )rV  rq   r}   rq   r   )
r  r  r  rz   r  r  r  r  r}   r  )r   rz   r}   rz   (  
__future__r   r]  rt  r   r  r1  concurrent.futuresr   r   dataclassesr   r   r   r   	functoolsr	   	itertoolsr
   pathlibr   typingr   r   r   r   r   r   r   r   r   r   r   r   r   urllib.parser   r1  Zrequests.exceptionsr   Z	tqdm.autor   Z	base_tqdmZtqdm.contrib.concurrentr   Z_commit_apir   r   r    r!   r"   r#   r$   r%   r&   Z_inference_endpointsr'   r(   Z_multi_commitsr)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   Z
_space_apir4   r5   r6   r7   Z	communityr8   r9   r:   r;   r<   r=   	constantsr>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   r  rR   rS   rT   Zrepocard_datarU   rV   rW   utilsrX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   r  Zutils._deprecationro   rp   Zutils._typingrq   Zutils.endpoint_helpersrr   rs   rt   ru   r3  ZUSERNAME_PLACEHOLDERcompiler  rp  r  r   r5  r   r  r   r   r   r   r   rz   r   r   r   r   r   r   r   r  r   r'  r+  r5  rC  rH  rL  rR  rT  ra  rb  r  r   apirw  rz  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  r~  r  rL  r9  r;  r>  r  rB  r  r  r  r  r  ro  r  r  r  r  r  r  r  rW  r  r  r  r  r  r  r+  r,  r  r  r  r  r  r@  rB  rH  rI  rJ  rL  rP  rR  rU  rY  r\  r^  r_  re  rz  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   <module>   s  <,4 Xd

[			E<"6 j}"> 
!                                                        t
$

















