U
    +-e                    @  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Zd dlm	Z	m
Z
 d dl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"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-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZI ddlJmKZKmLZLmMZMmNZN ddlOmPZPmQZQmRZRmSZSmTZTmUZU ddlVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^ ddl_m`Z`maZa ddlbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZl ddlmmnZn ddlompZp ddlqmrZrmsZsmtZtmuZumvZvmwZw e!dZxdZyezdZ{ei|e}Z~G dd dZdQddd d!d"d#ZG d$d% d%e d&d'ZeG d(d) d)ZG d*d+ d+eZG d,d- d-eZG d.d/ d/eZG d0d1 d1eZG d2d3 d3eZG d4d5 d5eZG d6d7 d7erZG d8d9 d9erZeG d:d; d;ZeG d<d= d=ZeG d>d? d?ZeG d@dA dAZdBdBdCdDdEZG dFdG dGZdRdHddIdIdJdKdLdMZdddNdOdPZe ZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZdS )S    )annotationsN)FutureThreadPoolExecutor)	dataclassfield)datetime)wraps)islice)Path)AnyBinaryIOCallableDictIterableIteratorListLiteralOptionalTuple	TypedDictTypeVarUnionoverload)quote)	HTTPError)tqdm)IGNORE_GIT_FOLDER_PATTERNSEntryNotFoundErrorLocalTokenNotFoundErrorRepositoryNotFoundErrorRevisionNotFoundErrorexperimentalget_session   )	CommitOperationCommitOperationAddCommitOperationCopyCommitOperationDeletefetch_lfs_files_to_copyfetch_upload_modesprepare_commit_payloadupload_lfs_fileswarn_on_overwriting_operations):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)DEFAULT_REVISIONENDPOINTREGEX_COMMIT_OIDREPO_TYPE_MODEL
REPO_TYPESREPO_TYPES_MAPPINGREPO_TYPES_URL_PREFIXESSPACES_SDK_TYPES)get_hf_file_metadata
hf_hub_url)
BadRequestErrorHfFolderHfHubHTTPErrorbuild_hf_headersfilter_repo_objectshf_raise_for_statusloggingpaginateparse_datetimevalidate_hf_hub_args)_deprecate_arguments)	CallableT)AttributeDictionaryDatasetFilterDatasetTagsModelFilter	ModelTags_filter_emissionsRZhf_userz.*/discussions/(\d+)$c                   @  s   e Zd ZdZdd ZdS )	ReprMixinz(Mixin to create the __repr__ for a classc                 C  sL   t j| jddd}d|kr6| jj dt|d dS | jj d| S d S )	Nw   T)widthcompact
z: { 
z  z
}z: )pprintpformat__dict__	__class____name__textwrapindent)selfZformatted_value rl   W/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/huggingface_hub/hf_api.py__repr__   s    zReprMixin.__repr__N)rh   
__module____qualname____doc__rn   rl   rl   rl   rm   r_      s   r_   strOptional[str]z(Tuple[Optional[str], Optional[str], str])hf_idhub_urlreturnc           
      C  s  | }t dd|dk	r|nt}|| ko,d| k}d}| |rL| t|d } | d}t|dk}|r|dd \}}||krd}t|d	kr||d
 kr|d
 }	n|tkrt| }	d}nd}	n|rPt|dkr|d
d \}	}}nht|d	kr>|d tkr"t|d  }	d}| dd }n| ddd \}}d}	n|d }d\}}	ntd|  |	tkrpt|	 }	|	dkr~d}	|	tk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subrC   
startswithlensplitrG   
ValueErrorrF   )
rt   ru   Zinput_hf_idZ	is_hf_urlZHFFS_PREFIXZurl_segmentsZis_hf_id	namespacerepo_id	repo_typerl   rl   rm   repo_type_and_id_from_hf_id   sL    






r   c                   @  s&   e Zd ZU ded< ded< ded< dS )BlobLfsInfointsizerr   sha256pointer_sizeN)rh   ro   rp   __annotations__rl   rl   rl   rm   r      s   
r   F)totalc                   @  sj   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< dd Z	dS )
CommitInfoaK  Data structure containing information about a newly created commit.

    Returned by [`create_commit`].

    Args:
        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`.
    rr   
commit_urlcommit_messagecommit_descriptionoidNrs   pr_urlF)initpr_revisionpr_numc                 C  s>   | j dk	r.t| j | _t| jdd | _nd| _d| _dS )zPopulate pr-related fields after initialization.

        See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing.
        Nry   r~   )r   _parse_revision_from_pr_urlr   r   r   r   rk   rl   rl   rm   __post_init__   s
    
zCommitInfo.__post_init__)
rh   ro   rp   rq   r   r   r   r   r   r   rl   rl   rl   rm   r      s   
r   c                      sP   e Zd ZdZdddd fddZddddd	 fd
dZd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.
    Nr   rs   )urlendpointc                   s   t t| | |S N)superr   __new__)clsr   r   rg   rl   rm   r   U  s    zRepoUrl.__new__None)r   r   rv   c                   sh   t    |pt| _t| | jd\}}}|| _|| _|d kr@|n| d| | _|pVt| _	t
| | _d S )N)ru   ry   )r   __init__rC   r   r   r   	repo_namer   rE   r   rr   r   )rk   r   r   r   r   r   r   rl   rm   r   X  s    


zRepoUrl.__init__rr   rv   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   rl   rl   rm   rn   e  s    zRepoUrl.__repr__)N)N)rh   ro   rp   rq   r   r   rn   __classcell__rl   rl   r   rm   r   -  s   'r   c                   @  s&   e Zd ZdZd
ddddddd	ZdS )RepoFilea  
    Data structure that represents a public file inside a repo, accessible from huggingface.co

    Args:
        rfilename (str):
            file name, relative to the repo root. This is the only attribute that's guaranteed to be here, but under
            certain conditions there can certain other stuff.
        size (`int`, *optional*):
            The file's size, in bytes. This attribute is present 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 present 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 present when`files_metadata` argument of [`repo_info`] is set to
            `True` and the file is stored with Git LFS. It's `None` otherwise.
    Nrr   Optional[int]rs   zOptional[BlobLfsInfo]	rfilenamer   blobIdlfsc                 K  s:   || _ || _|| _|| _| D ]\}}t| || q d S r   )r   r   Zblob_idr   itemssetattr)rk   r   r   r   r   kwargskvrl   rl   rm   r   |  s    zRepoFile.__init__)NNNrh   ro   rp   rq   r   rl   rl   rl   rm   r   i  s
      r   c                   @  sP   e Zd ZdZdd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 ZdS )	ModelInfoaC  
    Info about a model accessible from huggingface.co

    Attributes:
        modelId (`str`, *optional*):
            ID of model repository.
        sha (`str`, *optional*):
            repo sha at this particular revision
        lastModified (`str`, *optional*):
            date of last commit to repo
        tags (`List[str]`, *optional*):
            List of tags.
        pipeline_tag (`str`, *optional*):
            Pipeline tag to identify the correct widget.
        siblings (`List[RepoFile]`, *optional*):
            list of ([`huggingface_hub.hf_api.RepoFile`]) objects that constitute the model.
        private (`bool`, *optional*, defaults to `False`):
            is the repo private
        author (`str`, *optional*):
            repo author
        config (`Dict`, *optional*):
            Model configuration information
        securityStatus (`Dict`, *optional*):
            Security status of the model.
            Example: `{"containsInfected": False}`
        kwargs (`Dict`, *optional*):
            Kwargs that will be become attributes of the class.
    NF)
modelIdshalastModifiedtagspipeline_tagsiblingsprivateauthorconfigsecurityStatusrs   Optional[List[str]]Optional[List[Dict]]boolOptional[Dict]c       
         K  st   || _ || _|| _|| _|| _|d k	r4dd |D ng | _|| _|| _|	| _|
| _	|
 D ]\}}t| || qZd S )Nc                 S  s   g | ]}t f |qS rl   r   .0xrl   rl   rm   
<listcomp>  s     z&ModelInfo.__init__.<locals>.<listcomp>)r   r   r   r   r   r   r   r   r   r   r   r   )rk   r   r   r   r   r   r   r   r   r   r   r   r   r   rl   rl   rm   r     s    zModelInfo.__init__c                 C  s.   d| j  d| j }| jr*|d| j 7 }|S )NzModel Name: , Tags: z, Task: )r   r   r   rk   rrl   rl   rm   __str__  s    zModelInfo.__str__rh   ro   rp   rq   r   r   rl   rl   rl   rm   r     s    $r   c                   @  sP   e Zd ZdZdd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 ZdS )DatasetInfoa  
    Info about a dataset accessible from huggingface.co

    Attributes:
        id (`str`, *optional*):
            ID of dataset repository.
        sha (`str`, *optional*):
            repo sha at this particular revision
        lastModified (`str`, *optional*):
            date of last commit to repo
        tags (`List[str]`, *optional*):
            List of tags.
        siblings (`List[RepoFile]`, *optional*):
            list of [`huggingface_hub.hf_api.RepoFile`] objects that constitute the dataset.
        private (`bool`, *optional*, defaults to `False`):
            is the repo private
        author (`str`, *optional*):
            repo author
        description (`str`, *optional*):
            Description of the dataset
        citation (`str`, *optional*):
            Dataset citation
        cardData (`Dict`, *optional*):
            Metadata of the model card as a dictionary.
        kwargs (`Dict`, *optional*):
            Kwargs that will be become attributes of the class.
    NF)
idr   r   r   r   r   r   descriptioncitationcardDatars   r   r   r   Optional[dict]c       
         K  s   || _ || _|| _|| _|| _|| _|| _|	| _|
| _|d k	rLdd |D ng | _	|
dd  | D ]\}}t| || qfd S )Nc                 S  s   g | ]}t f |qS rl   r   r   rl   rl   rm   r     s     z(DatasetInfo.__init__.<locals>.<listcomp>key)r   r   r   r   r   r   r   r   r   r   popr   r   )rk   r   r   r   r   r   r   r   r   r   r   r   r   r   rl   rl   rm   r     s    zDatasetInfo.__init__c                 C  s   d| j  d| j }|S )NzDataset Name: r   )r   r   r   rl   rl   rm   r     s    zDatasetInfo.__str__r   rl   rl   rl   rm   r     s   $ r   c                   @  s8   e Zd ZdZdddddddddddddddd	ZdS )
	SpaceInfoa  
    Info about a Space accessible from huggingface.co

    This is a "dataclass" like container that just sets on itself any attribute
    passed by the server.

    Attributes:
        id (`str`, *optional*):
            id of space
        sha (`str`, *optional*):
            repo sha at this particular revision
        lastModified (`str`, *optional*):
            date of last commit to repo
        siblings (`List[RepoFile]`, *optional*):
            list of [`huggingface_hub.hf_api.RepoFIle`] objects that constitute the Space
        private (`bool`, *optional*, defaults to `False`):
            is the repo private
        author (`str`, *optional*):
            repo author
        kwargs (`Dict`, *optional*):
            Kwargs that will be become attributes of the class.
    NF)r   r   r   r   r   r   rs   r   r   c          
      K  s\   || _ || _|| _|d k	r(dd |D ng | _|| _|| _| D ]\}}	t| ||	 qBd S )Nc                 S  s   g | ]}t f |qS rl   r   r   rl   rl   rm   r   :  s     z&SpaceInfo.__init__.<locals>.<listcomp>)r   r   r   r   r   r   r   r   )
rk   r   r   r   r   r   r   r   r   r   rl   rl   rm   r   ,  s    zSpaceInfo.__init__r   rl   rl   rl   rm   r     s   r   c                   @  s4   e Zd ZdZddddddddddZdd ZdS )	
MetricInfozC
    Info about a public metric accessible from huggingface.co
    N)r   r   r   rs   c                K  s@   || _ || _|| _|dd  | D ]\}}t| || q&d S )Nr   )r   r   r   r   r   r   )rk   r   r   r   r   r   r   rl   rl   rm   r   F  s    zMetricInfo.__init__c                 C  s   d| j  }|S )NzMetric Name: r   r   rl   rl   rm   r   X  s    zMetricInfo.__str__r   rl   rl   rl   rm   r   A  s   r   c                      s0   e Zd ZdZd	dd fddZdd Z  ZS )
ModelSearchArgumentsa  
    A nested namespace object holding all possible values for properties of
    models currently hosted in the Hub with tab-completion. If a value starts
    with a number, it will only exist in the dictionary

    Example:

    ```python
    >>> args = ModelSearchArguments()

    >>> args.author.huggingface
    'huggingface'

    >>> args.language.en
    'en'
    ```

    <Tip warning={true}>

    `ModelSearchArguments` is a legacy class meant for exploratory purposes only. Its
    initialization requires listing all models on the Hub which makes it increasingly
    slower as the number of repos on the Hub increases.

    </Tip>
    NOptional['HfApi']apic                   s6   |d k	r|nt  | _| j }t | |   d S r   )HfApi_apiget_model_tagsr   r   _process_modelsrk   r   r   r   rl   rm   r   x  s    
zModelSearchArguments.__init__c                 C  s   ddddd}| j  }t t  }}|D ]>}d|jkrX|jd\}}||||< n|j}||||< q,|| d< || d< d S )Nrr   )srv   c                 S  s   |  dd dd ddS N rw   -_.replacer   rl   rl   rm   clean  s    z3ModelSearchArguments._process_models.<locals>.cleanry   
model_namer   )r   list_modelsrX   r   r   )rk   r   modelsauthor_dictZmodel_name_dictmodelr   namerl   rl   rm   r   ~  s    

z$ModelSearchArguments._process_models)Nrh   ro   rp   rq   r   r   r   rl   rl   r   rm   r   ]  s   r   c                      s0   e Zd ZdZd	dd fddZdd Z  ZS )
DatasetSearchArgumentsa  
    A nested namespace object holding all possible values for properties of
    datasets currently hosted in the Hub with tab-completion. If a value starts
    with a number, it will only exist in the dictionary

    Example:

    ```python
    >>> args = DatasetSearchArguments()

    >>> args.author.huggingface
    'huggingface'

    >>> args.language.en
    'language:en'
    ```

    <Tip warning={true}>

    `DatasetSearchArguments` is a legacy class meant for exploratory purposes only. Its
    initialization requires listing all datasets on the Hub which makes it increasingly
    slower as the number of repos on the Hub increases.

    </Tip>
    Nr   r   c                   s6   |d k	r|nt  | _| j }t | |   d S r   )r   r   get_dataset_tagsr   r   r   r   r   rl   rm   r     s    
zDatasetSearchArguments.__init__c                 C  s~   dddd}| j  }t t  }}|D ]>}d|jkrV|jd\}}||||< n|j}||||< q*|| d< || d< d S )Nrr   r   c                 S  s   |  dd dd ddS r   r   r   rl   rl   rm   r     s    z5DatasetSearchArguments._process_models.<locals>.cleanry   dataset_namer   )r   list_datasetsrX   r   r   )rk   r   datasetsr   Zdataset_name_dictdatasetr   r   rl   rl   rm   r     s    

z&DatasetSearchArguments._process_models)Nr   rl   rl   r   rm   r     s   r   c                   @  s:   e Zd ZU dZded< ded< ded< dddd	d
ZdS )
GitRefInfoa  
    Contains information about a git reference for a repo on the Hub.

    Args:
        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"`)
    rr   r   reftarget_commitr   r   datarv   c                 C  s"   |d | _ |d | _|d | _d S )Nr   r   ZtargetCommit)r   r   r   rk   r   rl   rl   rm   r     s    

zGitRefInfo.__init__Nrh   ro   rp   rq   r   r   rl   rl   rl   rm   r     s
   
r   c                   @  s*   e Zd ZU dZded< ded< ded< dS )GitRefsa_  
    Contains information about all git references for a repo on the Hub.

    Object is returned by [`list_repo_refs`].

    Args:
        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.
    zList[GitRefInfo]branchesconvertsr   Nrh   ro   rp   rq   r   rl   rl   rl   rm   r    s   
r  c                   @  sZ   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ddddZdS )GitCommitInfoao  
    Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details.

    Args:
        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.
    rr   	commit_id	List[str]authorsr   
created_attitlemessagers   formatted_titleformatted_messager   r   r   c                 C  sl   |d | _ dd |d D | _t|d | _|d | _|d | _|di d| _|di d| _d S )	Nr   c                 S  s   g | ]}|d  qS )userrl   )r   r   rl   rl   rm   r     s     z*GitCommitInfo.__init__.<locals>.<listcomp>r  dater
  r  	formatted)	r  r  rT   r	  r
  r  getr  r  r   rl   rl   rm   r     s    


zGitCommitInfo.__init__Nr   rl   rl   rl   rm   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
S )	UserLikesa  
    Contains information about a user likes on the Hub.

    Args:
        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).
    rr   r  r   r   r  r   r   spacesNr  rl   rl   rl   rm   r    s   
r  rW   fnrv   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                   sj   d|kr|d }d|d< n(d}t  |D ]\}}|dkr(|} qBq(|rZ| j| f||S | f||S )Nrun_as_futureF)zipr  )rk   argsr   r  paramvalueZargs_paramsr  rl   rm   _inner?  s    
z!future_compatible.<locals>._innerT)inspect	signaturelist
parametersr   Zis_future_compatible)r  sigr  rl   r  rm   future_compatible6  s    
r"  c                   @  s  e Zd ZdCdddddddddZdd	d
ddZedDdddddZdEdddddZddddZd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#d$d%d&d'd(Z
d)d*d+d,Zeddddddddd-d.dddd d!d"dd/d0	d1d2Zd3d4d5d6Zd7dd8d9Zedddddddddddd:d;dddd d!d;d;d#d"dd<d=d>d?Zeddd@dAddddBdCdDZeddd@dAddddBdEdFZedFddGdddHdIdJdKZeddddddLdAddMd"d#d$dNdOdPdQZedddddRdAddMd#d$dSdTdUdVZedddddRdAddMd#d$dWdTdXdYZeddddddZdAdddMd#d$d[d\d]d^Zeddd_dAddd#d`dadbZeddddcdAdAdddd#dddedfZedGdddddgdAdhd#ddd$didjdkdlZedmdngdodpedddddqdAdddMd$drdsdtduZeddd_dAdd$dvd`dwdxZedddddydAdd$dd#dzd{d|d}Zeddddd~dAddddddddZeddddddddddd
dAdd#dd#dddd!ddddddZedddddAddd#ddddZ edHddddddAd#ddddddddZ!ddd_dAdAdddddZ"e#ddddddddddAddAddddd"dddddddZ$e#ddddddddddAddAddddd"dddddddZ$ee%ddddddddddAddAddddd"ddd#ddddZ$e&eddddddddAdddAdddd#dd#dAdddZ'e#dddddddddddAdAdddddd"dddAdddZ(e#dddddddddddAdAdddddd"ddddddZ(ee%dddddddddddAdAdddddd"dd#ddddZ(e#ddddddddddddddddAdddddddd"ddddd#d#ddAdddZ)e#ddddddddddddddddAdddddddd"ddddd#d#dddddZ)ee%ddddddddddddddddAdddddddd"ddddd#d#d#ddddZ)edddddddddAdAdddddd"ddd
ddZ*edddddddddAdAdddddd"ddd
ddZ+eddddddddddddddŜdAdAddddddd#dddd#d#d#dAdʜdd̄Z,edddddddddddddddΜdAdddddddd#d#d#dddddAdМdd҄Z-edddddӜdAdAdddd#ddԜddքZ.eddd@dAdAddddלddلZ/eddddddڜdAdAddddd#ddۜdd݄Z0eddd@dAdAddddޜddZ1eddddAdd$dddZ2eddd_dAdddd`ddZ3eddd_dAdddddddZ4eddddddAdAdddd#ddddZ5edddddAdAdddddddZ6dddddAddAdddddddZ7eddd@dAddAddddddZ8eddd@dAddAddddd dZ9edddddAdddddddddZ:edddddAdddddd	d
Z;eddd@dAddAdAddddddZ<eddd@dAddAddddddZ=eddddAdAdAddddddZ>eddGdAdAdddddZ?eddGdAdddddZ@eddddAdAdAddddddZAeddGdAdAdddddZBeddGdAdd dd!d"ZCeddd#dAd$dd!d d%d&d'ZDeddGdAddd d(d)d*ZEeddGdAdd dd+d,ZFeddd-dAdd#d d.d/d0ZGedIddddddddd1dAdd"dd#ddd!dddd2d3d4ZHeddGdAd5dd d6d7d8ZIeddGdAdd dd9d:ZJdJd$d#dddd;d<d=d>ZKdAddddAdd?d@dAdBZLdS (K  r   Nrs   zUnion[Dict, str, None]r   )r   tokenlibrary_namelibrary_version
user_agentrv   c                 C  s4   |dk	r|nt | _|| _|| _|| _|| _d| _dS )aW  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:
            endpoint (`str`, *optional*):
                Hugging Face Hub base url. Will default to https://huggingface.co/. Otherwise,
                one can set the `HF_ENDPOINT` environment variable.
            token (`str`, *optional*):
                Hugging Face token. Will default to the locally saved token if
                not provided.
            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.
        N)rC   r   r#  r$  r%  r&  _thread_pool)rk   r   r#  r$  r%  r&  rl   rl   rm   r   X  s     zHfApi.__init__zCallable[..., R]z	Future[R]r  c                 O  s0   | j dkrtdd| _ | j  | j j|f||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)r'  r   submit)rk   r  r  r   rl   rl   rm   r    s    #
zHfApi.run_as_futurer   )r#  rv   c              
   C  sl   t  j| j d| j|p | jp ddd}zt| W n, tk
rb } ztd|W 5 d}~X Y nX | S )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r#  headerszInvalid 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.N)r"   r  r   _build_hf_headersr#  rQ   r   json)rk   r#  r   erl   rl   rm   whoami  s    

zHfApi.whoamiz Literal[('read', 'write', None)]c              	   C  s:   z| j |dd d d W S  ttfk
r4   Y dS X dS )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.
        r*  authZaccessTokenZroleN)r0  r   r   )rk   r#  rl   rl   rm   get_token_permission  s    zHfApi.get_token_permissionr\   r   c                 C  s0   | j  d}t |}t| | }t|S )zH
        List all valid model tags as a nested namespace object
        z/api/models-tags-by-type)r   r"   r  rQ   r.  r\   rk   pathr   drl   rl   rm   r     s
    zHfApi.get_model_tagsrZ   c                 C  s0   | j  d}t |}t| | }t|S )zK
        List all valid dataset tags as a nested namespace object.
        z/api/datasets-tags-by-type)r   r"   r  rQ   r.  rZ   r3  rl   rl   rm   r     s
    zHfApi.get_dataset_tagsF)filterr   searchemissions_thresholdssort	directionlimitfullr   fetch_configr#  z,Union[ModelFilter, str, Iterable[str], None]zOptional[Tuple[float, float]]z)Union[Literal['lastModified'], str, None]zOptional[Literal[-1]]r   zOptional[bool]r   zOptional[Union[bool, str]]zIterable[ModelInfo])r6  r   r7  r8  r9  r:  r;  r<  r   r=  r#  rv   c                c  s  |dk	r|	dkrt d| j d}| j|d}i }|dk	rnt|trR| |}n|d|i |ddi |dk	r|d|i |dk	r|d	|i |dk	r|d
|i |dk	r|d|i |dk	r|d|i |dk	r
|r|ddi nd|kr
|d= |
r|ddi |	r2|ddi t|||d}|dk	rTt||}|dk	rlt	|f| }|D ]}t
f |V  qpdS )a3  
        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
            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["lastModified"]` 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 `lastModified`,
                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.

        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()

        >>> # Get all valid search arguments
        >>> args = ModelSearchArguments()

        >>> # List only the text classification models
        >>> api.list_models(filter="text-classification")
        >>> # Using the `ModelFilter`
        >>> filt = ModelFilter(task="text-classification")
        >>> # With `ModelSearchArguments`
        >>> filt = ModelFilter(task=args.pipeline_tags.TextClassification)
        >>> api.list_models(filter=filt)

        >>> # Using `ModelFilter` and `ModelSearchArguments` to find text classification in both PyTorch and TensorFlow
        >>> filt = ModelFilter(
        ...     task=args.pipeline_tags.TextClassification,
        ...     library=[args.library.PyTorch, args.library.TensorFlow],
        ... )
        >>> api.list_models(filter=filt)

        >>> # List only models from the AllenNLP library
        >>> api.list_models(filter="allennlp")
        >>> # Using `ModelFilter` and `ModelSearchArguments`
        >>> filt = ModelFilter(library=args.library.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/modelsr*  r6  r<  Tr   r7  r9  r:  r;  r   r   paramsr,  )r   r   r-  
isinstancer[   _unpack_model_filterupdaterS   r	   r]   r   )rk   r6  r   r7  r8  r9  r:  r;  r<  r   r=  r#  r4  r,  r?  r   itemrl   rl   rm   r     sH    l





zHfApi.list_modelsr[   )model_filterc                 C  sj  d}g }|j dk	r|j  d}|jdk	r2||j7 }g }|jdk	r`|t|jtrX|jgn|j |jdk	rt|jttfs|jg|_|jD ] }d|krd| }|	| q|j
r|t|j
tr|j
gn|j
 |jr|t|jtr|jgn|j i }|dk	r||d< t|dkr$||d< t|jtr@||j nt|jtrZ|	|j t||d< |S )	zU
        Unpacks a [`ModelFilter`] into something readable for `list_models`
        rw   Nry   zdataset:r7  r   r   r6  )r   r   taskextendr@  rr   Ztrained_datasetr  tupleappendZlibraryr   r   language)rk   rD  Z	model_strr   filter_listr   
query_dictrl   rl   rm   rA    sB    



 



 
zHfApi._unpack_model_filter)r6  r   r7  r9  r:  r;  r<  r#  z.Union[DatasetFilter, str, Iterable[str], None]zIterable[DatasetInfo])	r6  r   r7  r9  r:  r;  r<  r#  rv   c                c  s  | j  d}	| j|d}
i }|dk	rHt|tr:| |}n|d|i |dk	r^|d|i |dk	rt|d|i |dk	r|d|i |dk	r|d|i |dk	r|d	|i |r|d
di t|	||
d}|dk	rt||}|D ]}tf |V  qdS )a  
        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.
            search (`str`, *optional*):
                A string that will be contained in the returned datasets.
            sort (`Literal["lastModified"]` 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 `lastModified`
                and the `cardData`. 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()

        >>> # Get all valid search arguments
        >>> args = DatasetSearchArguments()

        >>> # List only the text classification datasets
        >>> api.list_datasets(filter="task_categories:text-classification")
        >>> # Using the `DatasetFilter`
        >>> filt = DatasetFilter(task_categories="text-classification")
        >>> # With `DatasetSearchArguments`
        >>> filt = DatasetFilter(task=args.task_categories.text_classification)
        >>> api.list_models(filter=filt)

        >>> # List only the datasets in russian for language modeling
        >>> api.list_datasets(
        ...     filter=("language:ru", "task_ids:language-modeling")
        ... )
        >>> # Using the `DatasetFilter`
        >>> filt = DatasetFilter(language="ru", task_ids="language-modeling")
        >>> # With `DatasetSearchArguments`
        >>> filt = DatasetFilter(
        ...     language=args.language.ru,
        ...     task_ids=args.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/datasetsr*  Nr6  r   r7  r9  r:  r;  r<  Tr>  )	r   r-  r@  rY   _unpack_dataset_filterrB  rS   r	   r   )rk   r6  r   r7  r9  r:  r;  r<  r#  r4  r,  r?  r   rC  rl   rl   rm   r     s0    _

zHfApi.list_datasetsrY   )dataset_filterc           	      C  s   d}|j dk	r|j  d}|jdk	r.||j7 }g }dddddd	d
g}|D ]Z}t||}|dk	rHt|ttfsr|g}|D ]*}| d|kr| d| }|| qvqHi }|dk	r||d< t||d< |S )zY
        Unpacks a [`DatasetFilter`] into something readable for `list_datasets`
        rw   Nry   Z	benchmarkZlanguage_creatorsrI  ZmultilingualityZsize_categoriesZtask_categoriestask_ids:r7  r6  )r   r   getattrr@  r  rG  rH  )	rk   rM  Zdataset_strrJ  Zdata_attributesattrZ	curr_attrr   rK  rl   rl   rm   rL  -  s8    




zHfApi._unpack_dataset_filterz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  s   g | ]}t f |qS rl   )r   r   rl   rl   rm   r   a  s     z&HfApi.list_metrics.<locals>.<listcomp>)r   r"   r  rQ   r.  r3  rl   rl   rm   list_metricsV  s
    zHfApi.list_metrics)r6  r   r7  r9  r:  r;  r   r   linkedr<  r#  zUnion[str, Iterable[str], None]zIterable[SpaceInfo])r6  r   r7  r9  r:  r;  r   r   rS  r<  r#  rv   c                c  s.  | j  d}| j|d}i }|dk	r2|d|i |dk	rH|d|i |dk	r^|d|i |dk	rt|d|i |dk	r|d|i |dk	r|d	|i |
r|d
di |	r|ddi |dk	r|d|i |dk	r|d|i t|||d}|dk	rt||}|D ]}tf |V  qd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["lastModified"]` 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 `lastModified`
                and the `cardData`.
            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/spacesr*  Nr6  r   r7  r9  r:  r;  r<  TrS  r   r   r>  )r   r-  rB  rS   r	   r   )rk   r6  r   r7  r9  r:  r;  r   r   rS  r<  r#  r4  r,  r?  r   rC  rl   rl   rm   list_spacesc  s8    7

zHfApi.list_spaces)r#  r   rr   )r   r#  r   rv   c                C  sD   |dk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//liker*  r   r,  )rE   r"   postr   r-  rQ   rk   r   r#  r   responserl   rl   rm   like  s    (
z
HfApi.likec                C  sD   |dkrt }t j| j d| d| d| j|dd}t| dS )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
        ```
        NrU  rV  rW  r*  rX  )rE   r"   deleter   r-  rQ   rZ  rl   rl   rm   unlike  s    ( 
zHfApi.unliker*  r  )r  r#  rv   c                C  s   |dkr2| 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", ...]
        ```
        Nr*  typer  r   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  s(   g | ] }|d  d dkr|d  d qS )repor_  r   r   rl   r   r\  rl   rl   rm   r   ]  s      z*HfApi.list_liked_repos.<locals>.<listcomp>c                 S  s(   g | ] }|d  d dkr|d  d qS )r`  r_  r   r   rl   ra  rl   rl   rm   r   ^  s      c                 S  s(   g | ] }|d  d dkr|d  d qS )r`  r_  spacer   rl   ra  rl   rl   rm   r   _  s      )r  r   r   r   r  )r0  r   r   r-  r  rS   r  r   )rk   r  r#  mer4  r,  Zlikesrl   rl   rm   list_liked_repos  s"    -

zHfApi.list_liked_repos)revisiontimeoutr   files_metadatar#  zOptional[float]r   )r   re  rf  r   rg  r#  rv   c                C  s   | j |d}|dkr$| j d| n| j d| dt|dd }i }	|rRd|	d< |r^d|	d	< t j||||	d
}
t|
 |
 }tf |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>
        r*  Nz/api/models/
/revision/rw   safeTr   blobsr,  rf  r?  )r-  r   r   r"   r  rQ   r.  r   )rk   r   re  rf  r   rg  r#  r,  r4  r?  r   r5  rl   rl   rm   
model_infob  s    4zHfApi.model_info)re  rf  rg  r#  r   )r   re  rf  rg  r#  rv   c                C  s   | j |d}|dkr$| j d| n| j d| dt|dd }i }|rRd|d< t j||||d	}	t|	 |	 }
tf |
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>
        r*  Nz/api/datasets/rh  rw   ri  Trk  rl  )r-  r   r   r"   r  rQ   r.  r   rk   r   re  rf  rg  r#  r,  r4  r?  r   r5  rl   rl   rm   dataset_info  s    0zHfApi.dataset_infor   c                C  s   | j |d}|dkr$| j d| n| j d| dt|dd }i }|rRd|d< t j||||d	}	t|	 |	 }
tf |
S )
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>
        r*  N/api/spaces/rh  rw   ri  Trk  rl  )r-  r   r   r"   r  rQ   r.  r   rn  rl   rl   rm   
space_info  s    0zHfApi.space_info)re  r   rf  rg  r#  z(Union[ModelInfo, DatasetInfo, SpaceInfo])r   re  r   rf  rg  r#  rv   c                C  sR   |dks|dkr| j }n(|dkr(| j}n|dkr8| 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>
        Nr   r   rb  zUnsupported repo type.)re  r#  rf  rg  )rm  ro  rq  r   )rk   r   re  r   rf  rg  r#  methodrl   rl   rm   	repo_info$  s    4zHfApi.repo_info)r   r#  )r   r   r#  rv   c                C  s2   z| j |||d W dS  tk
r,   Y dS X dS )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.

        <Tip>

        Examples:
            ```py
            >>> from huggingface_hub import repo_exists
            >>> repo_exists("huggingface/transformers")
            True
            >>> repo_exists("huggingface/not-a-repo")
            False
            ```

        </Tip>
        r   r   r#  TFN)rs  r   )rk   r   r   r#  rl   rl   rm   repo_existsh  s
    (zHfApi.repo_exists)r   re  r#  )r   filenamer   re  r#  rv   c             
   C  sR   t ||||d}z |dkr | j}t||d W dS  tttfk
rL   Y dS X dS )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.

        <Tip>

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

        </Tip>
        )r   r   re  rv  Nr*  TF)rK   r#  rJ   r   r   r    )rk   r   rv  r   re  r#  r   rl   rl   rm   file_exists  s    1zHfApi.file_exists)expandre  r   r#  zUnion[List[str], str, None]zIterable[RepoFile])r   pathsrx  re  r   r#  rv   c             	   c  sZ  |pt }|dk	rt|ddnt}| j|d}ddddd	}g }	|dkrT|	d n|g kr`dS t j| j d
| d| d| t|t	r|n|gdd|d}
t
|
 |
 }|D ]*}|d dkr||V  q|	|d  q|	D ]p}|rdt|dd nd}| j d
| d| d| | }t||d|ddD ]}|d dkr4||V  q4qd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: {"blob_id": "43bd404b159de6fba7c2f4d3264347668d43af25", "lfs": None, "rfilename": "README.md", "size": 391},
                RepoFile: {"blob_id": "2f9618c3a19b9a61add74f70bfb121335aeef666", "lfs": None, "rfilename": "config.json", "size": 554},
            ]
            ```

            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: {
                {'blob_id': '815004af1a321eaed1d93f850b2e94b0c0678e42',
                'lastCommit': {'date': '2023-03-21T09:05:27.000Z',
                                'id': '47b62b20b20e06b9de610e840282b7e6c3d51190',
                                'title': 'Upload diffusers weights (#48)'},
                'lfs': None,
                'rfilename': 'model_index.json',
                'security': {'avScan': {'virusFound': False, 'virusNames': None},
                                'blobId': '815004af1a321eaed1d93f850b2e94b0c0678e42',
                                'name': 'model_index.json',
                                'pickleImportScan': None,
                                'repositoryId': 'models/prompthero/openjourney-v4',
                                'safe': True},
                'size': 584}
                },
                RepoFile: {
                {'blob_id': 'd2343d78b33ac03dade1d525538b02b130d0a3a0',
                'lastCommit': {'date': '2023-03-21T09:05:27.000Z',
                                'id': '47b62b20b20e06b9de610e840282b7e6c3d51190',
                                'title': 'Upload diffusers weights (#48)'},
                'lfs': {'pointer_size': 134,
                        'sha256': 'dcf4507d99b88db73f3916e2a20169fe74ada6b5582e9af56cfa80f5f3141765',
                        'size': 334711857},
                'rfilename': 'vae/diffusion_pytorch_model.bin',
                'security': {'avScan': {'virusFound': False, 'virusNames': None},
                                'blobId': 'd2343d78b33ac03dade1d525538b02b130d0a3a0',
                                'name': 'vae/diffusion_pytorch_model.bin',
                                'pickleImportScan': {'highestSafetyLevel': 'innocuous',
                                                    'imports': [{'module': 'torch._utils',
                                                                'name': '_rebuild_tensor_v2',
                                                                'safety': 'innocuous'},
                                                                {'module': 'collections', 'name': 'OrderedDict', 'safety': 'innocuous'},
                                                                {'module': 'torch', 'name': 'FloatStorage', 'safety': 'innocuous'}]},
                                'repositoryId': 'models/prompthero/openjourney-v4',
                                'safe': True},
                'size': 334711857}
                },
                (...)
            ]
            ```

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

            ```py
            >>> from huggingface_hub import list_files_info
            >>> [info.rfilename 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.rfilename for info in list_files_info("glue", repo_type="dataset")]
            ['.gitattributes', 'README.md', 'dataset_infos.json', 'glue.py']
            ```
        Nrw   ri  r*  r   r   )inforv   c                 S  sp   |  d}|  d}|  d}|  dd }|  dd  |d k	rXt|d |d |d d}tf ||||d| S )	Nr4  r   r   r   r_  ZpointerSize)r   r   r   r   )r   r   r   )rz  r   r   r   r   rl   rl   rm   _format_as_repo_fileX  s    


z3HfApi.list_files_info.<locals>._format_as_repo_filerU  rV  z/paths-info/T)ry  rx  )r   r,  r_  filer4  ry   /tree/)	recursiverx  )r4  r,  r?  )rE   r   rB   r-  rH  r"   rY  r   r@  r  rQ   r.  rS   )rk   r   ry  rx  re  r   r#  r,  r{  Zfolder_pathsr[  Z
paths_infoZ	path_infor4  Zencoded_pathZtree_urlZsubpath_inforl   rl   rm   list_files_info  s:      zHfApi.list_files_infoz0.17rf  ztimeout is not used anymore.)versionZdeprecated_argsZcustom_message)re  r   rf  r#  r  )r   re  r   rf  r#  rv   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 | ]
}|j qS rl   )r   )r   frl   rl   rm   r     s   z)HfApi.list_repo_files.<locals>.<listcomp>N)r   ry  re  r   r#  )r  )rk   r   re  r   rf  r#  rl   rl   rm   list_repo_files  s        zHfApi.list_repo_filesr  c                C  s|   |pt }t j| j d| d| d| j|dd}t| | }tdd |d D d	d |d
 D dd |d D dS )a6  
        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`.
            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.
        rU  rV  z/refsr*  r+  c                 S  s   g | ]}t |qS rl   r   r   rC  rl   rl   rm   r     s     z(HfApi.list_repo_refs.<locals>.<listcomp>r  c                 S  s   g | ]}t |qS rl   r  r  rl   rl   rm   r     s     r  c                 S  s   g | ]}t |qS rl   r  r  rl   rl   rm   r     s     r   )r  r  r   )rE   r"   r  r   r-  rQ   r.  r  )rk   r   r   r#  r[  r   rl   rl   rm   list_repo_refs  s    0 
zHfApi.list_repo_refs)r   r#  re  r  zList[GitCommitInfo])r   r   r#  re  r  rv   c             	   C  sd   |pt }|dk	rt|ddnt}dd t| j d| d| d| | j|d	|rXd
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.
        Nrw   ri  c                 S  s   g | ]}t |qS rl   )r  r  rl   rl   rm   r   -	  s   z+HfApi.list_repo_commits.<locals>.<listcomp>rU  rV  z	/commits/r*  zexpand[]r  r,  r?  )rE   r   rB   rS   r   r-  )rk   r   r   r#  re  r  rl   rl   rm   list_repo_commits  s    A
zHfApi.list_repo_commits)branchr   r   r#  )r   r  r   r   r#  rv   c          	      C  s   |dkrt }|tkrtd|dkr(t}| j d| d| d| }| j|d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 typerU  rV  z/super-squash/Tr#  is_write_actionzSuper-squash branch 'z' using huggingface_hubr  r   r,  r.  )	rE   rF   r   rB   r   r-  r"   rY  rQ   )	rk   r   r  r   r   r#  r   r,  r[  rl   rl   rm   super_squash_history6	  s    EzHfApi.super_squash_history)
r#  r   r   exist_ok	space_sdkspace_hardwarespace_storagespace_sleep_timespace_secretsspace_variableszOptional[SpaceHardware]zOptional[SpaceStorage]zOptional[List[Dict[str, str]]]r   )r   r#  r   r   r  r  r  r  r  r  r  rv   c       
         C  sb  d|kr| dnd|f\}}| j d}|tkr:td|||d}|dk	rV||d< |dkr|dkrvtdt d	|tkrtd
t d||d< |dk	r|dkrtd dddddg}dddddg}|||	|
|g}|dkr|dd t||D  n2dd t||D }|r0tdd	| d t
| ddrH| j|d < | j|d!d"}t j|||d#}zt| W n tk
rF } z|r|jjd$krn|r4|jjd%kr4zf| j|||d& |dks|tkrt| j d| W  W Y FS t| j d| d| W  W Y "S  tk
r0    Y nX n W 5 d}~X Y nX | }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`.
        ry   Nz/api/repos/creater  )r   organizationr   r_  rb  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sdkz=Ignoring provided space_sdk because repo_type is not 'space'.r  r  r  r  r  hardwarestorageTiersleepTimeSecondssecrets	variablesc                 S  s   i | ]\}}|d k	r||qS r   rl   r   r   r   rl   rl   rm   
<dictcomp>	  s       z%HfApi.create_repo.<locals>.<dictcomp>c                 S  s   g | ]\}}|d k	r|qS r   rl   )r   r   r  rl   rl   rm   r   	  s      z%HfApi.create_repo.<locals>.<listcomp>zIgnoring provided , z" because repo_type is not 'space'._lfsmultipartthreshZlfsmultipartthreshTr  r,  r.    i  rt  r   r   )r   r   rF   r   rI   warningswarnrB  r  joinrP  r  r-  r"   rY  rQ   r   r[  status_coders  rE   r   rN   r.  )rk   r   r#  r   r   r  r  r  r  r  r  r  r  r   r4  r.  Zfunction_argsZ	json_keysvaluesZprovided_space_argsr,  r   errr5  rl   rl   rm   create_repo	  sd    6


$
zHfApi.create_repo)r#  r   
missing_ok)r   r#  r   r  rv   c                C  s   d|kr| dnd|f\}}| j d}|tkr:td||d}|dk	rT||d< | j|dd}	t j||	|d	}
zt|
 W n tk
r   |s Y nX dS )
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).
        ry   Nz/api/repos/deleter  )r   r  r_  Tr  r  )	r   r   rF   r   r-  r"   r]  rQ   r   )rk   r   r#  r   r  r  r   r4  r.  r,  r   rl   rl   rm   delete_repo
  s    
zHfApi.delete_repo)r#  r  r   r   zDict[str, bool])r   r   r#  r  r   r   rv   c          	   	   C  s   |t krtdd|kr"|dnd|f\}}|dkrF| |d }n|}|dkrVt}t j| j d| d| d| d| j|d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  ry   Nr   rU  rV  z	/settingsTr  r   r  )rF   r   r   r0  rE   r"   putr   r-  rQ   r.  )	rk   r   r   r#  r  r   r   r   r   rl   rl   rm   update_repo_visibility5
  s    'zHfApi.update_repo_visibility)from_idto_idr   r#  c          
   
   C  s   t |ddkr"td| dt |ddkrDtd| d|dkrPt}|||d}| j d}| j|dd	}t j|||d
}zt| W n. t	k
r }	 z|	
d  W 5 d}	~	X Y nX dS )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>
        ry   r|   zInvalid repo_id: z6. It should have a namespace (:namespace:/:repo_name:)N)ZfromRepoZtoRepor_  z/api/repos/moveTr  r  zv
For additional documentation please see https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.)r   r   r   rE   r   r-  r"   rY  rQ   rN   append_to_message)
rk   r  r  r   r#  r.  r4  r,  r   r/  rl   rl   rm   	move_repoq
  s"    'zHfApi.move_repo   .)r   r#  r   re  	create_prnum_threadsparent_commitr  zIterable[CommitOperation]r   zLiteral[False]r   )r   
operationsr   r   r#  r   re  r  r  r  r  rv   c       	         C  s   d S r   rl   rk   r   r  r   r   r#  r   re  r  r  r  r  rl   rl   rm   create_commit
  s    zHfApi.create_commitzLiteral[True]zFuture[CommitInfo]c       	         C  s   d S r   rl   r  rl   rl   rm   r  
  s    z%Union[CommitInfo, Future[CommitInfo]]c       	      
     s  d}|
dk	r$t |
s$tdt  |dks8t|dkr@td|dk	rL|nd}|dk	r\|nt}|tkrvtdt |dk	rt|ddnt}|dk	r|nd	}t|}d
d |D }dd |D }t|}t|}t|| | }t	
dt| dt| d| d t| z$t||||p$| j|| j|dW n0 tk
rd } z||  W 5 d}~X Y nX t||||px| j|| jd}tfdd|D |||p| j| j|	d t|||||
d | j d| d| d| }dd fdd}ddi| j|dd }d!| }|r"d"d#ind}z$t j||||d$}t|d%d& W nv tk
rz } z||  W 5 d}~X Y nH tk
r } z(|dkrd't|kr|d(  W 5 d}~X Y nX | }t|d) |||d* |r|d+ ndd,S )-az  
        Creates a commit in the given repo, deleting & uploading files as needed.

        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

            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 the Hub API returns an HTTP 400 error (bad request)
            [`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.

        <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>
        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.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.rw   "Invalid repo type, must be one of ri  Fc                 S  s   g | ]}t |tr|qS rl   )r@  r%   r   oprl   rl   rm   r   S  s     
 z'HfApi.create_commit.<locals>.<listcomp>c                 S  s   g | ]}t |tr|qS rl   )r@  r&   r  rl   rl   rm   r   T  s     
 zAbout to commit to the hub: z addition(s), z copie(s) and z deletion(s).)	additionsr   r   r#  re  r   r  )copiesr   r   r#  re  r   c                   s   g | ]} |j  d kr|qS )r   path_in_repo)r   Zaddition)upload_modesrl   rm   r   w  s      )r  r   r   r#  r   r  )r  r  files_to_copyr   r   r  rU  rV  z/commit/zIterable[bytes]r   c                  3  s$    D ]} t |  V  dV  qd S )N   
)r.  dumpsencode)rC  )commit_payloadrl   rm   _payload_as_ndjson  s    z/HfApi.create_commit.<locals>._payload_as_ndjsonzContent-Typezapplication/x-ndjsonTr      r  1)r   r,  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`.Z	commitUrlZ	commitOidZpullRequestUrl)r   r   r   r   r   )rD   	fullmatchr   r   rE   rF   r   rB   r  loggerdebugr,   r)   r#  r   r   r  r(   r+   r*   r-  r  r"   rY  rQ   r   rr   r.  r   )rk   r   r  r   r   r#  r   re  r  r  r  r  Z$_CREATE_COMMIT_NO_REPO_ERROR_MESSAGEr  r  Znb_additionsZ	nb_copiesZnb_deletionsr/  r  r   r  r,  r   r?  Zcommit_respZcommit_datarl   )r  r  rm   r  
  s    l

	


 
T)r   r#  r   merge_prr  verbosezList[List[CommitOperationAdd]]z!List[List[CommitOperationDelete]])r   addition_commitsdeletion_commitsr   r   r#  r   r  r  r  rv   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 ]N}|j
r|jdkr|j|jkr| j||j||d}|d|j d  qqt| ||||||d}|d|j  |jD ]}t|tr|} qFqtd|j dt|j}t|t|jkrtd|j dt| dt|j d|jD ]4}||k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rftd|j d't|j d(t| d)d*d+ |jD }d,d+ |jD }|D ]D}|j|kr||j}d-|_n|j|kr||j}d-|_qt|d$krt|t|jk rtd|j d.t|t| }t|d$krF|| d/t| d0t| d1 t |! t |!  D ]r}| 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> |rz$| j)||||jt*d? |d@ W n t+k
r } zr|j,dAk	rdB|j,kr| j'||||jt-dCdD |.dE n2| j/||||jt0j1|j,dFd? tdG|j, |W 5 dA}~X Y nX |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>

        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.

        <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>
        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   Zopsrl   rl   rm   	<genexpr>  s     z-HfApi.create_commits_on_pr.<locals>.<genexpr>z atomic operations.c                 S  s   g | ]}t |d qS r  r2   r   r  rl   rl   rm   r     s     z.HfApi.create_commits_on_pr.<locals>.<listcomp>c                 S  s   g | ]}t |d qS r  r  r  rl   rl   rm   r     s     )r  r  zMulti-commits strategy with ID r   rt  Zdraft)r   discussion_numr   r#  zPR already exists: z'. Will resume process where it stopped.)r   r   r   strategyr#  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  z).c                 S  s   h | ]
}|j qS rl   r  r   r  rl   rl   rm   	<setcomp>O  s   z-HfApi.create_commits_on_pr.<locals>.<setcomp>)r   r   r#  re  c                   s   g | ]}|j  kr|qS rl   r  r  Zcommits_on_main_branchrl   rm   r   U  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  s   i | ]}|j |qS rl   r   r   steprl   rl   rm   r  h  s      z.HfApi.create_commits_on_pr.<locals>.<dictcomp>c                 S  s   i | ]}|j |qS rl   r   r  rl   rl   rm   r  i  s      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   r#  r   re  r  r  r  r#   z  step z completed (still z to go).)r   r   r  )r   r   r#  r  
comment_idnew_contentzAll commits have been pushed.)r   r   r#  r  	new_titleopen)r   r   r#  r  
new_statuscommentzPR is now open for reviews.)r   r   r#  r  r  z>PR has been automatically merged (`merge_pr=True` was passed).Nzno associated changesclosed)r   r   r#  r  r  r  z-Couldn't merge the PR: no associated changes.)error_messagez-Couldn't merge Pull Request in multi-commit: )2rR   
get_loggerrh   setLevelrz  r   sumr3   r   get_repo_discussionsis_pull_requeststatusr
  get_discussion_detailsnumr   r4   eventsr@  r=   r1   r6   contentZ	all_stepsr  r  rB   Zgit_referencer  r  r   	completedr  r  r  r  edit_discussion_commentr5   rename_discussionchange_discussion_statusr0   merge_pull_requestr/   rL   Zserver_messager.   warningcomment_discussionr-   format)rk   r   r  r  r   r   r#  r   r  r  r  r  r  
discussionpreventZ
pr_commentZdescription_commitsZstep_idZ
pr_commitsZremaining_additionsZremaining_deletionsr  r  Znb_remainingerrorrl   r  rm   create_commits_on_pr  sJ   h
0   	


"

   
   "
"
  



	
zHfApi.create_commits_on_pr)r#  r   re  r   r   r  r  r  z!Union[str, Path, bytes, BinaryIO])path_or_fileobjr  r   r#  r   re  r   r   r  r  r  rv   c                C  s   d S r   rl   rk   r  r  r   r#  r   re  r   r   r  r  r  rl   rl   rm   upload_file  s    zHfApi.upload_filezFuture[str]c                C  s   d S r   rl   r  rl   rl   rm   r    s    zUnion[str, Future[str]]c                C  s   |t krtdt  |dk	r"|n
d| d}t||d}| j|||g|||||	|
d	}|jdk	rttt|jdd}|tkrt| | }|dk	r|nt}| j	 d	| d
| d	| S )a  
        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:
            `str` or `Future`: The URL to visualize the uploaded file on the hub. 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"
        ```
        r  NzUpload  with huggingface_hubr  r  )	r   r   r  r   r   r#  re  r  r  rw   ri  ry   z/blob/)
rF   r   r%   r  r   r   r   rH   rB   r   )rk   r  r  r   r#  r   re  r   r   r  r  r  Z	operationcommit_inforl   rl   rm   r    s2    }
)r  r   r   r#  r   re  r  r  allow_patternsignore_patternsdelete_patternsmulti_commitsmulti_commits_verboser  Union[str, Path]Optional[Union[List[str], str]])r   folder_pathr  r   r   r#  r   re  r  r  r  r  r  r  r  r  rv   c                C  s   d S r   rl   rk   r   r
  r  r   r   r#  r   re  r  r  r  r  r  r  r  r  rl   rl   rm   upload_folder  s    zHfApi.upload_folderc                C  s   d S r   rl   r  rl   rl   rm   r    s    c                  s  |t krtdt  |r2|dk	r2|tkr2td|dkr>d}|dkrLg }nt|tr\|g}|t7 }| j|||	rttn||||d}t||||d}t|dkrt	dd	 |D   fd
d|D }|| }|pd}|rt
|d\}}| j||||||||	 |d	}n"| j||||||||	|
d	}|j}|	rH|dk	rHtt|dd}|tkr^t| | }|dk	rl|nt}| j 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:
            `str` or `Future[str]`: A URL to visualize the uploaded folder on the hub. 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"

        ```
        r  NzGCannot use `multi_commit` to commit changes other than the main branch.rw   )r   r   re  r#  r  r  r  r  r   c                 s  s   | ]}|j V  qd S r   r  r  rl   rl   rm   r    s     z&HfApi.upload_folder.<locals>.<genexpr>c                   s   g | ]}|j  kr|qS rl   r  )r   Z	delete_opZadded_pathsrl   rm   r     s    
 z'HfApi.upload_folder.<locals>.<listcomp>z#Upload folder using huggingface_hubr  )	r   r   r  r  r   r   r#  r  r  )	r   r   r  r   r   r#  re  r  r  ri  ry   r}  )rF   r   rB   r@  rr   r    _prepare_upload_folder_deletions _prepare_upload_folder_additionsr   setr7   r  r  r   r   r   rH   r   )rk   r   r
  r  r   r   r#  r   re  r  r  r  r  r  r  r  r  Zdelete_operationsZadd_operationsZcommit_operationsr  r  r   r  rl   r  rm   r    s     &



)r#  r   re  r   r   r  r  )
r  r   r#  r   re  r   r   r  r  rv   c                C  s@   |dk	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   r#  r  re  r   r   r  r  )r'   r  )rk   r  r   r#  r   re  r   r   r  r  r  rl   rl   rm   delete_file  s    GzHfApi.delete_filec          
      C  s:   | j |||t|ddg||dk	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  )r  r'   )
rk   r  r   r#  r   re  r   r   r  r  rl   rl   rm   delete_folder  s    3zHfApi.delete_folderauto
   )	subfolderr   re  	cache_dir	local_dirlocal_dir_use_symlinksforce_downloadforce_filenameproxiesetag_timeoutresume_downloadlocal_files_onlylegacy_cache_layoutzUnion[str, Path, None]zUnion[bool, Literal['auto']]r   float)r   rv  r  r   re  r  r  r  r  r  r  r  r   r!  r"  rv   c                C  sF   ddl m} ||||||| j| j| j|||| j|	|
|||| j||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.
            endpoint (`str`, *optional*):
                Hugging Face Hub base url. Will default to https://huggingface.co/. Otherwise, one can set the `HF_ENDPOINT`
                environment variable.
            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.
            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_download)r   rv  r  r   re  r   r$  r%  r  r  r  r&  r  r  r  r  r   r#  r!  r"  )file_downloadr$  r   r$  r%  r&  r#  )rk   r   rv  r  r   re  r  r  r  r  r  r  r  r   r!  r"  r$  rl   rl   rm   r$  R  s0     	zHfApi.hf_hub_download   )r   re  r  r  r  r  r  r   r  r!  r  r  r(  
tqdm_classzOptional[base_tqdm])r   r   re  r  r  r  r  r  r   r  r!  r  r  r(  r'  rv   c                C  sF   ddl m} ||||| j|||| j| j| j|||	|
| j|||||dS )a  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.
            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_download)r   r   re  r   r  r  r  r$  r%  r&  r  r  r   r  r#  r!  r  r  r(  r'  )Z_snapshot_downloadr(  r   r$  r%  r&  r#  )rk   r   r   re  r  r  r  r  r  r   r  r!  r  r  r(  r'  r(  rl   rl   rm   r(    s.    kzHfApi.snapshot_download)re  r#  r   r  )r   r  re  r#  r   r  rv   c             
   C  s   |dkrt }t|dd}| j d| d| d| }| j|dd}i }	|dk	rV||	d	< t j|||	d
}
zt|
 W n4 tk
r } z|jj	dkr|s W 5 d}~X Y nX dS )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`.
        Nrw   ri  rU  rV  /branch/Tr  ZstartingPointr  r  )
rE   r   r   r-  r"   rY  rQ   rN   r[  r  )rk   r   r  re  r#  r   r  
branch_urlr,  payloadr[  r/  rl   rl   rm   create_branchw  s    0zHfApi.create_branch)r   r  r#  r   rv   c                C  s^   |dkrt }t|dd}| j d| d| d| }| j|d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.

        Nrw   ri  rU  rV  r)  Tr  rX  rE   r   r   r-  r"   r]  rQ   )rk   r   r  r#  r   r*  r,  r[  rl   rl   rm   delete_branch  s    %zHfApi.delete_branch)tag_messagere  r#  r   r  )r   tagr/  re  r#  r   r  rv   c             
   C  s   |dkrt }|dk	r t|ddnt}| j d| d| d| }| j|dd}	d	|i}
|dk	rf||
d
< t j||	|
d}zt| W n4 tk
r } z|j	j
dkr|s W 5 d}~X Y nX dS )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`.
        Nrw   ri  rU  rV  /tag/Tr  r0  r  r  r  )rE   r   rB   r   r-  r"   rY  rQ   rN   r[  r  )rk   r   r0  r/  re  r#  r   r  tag_urlr,  r+  r[  r/  rl   rl   rm   
create_tag  s    4zHfApi.create_tag)r   r0  r#  r   rv   c                C  s^   |dkrt }t|dd}| j d| d| d| }| j|dd}t j||d	}t| dS )
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.
        Nrw   ri  rU  rV  r1  Tr  rX  r-  )rk   r   r0  r#  r   r2  r,  r[  rl   rl   rm   
delete_tag2  s    "zHfApi.delete_tag)r  r#  )model_idr  r#  c                C  sP   |dkr>d|kr | dd }n| j|dd }| d| S | 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.
        Nry   r   r*  r   )r   r0  )rk   r5  r  r#  usernamerl   rl   rm   get_full_repo_name`  s    zHfApi.get_full_repo_namezIterator[Discussion]c          	      #  s   t krtdt  dkr"tj|d dd fdd}d\}}|r||d\}}|D ]Z}t|d	 |d
 |di ddt|d |d |d d |d d |d jd	V  qd|d }qNd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 `/`.
            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)
            ```
        r  Nr*  r   )
page_indexc                   sl   j  d d d|  }t j| d}t| | }|d }|d }|d }|t| |k }||fS )NrU  rV  z/discussions?p=r+  countstartdiscussions)r   r"   r  rQ   r.  r   )r8  r4  respZpaginated_discussionsr   r:  r;  has_nextr,  r   r   rk   rl   rm   _fetch_discussion_page  s    z:HfApi.get_repo_discussions.<locals>._fetch_discussion_page)Tr   r
  r  r   r   deleted	createdAtr  r`  r_  isPullRequest)	r
  r  r   r	  r  r   r   r  r   r#   )rF   r   rE   r-  r<   r  rT   r   )	rk   r   r   r#  r?  r=  r8  r;  r  rl   r>  rm   r    s,    )



zHfApi.get_repo_discussionsr@   )r   r  r   r#  rv   c                C  s@  t |tr|dkrtd|tkr0tdt |dkr<t}| j d| d| d| }| j|d}t j|d	d
i|d}t	| |
 }|d }	|	r|d d nd}
|	r|d nd}|	r|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 integerr  NrU  rV  /discussions/r*  diffr  r>  rB  changesbaseZfilesWithConflictsZmergeCommitIdr
  r  r   r   r@  rA  r  r`  r_  c                 S  s   g | ]}t |qS rl   )rA   )r   Zevtrl   rl   rm   r     s     z0HfApi.get_discussion_details.<locals>.<listcomp>r  )r
  r  r   r	  r  r   r   r  r  conflicting_filestarget_branchmerge_commit_oidrE  r   )r@  r   r   rF   rE   r   r-  r"   r  rQ   r.  r@   rT   )rk   r   r  r   r#  r4  r,  r<  Zdiscussion_detailsr  rI  rH  rJ  rl   rl   rm   r    s>    (


zHfApi.get_discussion_details)r#  r   r   pull_request)r   r
  r#  r   r   rK  rv   c          
      C  s   |t krtdt  |dkr"t}|dk	r2| }|r:|n|rBdnd d}| j|d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>r  NzPull Requestr<   z^ opened with the [huggingface_hub Python library](https://huggingface.co/docs/huggingface_hub)Tr  rU  rV  z/discussions)r
  r   ZpullRequest)r.  r,  r  )r   r   r  r#  )rF   r   rE   stripr-  r"   rY  r   rQ   r.  r  )
rk   r   r
  r#  r   r   rK  r,  r<  r  rl   rl   rm   create_discussion  s6    5
	zHfApi.create_discussion)r#  r   r   )r   r
  r#  r   r   rv   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
  r#  r   r   rK  )rM  )rk   r   r
  r#  r   r   rl   rl   rm   create_pull_requestx  s    1zHfApi.create_pull_request)bodyr#  r   r   zrequests.Response)r   r  resourcerO  r#  r   rv   c          
      C  s   t |tr|dkrtd|tkr0tdt |dkr<t}| d| }| j d| d| d| }| j|d	d
}tj|||d}	t	|	 |	S )z@Internal utility to POST changes to a Discussion or Pull Requestr   rC  r  NrV  rU  rD  ry   Tr  r  )
r@  r   r   rF   rE   r   r-  requestsrY  rQ   )
rk   r   r  rP  rO  r#  r   r4  r,  r<  rl   rl   rm   _post_discussion_changes  s    zHfApi._post_discussion_changesr=   )r   r  r  r#  r   rv   c                C  s*   | 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  r#  rP  rO  Z
newMessagerR  rA   r.  )rk   r   r  r  r#  r   r<  rl   rl   rm   r    s    BzHfApi.comment_discussionr?   )r   r  r  r#  r   rv   c                C  s*   | j ||||dd|id}t| d S )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
  rS  ZnewTitlerT  )rk   r   r  r  r#  r   r<  rl   rl   rm   r    s    9zHfApi.rename_discussion)r#  r  r   zLiteral[('open', 'closed')]r>   )r   r  r  r#  r  r   rv   c          	      C  sV   |dkrt dd|i}|r0| r0| |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  rS  Z	newStatus)r   rL  rR  rA   r.  )	rk   r   r  r  r#  r  r   rO  r<  rl   rl   rm   r  [  s    <zHfApi.change_discussion_status)r   r  r#  r  r   c             	   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  NrS  )rR  rL  )rk   r   r  r#  r  r   rl   rl   rm   r    s    ,zHfApi.merge_pull_request)r   r  r  r  r#  r   rv   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/editr  rS  updatedComment)rR  lowerrA   r.  )rk   r   r  r  r  r#  r   r<  rl   rl   rm   r    s    /zHfApi.edit_discussion_comment)r   r  r  r#  r   rv   c                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.rV  z/hide)r   r   r  r#  rP  rW  )r  r  UserWarningrR  rX  rA   r.  )rk   r   r  r  r#  r   r<  rl   rl   rm   hide_discussion_comment  s    0zHfApi.hide_discussion_comment)r   r#  )r   r   r  r   r#  rv   c                C  sN   ||d}|dk	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   r  Nr   rp  /secretsr*  r  )r"   rY  r   r-  rQ   rk   r   r   r  r   r#  r+  r   rl   rl   rm   add_space_secretQ  s    

zHfApi.add_space_secret)r   r   r#  rv   c                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.
        rp  r\  r*  r   r  N)r"   r]  r   r-  rQ   rk   r   r   r#  r   rl   rl   rm   delete_space_secretp  s    
zHfApi.delete_space_secretzDict[str, SpaceVariable])r   r#  rv   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.
        rp  
/variablesr*  r+  c                 S  s   i | ]\}}|t ||qS rl   r;   r  rl   rl   rm   r    s      z-HfApi.get_space_variables.<locals>.<dictcomp>)r"   r  r   r-  rQ   r.  r   rk   r   r#  r   rl   rl   rm   get_space_variables  s    
zHfApi.get_space_variablesc                C  s`   ||d}|dk	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   rp  ra  r*  r  c                 S  s   i | ]\}}|t ||qS rl   rb  r  rl   rl   rm   r    s      z,HfApi.add_space_variable.<locals>.<dictcomp>)r"   rY  r   r-  rQ   r.  r   r]  rl   rl   rm   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.
        rp  ra  r*  r   r  c                 S  s   i | ]\}}|t ||qS rl   rb  r  rl   rl   rm   r    s      z/HfApi.delete_space_variable.<locals>.<dictcomp>)r"   r]  r   r-  rQ   r.  r   r_  rl   rl   rm   delete_space_variable  s    
zHfApi.delete_space_variabler9   c                C  s:   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.
        rp  z/runtimer*  r+  )r"   r  r   r-  rQ   r9   r.  rc  rl   rl   rm   get_space_runtime  s     
zHfApi.get_space_runtime)r#  
sleep_timer8   )r   r  r#  rh  rv   c                C  sr   |dk	r|t jkrtdt d|i}|dk	r6||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  rp  z	/hardwarer*  r  )r8   	CPU_BASICr  r  rY  r"   rY  r   r-  rQ   r9   r.  )rk   r   r  r#  rh  r+  r   rl   rl   rm   request_space_hardware  s     
zHfApi.request_space_hardware)r   rh  r#  rv   c                C  sf   t  j| j d| d| j|dd|id}t| t| }|jpJ|j}|t	j
krbt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>
        rp  z
/sleeptimer*  secondsr  ri  )r"   rY  r   r-  rQ   r9   r.  Zrequested_hardwarer  r8   rj  r  r  rY  )rk   r   rh  r#  r   Zruntimer  rl   rl   rm   set_space_sleep_time  s    

zHfApi.set_space_sleep_timec                C  s:   t  j| j d| d| j|dd}t| t| S )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.
        rp  z/pauser*  r+  r"   rY  r   r-  rQ   r9   r.  rc  rl   rl   rm   pause_spaceF  s     
zHfApi.pause_space)r#  factory_reboot)r   r#  rp  rv   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factoryrp  z/restartr*  r  rn  )rk   r   r#  rp  r?  r   rl   rl   rm   restart_spacej  s    " 
 zHfApi.restart_space)r   r#  r  r  storagerh  r  r  )r  r  r   r#  r  r  rt  rh  r  r  rv   c             
   C  sF  |dk	rt |nd}|dk	r,|jdk	r,|jn| |d }|dk	rH|jnt |j}d| d| i}ddddd	d
g}|||||	|
g}|dd t||D  |dk	r|tjkrt	dt
 t j| j d| d| j|dd|d}zt| W n< tk
r. } z|r|jjdkrn W 5 d}~X Y nX 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',...)
        ```
        Nr   
repositoryry   r   r  r  r  r  r  c                 S  s   i | ]\}}|d k	r||qS r   rl   r  rl   rl   rm   r    s       z)HfApi.duplicate_space.<locals>.<dictcomp>ri  rp  z
/duplicateTr  r  r  r   r  )r   r   r0  r   rB  r  r8   rj  r  r  rY  r"   rY  r   r-  rQ   r   r[  r  r.  )rk   r  r  r   r#  r  r  rt  rh  r  r  Zparsed_to_idZto_namespaceZto_repo_namer+  keysr  r   r  rl   rl   rm   duplicate_space  s:    IzHfApi.duplicate_spacer:   )r   rt  r#  rv   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tierrp  /storager*  r  rn  )rk   r   rt  r#  r+  r   rl   rl   rm   request_space_storage  s    
zHfApi.request_space_storagec                C  s:   t  j| j d| d| j|dd}t| t| S )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.

        rp  rx  r*  r+  )r"   r]  r   r-  rQ   r9   r.  rc  rl   rl   rm   delete_space_storage,  s    
zHfApi.delete_space_storagezDict[str, str])r#  r  r$  r%  r&  rv   c                 C  s2   |dkr| j }t|||p| j|p$| j|p,| jdS )z
        Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client
        when `token` is not provided.
        N)r#  r  r$  r%  r&  )r#  rO   r$  r%  r&  )rk   r#  r  r$  r%  r&  rl   rl   rm   r-  H  s    zHfApi._build_hf_headerszList[CommitOperationDelete])r   r   re  r#  r  r  rv   c                   sp   |dkrg S | j ||||d} rD 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.
        N)r   re  r   r#  ry   c                   s(   i | ] }|  r|t d  |qS r   )r   r   r   r|  r  rl   rm   r  z  s    
  z:HfApi._prepare_upload_folder_deletions.<locals>.<dictcomp>c                 S  s   i | ]
}||qS rl   rl   r{  rl   rl   rm   r  ~  s      c                   s(   g | ] } | d krt  | ddqS )z.gitattributesFr  )r'   r   relpath)relpath_to_abspathrl   rm   r     s   z:HfApi._prepare_upload_folder_deletions.<locals>.<listcomp>)r  )r  rL  rP   rv  )rk   r   r   re  r#  r  r  	filenamesrl   )r  r~  rm   r  _  s    

z&HfApi._prepare_upload_folder_deletions)NNNNN)N)N)N)N)F)N)NFNNN)Mrh   ro   rp   r   r  rU   r0  r2  r   r   r   rA  r   rL  rR  rT  r\  r^  rd  rm  ro  rq  rs  ru  rw  r  rV   r  r  r  r  r  r  r  r  r   r  r"  r!   r  r  r  r  r  r$  r(  r,  r.  r3  r4  r7  r  r  rM  rN  rR  r  r  r  r  r  rZ  r^  r`  rd  re  rf  rg  rk  rm  ro  rs  rw  ry  rz  r-  r  rl   rl   rl   rm   r   W  s      '(

* 4$y)*T/.J C>> C-9  7 #;MT*z. @>**, X*  ,**, 446 r&W&@2 !2  B0"F-%LK X?K"B,J$4&8$< &"" (""(1$-"# $*0r$#     "r   r  r	  zList[CommitOperationAdd])r
  r  r  r  rv   c                   s~   t       s(td  d fddt dD |rX|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 rl   )is_filerelative_toas_posix)r   r4  )r
  rl   rm   r    s    z4_prepare_upload_folder_additions.<locals>.<dictcomp>z**/*ry   rw   c                   s    g | ]}t |  | d qS )r  )r%   r|  )prefixr~  rl   rm   r     s
   z4_prepare_upload_folder_additions.<locals>.<listcomp>r  )
r
   
expanduserresolveis_dirr   sortedglobrL  rP   rv  )r
  r  r  r  rl   )r
  r  r~  rm   r    s    
  r  )r   rv   c                 C  s2   t t| }|dk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: ''zrefs/pr/r#   )r   match_REGEX_DISCUSSION_URLRuntimeError)r   re_matchrl   rl   rm   r     s    	r   )N)NN)
__future__r   r  r.  rd   r   ri   r  concurrent.futuresr   r   dataclassesr   r   r   	functoolsr   	itertoolsr	   pathlibr
   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   urllib.parser   rQ  Zrequests.exceptionsr   Z	tqdm.autor   Z	base_tqdmZhuggingface_hub.utilsr   r   r   r   r    r!   r"   Z_commit_apir$   r%   r&   r'   r(   r)   r*   r+   r,   Z_multi_commitsr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   Z
_space_apir8   r9   r:   r;   Z	communityr<   r=   r>   r?   r@   rA   	constantsrB   rC   rD   rE   rF   rG   rH   rI   r%  rJ   rK   utilsrL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   Zutils._deprecationrV   Zutils._typingrW   Zutils.endpoint_helpersrX   rY   rZ   r[   r\   r]   r^   ZUSERNAME_PLACEHOLDERcompiler  r  rh   r  r_   r   r   r   rr   r   r   r   r   r   r   r   r   r   r  r  r  r"  r   r  r   r   r0  r2  r   rm  r   ro  rT  rq  ru  rw  rs  r  r  r  r  rR  r   r   r  r  r  r  r  r  r  r  r  r  r  r,  r.  r3  r4  r7  r  rd  r\  r^  r  r  rM  rN  r  r  r  r  r  r^  r`  rd  re  rf  rg  rk  rm  ro  rs  rw  ry  rz  rl   rl   rl   rm   <module>   s<  @$
,4 (
0 


U7<(AB-22*!                                      Z  $