U
    ”Ê¹j1ˆ  ã                   @   s,  d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	m
Z
 d dlZd dl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 d dlmZmZmZ dd	lmZ dd
lm Z  ddl!m"Z"m#Z#m$Z$ e# %e&¡Z'ee(ƒj)d d Z*ee(ƒj)d d Z+e ,d¡Z-G dd„ dƒZ.G dd„ de.ƒZ/G dd„ de.ƒZ0G dd„ de.ƒZ1e2ed dœdd„Z3e
e2ef ee dœdd„Z4e
e2ef eddœd d!„Z5dd"ddddd#œe2e2e2e2e2ee2e2ee2 e6ee2 ee2 ee2 ee2 ed$œd%d&„Z7e$dd"ddddd"dd'œe2eee2 e6ee2 ee2 ee2 ee2 e6ee2 e2d(œd)d*„ƒZ8dS )+é    N)ÚPath)ÚAnyÚDictÚLiteralÚOptionalÚTypeÚUnion)Úhf_hub_download)Úupload_file)ÚCardDataÚDatasetCardDataÚ
EvalResultÚModelCardDataÚSpaceCardDataÚeval_results_to_model_indexÚmodel_index_to_eval_results)Úget_sessionÚis_jinja_availableÚ	yaml_dumpé   )Ú	constants)ÚEntryNotFoundError)ÚSoftTemporaryDirectoryÚloggingÚvalidate_hf_hub_argsZ	templateszmodelcard_template.mdzdatasetcard_template.mdz1^(\s*---[\r\n]+)([\S\s]*?)([\r\n]+---(\r\n|\n|$))c                
   @   s   e Zd ZeZeZdZdee	dœdd„Z
edd„ ƒZejedœd	d„ƒZd
d„ Zeeef dœdd„Zedeeef ee ee e	dœdd„ƒZdee dœdd„Zdeee ee ee ee ee ee	 ee dœdd„Zed eee ee dœdd„ƒZdS )!ÚRepoCardÚmodelF)ÚcontentÚignore_metadata_errorsc                 C   s   || _ || _dS )a¸  Initialize a RepoCard from string content. The content should be a
        Markdown file with a YAML block at the beginning and a Markdown body.

        Args:
            content (`str`): The content of the Markdown file.

        Example:
            ```python
            >>> from huggingface_hub.repocard import RepoCard
            >>> text = '''
            ... ---
            ... language: en
            ... license: mit
            ... ---
            ...
            ... # My repo
            ... '''
            >>> card = RepoCard(text)
            >>> card.data.to_dict()
            {'language': 'en', 'license': 'mit'}
            >>> card.text
            '\n# My repo\n'

            ```
        > [!TIP]
        > Raises the following error:
        >
        >     - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
        >       when the content of the repo card metadata is not a dictionary.
        N)r   r   )Úselfr   r   © r    úW/var/www/html/bwave/python/venv/lib/python3.8/site-packages/huggingface_hub/repocard.pyÚ__init__+   s    "zRepoCard.__init__c                 C   s:   t | jƒpd}d|› | jj|| jd�› |› d|› | j› �S )zLThe content of the RepoCard, including the YAML block and the Markdown body.Ú
ú---)Ú
line_breakZoriginal_order)Ú_detect_line_endingÚ_contentÚdataÚto_yamlÚ_original_orderÚtext)r   r%   r    r    r!   r   P   s    zRepoCard.content©r   c                 C   s˜   || _ t |¡}|rZ| d¡}|| ¡ d… | _t |¡}|dkrFi }t|t	ƒsnt
dƒ‚nt d¡ i }|| _| jf |d| ji—Ž| _t| ¡ ƒ| _dS )z Set the content of the RepoCard.é   Nú)repo card metadata block should be a dictzBRepo card metadata block was not found. Setting CardData to empty.r   )r'   ÚREGEX_YAML_BLOCKÚsearchÚgroupÚendr+   ÚyamlÚ	safe_loadÚ
isinstanceÚdictÚ
ValueErrorÚloggerÚwarningÚcard_data_classr   r(   ÚlistÚkeysr*   )r   r   ÚmatchÚ
yaml_blockZ	data_dictr    r    r!   r   V   s    





c                 C   s   | j S )Nr,   )r   r    r    r!   Ú__str__q   s    zRepoCard.__str__)Úfilepathc              	   C   sF   t |ƒ}|jjddd� t|dddd��}| t| ƒ¡ W 5 Q R X dS )a{  Save a RepoCard to a file.

        Args:
            filepath (`Union[Path, str]`): Filepath to the markdown file to save.

        Example:
            ```python
            >>> from huggingface_hub.repocard import RepoCard
            >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
            >>> card.save("/tmp/test.md")

            ```
        T)ÚparentsÚexist_okÚwÚ úutf-8©ÚmodeÚnewlineÚencodingN)r   ÚparentÚmkdirÚopenÚwriteÚstr)r   r@   Úfr    r    r!   Úsavet   s    zRepoCard.saveN)Úrepo_id_or_pathÚ	repo_typeÚtokenr   c              
   C   s†   t |ƒ ¡ rt |ƒ}n8t|tƒr>t t|tj|p2| j|d�ƒ}ntd|› d�ƒ‚|j	dddd��}| | 
¡ |d�W  5 Q R £ S Q R X d	S )
a˜  Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath.

        Args:
            repo_id_or_path (`Union[str, Path]`):
                The repo ID associated with a Hugging Face Hub repo or a local filepath.
            repo_type (`str`, *optional*):
                The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options
                are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child
                class, the default value will be the child class's `repo_type`.
            token (`str`, *optional*):
                Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
            ignore_metadata_errors (`str`):
                If True, errors while parsing the metadata section will be ignored. Some information might be lost during
                the process. Use it at your own risk.

        Returns:
            [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's
                README.md file or filepath.

        Example:
            ```python
            >>> from huggingface_hub.repocard import RepoCard
            >>> card = RepoCard.load("nateraw/food")
            >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]

            ```
        )rR   rS   z.Cannot load RepoCard: path not found on disk (z).ÚrrD   rE   rF   )r   N)r   Úis_filer5   rN   r	   r   ÚREPOCARD_NAMErR   r7   rL   Úread)ÚclsrQ   rR   rS   r   Z	card_pathrO   r    r    r!   Úloadˆ   s    $

üÿ	zRepoCard.load©rR   c              
   C   s„   |p| j }|t| ƒdœ}ddi}ztƒ jd||d�}| ¡  W n@ tjjk
r~ } z|jdkrjt	|j
ƒ‚n|‚W 5 d}~X Y nX dS )aŒ  Validates card against Hugging Face Hub's card validation logic.
        Using this function requires access to the internet, so it is only called
        internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`].

        Args:
            repo_type (`str`, *optional*, defaults to "model"):
                The type of Hugging Face repo to push to. Options are "model", "dataset", and "space".
                If this function is called from a child class, the default will be the child class's `repo_type`.

        > [!TIP]
        > Raises the following errors:
        >
        >     - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
        >       if the card fails validation checks.
        >     - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
        >       if the request to the Hub API fails for any other reason.
        )ZrepoTyper   ÚAcceptz
text/plainz(https://huggingface.co/api/validate-yaml)Úheadersi�  N)rR   rN   r   ÚpostÚraise_for_statusÚrequestsÚ
exceptionsÚ	HTTPErrorÚstatus_coder7   r+   )r   rR   Úbodyr\   rT   Úexcr    r    r!   Úvalidate¾   s    
þ
zRepoCard.validate)Úrepo_idrS   rR   Úcommit_messageÚcommit_descriptionÚrevisionÚ	create_prÚparent_commitc	                 C   sn   |p| j }| j|d� tƒ �H}	t|	ƒtj }
|
jt| ƒdd� tt|
ƒtj||||||||d�
}W 5 Q R X |S )aA  Push a RepoCard to a Hugging Face Hub repo.

        Args:
            repo_id (`str`):
                The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food".
            token (`str`, *optional*):
                Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to
                the stored token.
            repo_type (`str`, *optional*, defaults to "model"):
                The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this
                function is called by a child class, it will default to the child class's `repo_type`.
            commit_message (`str`, *optional*):
                The summary / title / first line of the generated commit.
            commit_description (`str`, *optional*)
                The description of the generated commit.
            revision (`str`, *optional*):
                The git revision to commit from. Defaults to the head of the `"main"` branch.
            create_pr (`bool`, *optional*):
                Whether or not to create a Pull Request with this commit. Defaults to `False`.
            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.
        Returns:
            `str`: URL of the commit which updated the card metadata.
        rZ   rE   )rI   )
Zpath_or_fileobjZpath_in_reporf   rS   rR   rg   rh   rj   ri   rk   )	rR   re   r   r   r   rV   Ú
write_textrN   r
   )r   rf   rS   rR   rg   rh   ri   rj   rk   ZtmpdirZtmp_pathÚurlr    r    r!   Úpush_to_hubã   s$    )
özRepoCard.push_to_hub©Ú	card_dataÚtemplate_pathÚtemplate_strc           	      K   s‚   t ƒ rddl}ntdƒ‚| ¡  ¡ }| |¡ |dk	rBt|ƒ ¡ }|dkrXt| jƒ ¡ }| 	|¡}|j
f d| ¡ i|—Ž}| |ƒS )a'  Initialize a RepoCard from a template. By default, it uses the default template.

        Templates are Jinja2 templates that can be customized by passing keyword arguments.

        Args:
            card_data (`huggingface_hub.CardData`):
                A huggingface_hub.CardData instance containing the metadata you want to include in the YAML
                header of the repo card on the Hugging Face Hub.
            template_path (`str`, *optional*):
                A path to a markdown file with optional Jinja template variables that can be filled
                in with `template_kwargs`. Defaults to the default template.

        Returns:
            [`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the
            template.
        r   NzjUsing RepoCard.from_template requires Jinja2 to be installed. Please install it with `pip install Jinja2`.rp   )r   Újinja2ÚImportErrorÚto_dictÚcopyÚupdater   Ú	read_textÚdefault_template_pathÚTemplateÚrenderr)   )	rX   rp   rq   rr   Útemplate_kwargsrs   ÚkwargsÚtemplater   r    r    r!   Úfrom_template"  s    
ÿ

zRepoCard.from_template)F)NNF)N)NNNNNNN)NN)Ú__name__Ú
__module__Ú__qualname__r   r:   ÚTEMPLATE_MODELCARD_PATHry   rR   rN   Úboolr"   Úpropertyr   Úsetterr?   r   r   rP   Úclassmethodr   rY   re   rn   r   r    r    r    r!   r   &   s\   %
   û
û5(       ÷÷?  üür   c                       s@   e Zd ZeZeZdZedee	e
 e	e
 dœ‡ fdd„ƒZ‡  ZS )Ú	ModelCardr   Nro   c                    s   t ƒ j|||f|ŽS )aõ
  Initialize a ModelCard from a template. By default, it uses the default template, which can be found here:
        https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md

        Templates are Jinja2 templates that can be customized by passing keyword arguments.

        Args:
            card_data (`huggingface_hub.ModelCardData`):
                A huggingface_hub.ModelCardData instance containing the metadata you want to include in the YAML
                header of the model card on the Hugging Face Hub.
            template_path (`str`, *optional*):
                A path to a markdown file with optional Jinja template variables that can be filled
                in with `template_kwargs`. Defaults to the default template.

        Returns:
            [`huggingface_hub.ModelCard`]: A ModelCard instance with the specified card data and content from the
            template.

        Example:
            ```python
            >>> from huggingface_hub import ModelCard, ModelCardData, EvalResult

            >>> # Using the Default Template
            >>> card_data = ModelCardData(
            ...     language='en',
            ...     license='mit',
            ...     library_name='timm',
            ...     tags=['image-classification', 'resnet'],
            ...     datasets=['beans'],
            ...     metrics=['accuracy'],
            ... )
            >>> card = ModelCard.from_template(
            ...     card_data,
            ...     model_description='This model does x + y...'
            ... )

            >>> # Including Evaluation Results
            >>> card_data = ModelCardData(
            ...     language='en',
            ...     tags=['image-classification', 'resnet'],
            ...     eval_results=[
            ...         EvalResult(
            ...             task_type='image-classification',
            ...             dataset_type='beans',
            ...             dataset_name='Beans',
            ...             metric_type='accuracy',
            ...             metric_value=0.9,
            ...         ),
            ...     ],
            ...     model_name='my-cool-model',
            ... )
            >>> card = ModelCard.from_template(card_data)

            >>> # Using a Custom Template
            >>> card_data = ModelCardData(
            ...     language='en',
            ...     tags=['image-classification', 'resnet']
            ... )
            >>> card = ModelCard.from_template(
            ...     card_data=card_data,
            ...     template_path='./src/huggingface_hub/templates/modelcard_template.md',
            ...     custom_template_var='custom value',  # will be replaced in template if it exists
            ... )

            ```
        ©Úsuperr   ©rX   rp   rq   rr   r|   ©Ú	__class__r    r!   r   S  s    IzModelCard.from_template)NN)r€   r�   r‚   r   r:   rƒ   ry   rR   r‡   r   rN   r   Ú__classcell__r    r    rŒ   r!   rˆ   N  s     üürˆ   c                       s@   e Zd ZeZeZdZedee	e
 e	e
 dœ‡ fdd„ƒZ‡  ZS )ÚDatasetCardÚdatasetNro   c                    s   t ƒ j|||f|ŽS )a¬  Initialize a DatasetCard from a template. By default, it uses the default template, which can be found here:
        https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md

        Templates are Jinja2 templates that can be customized by passing keyword arguments.

        Args:
            card_data (`huggingface_hub.DatasetCardData`):
                A huggingface_hub.DatasetCardData instance containing the metadata you want to include in the YAML
                header of the dataset card on the Hugging Face Hub.
            template_path (`str`, *optional*):
                A path to a markdown file with optional Jinja template variables that can be filled
                in with `template_kwargs`. Defaults to the default template.

        Returns:
            [`huggingface_hub.DatasetCard`]: A DatasetCard instance with the specified card data and content from the
            template.

        Example:
            ```python
            >>> from huggingface_hub import DatasetCard, DatasetCardData

            >>> # Using the Default Template
            >>> card_data = DatasetCardData(
            ...     language='en',
            ...     license='mit',
            ...     annotations_creators='crowdsourced',
            ...     task_categories=['text-classification'],
            ...     task_ids=['sentiment-classification', 'text-scoring'],
            ...     multilinguality='monolingual',
            ...     pretty_name='My Text Classification Dataset',
            ... )
            >>> card = DatasetCard.from_template(
            ...     card_data,
            ...     pretty_name=card_data.pretty_name,
            ... )

            >>> # Using a Custom Template
            >>> card_data = DatasetCardData(
            ...     language='en',
            ...     license='mit',
            ... )
            >>> card = DatasetCard.from_template(
            ...     card_data=card_data,
            ...     template_path='./src/huggingface_hub/templates/datasetcard_template.md',
            ...     custom_template_var='custom value',  # will be replaced in template if it exists
            ... )

            ```
        r‰   r‹   rŒ   r    r!   r   ¤  s    9zDatasetCard.from_template)NN)r€   r�   r‚   r   r:   ÚTEMPLATE_DATASETCARD_PATHry   rR   r‡   r   rN   r   rŽ   r    r    rŒ   r!   r�   Ÿ  s     üür�   c                   @   s   e Zd ZeZeZdZdS )Ú	SpaceCardÚspaceN)r€   r�   r‚   r   r:   rƒ   ry   rR   r    r    r    r!   r’   à  s   r’   )úr#   ú
N)r   Úreturnc                 C   sV   |   d¡}|   d¡}|   d¡}|| dkr.dS ||krB||krBdS ||krNdS dS dS )zäDetect the line ending of a string. Used by RepoCard to avoid making huge diff on newlines.

    Uses same implementation as in Hub server, keep it in sync.

    Returns:
        str: The detected line ending of the string.
    r”   r#   r•   r   N)Úcount)r   ÚcrÚlfZcrlfr    r    r!   r&   æ  s    


r&   )Ú
local_pathr–   c                 C   sV   t | ƒ ¡ }t |¡}|rN| d¡}t |¡}|d ks@t|tƒrD|S t	dƒ‚nd S d S )Nr-   r.   )
r   rx   r/   r0   r1   r3   r4   r5   r6   r7   )rš   r   r=   r>   r(   r    r    r!   Úmetadata_loadû  s    



r›   )rš   r(   r–   c              	   C   sþ   d}d}t j | ¡rbt| dddd��8}| ¡ }t|jtƒrF|jd }nt|jtƒrX|j}W 5 Q R X t| dddd��‚}t	|d|d	�}t
 |¡}|rÆ|d
| ¡ … d|› |› d|› � || ¡ d
…  }nd|› |› d|› |› �}| |¡ | ¡  W 5 Q R X d
S )a&  
    Save the metadata dict in the upper YAML part Trying to preserve newlines as
    in the existing file. Docs about open() with newline="" parameter:
    https://docs.python.org/3/library/functions.html?highlight=open#open Does
    not work with "^M" linebreaks, which are replaced by 

    r#   rD   rT   Úutf8)rH   rI   r   rC   F)Ú	sort_keysr%   Nr$   )ÚosÚpathÚexistsrL   rW   r5   ÚnewlinesÚtuplerN   r   r/   r0   Ústartr2   rM   Úclose)rš   r(   r%   r   ZreadmeZ	data_yamlr=   Úoutputr    r    r!   Úmetadata_save  s"    
6
r¦   F)Úmetrics_configÚmetrics_verifiedÚdataset_configÚdataset_splitÚdataset_revisionÚmetrics_verification_token)Úmodel_pretty_nameÚtask_pretty_nameÚtask_idÚmetrics_pretty_nameÚ
metrics_idÚmetrics_valueÚdataset_pretty_nameÚ
dataset_idr§   r¨   r©   rª   r«   r¬   r–   c                 C   s0   dt | t|||||||||	||
||d�gd�iS )u  
    Creates a metadata dict with the result from a model evaluated on a dataset.

    Args:
        model_pretty_name (`str`):
            The name of the model in natural language.
        task_pretty_name (`str`):
            The name of a task in natural language.
        task_id (`str`):
            Example: automatic-speech-recognition. A task id.
        metrics_pretty_name (`str`):
            A name for the metric in natural language. Example: Test WER.
        metrics_id (`str`):
            Example: wer. A metric id from https://hf.co/metrics.
        metrics_value (`Any`):
            The value from the metric. Example: 20.0 or "20.0 Â± 1.2".
        dataset_pretty_name (`str`):
            The name of the dataset in natural language.
        dataset_id (`str`):
            Example: common_voice. A dataset id from https://hf.co/datasets.
        metrics_config (`str`, *optional*):
            The name of the metric configuration used in `load_metric()`.
            Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
        metrics_verified (`bool`, *optional*, defaults to `False`):
            Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
        dataset_config (`str`, *optional*):
            Example: fr. The name of the dataset configuration used in `load_dataset()`.
        dataset_split (`str`, *optional*):
            Example: test. The name of the dataset split used in `load_dataset()`.
        dataset_revision (`str`, *optional*):
            Example: 5503434ddd753f426f4b38109466949a1217c2bb. The name of the dataset dataset revision
            used in `load_dataset()`.
        metrics_verification_token (`bool`, *optional*):
            A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.

    Returns:
        `dict`: a metadata dict with the result from a model evaluated on a dataset.

    Example:
        ```python
        >>> from huggingface_hub import metadata_eval_result
        >>> results = metadata_eval_result(
        ...         model_pretty_name="RoBERTa fine-tuned on ReactionGIF",
        ...         task_pretty_name="Text Classification",
        ...         task_id="text-classification",
        ...         metrics_pretty_name="Accuracy",
        ...         metrics_id="accuracy",
        ...         metrics_value=0.2662102282047272,
        ...         dataset_pretty_name="ReactionJPEG",
        ...         dataset_id="julien-c/reactionjpeg",
        ...         dataset_config="default",
        ...         dataset_split="test",
        ... )
        >>> results == {
        ...     'model-index': [
        ...         {
        ...             'name': 'RoBERTa fine-tuned on ReactionGIF',
        ...             'results': [
        ...                 {
        ...                     'task': {
        ...                         'type': 'text-classification',
        ...                         'name': 'Text Classification'
        ...                     },
        ...                     'dataset': {
        ...                         'name': 'ReactionJPEG',
        ...                         'type': 'julien-c/reactionjpeg',
        ...                         'config': 'default',
        ...                         'split': 'test'
        ...                     },
        ...                     'metrics': [
        ...                         {
        ...                             'type': 'accuracy',
        ...                             'value': 0.2662102282047272,
        ...                             'name': 'Accuracy',
        ...                             'verified': False
        ...                         }
        ...                     ]
        ...                 }
        ...             ]
        ...         }
        ...     ]
        ... }
        True

        ```
    úmodel-index)Z	task_nameZ	task_typeÚmetric_nameÚmetric_typeÚmetric_valueZdataset_nameZdataset_typeZmetric_configÚverifiedÚverify_tokenr©   rª   r«   )Ú
model_nameÚeval_results)r   r   )r­   r®   r¯   r°   r±   r²   r³   r´   r§   r¨   r©   rª   r«   r¬   r    r    r!   Úmetadata_eval_result(  s*    i óÿþÿr½   )rR   Ú	overwriterS   rg   rh   ri   rj   rk   )rf   ÚmetadatarR   r¾   rS   rg   rh   ri   rj   rk   r–   c             
   C   sî  |dk	r|nd}|dks |dkr&t }
n*|dkr4t}
n|dkrBt}
ntd|› �ƒ‚z|
j| ||d�}W n0 tk
r”   |dkr„tdƒ‚|
 tƒ ¡}Y nX | ¡ D �]2\}}|d	k�rŒd
|d krÒt	|d| ƒ|d d
< t
|ƒ\}}|jjdkrü||j_||j_nŽ|jj}|D ]€}d}|D ]\}| |¡�r||k�rN|�sNtd|j› d|j› d�ƒ‚d}|j|_|jdk�r|j|_�q|�s|jj |¡ �qqž|j |¡dk	�rÈ|�sÈ|j |¡|k�rÈtd|› d�ƒ‚qž||j|< qž|j| |||||||	d�S )aã  
    Updates the metadata in the README.md of a repository on the Hugging Face Hub.
    If the README.md file doesn't exist yet, a new one is created with metadata and an
    the default ModelCard or DatasetCard template. For `space` repo, an error is thrown
    as a Space cannot exist without a `README.md` file.

    Args:
        repo_id (`str`):
            The name of the repository.
        metadata (`dict`):
            A dictionary containing the metadata to be updated.
        repo_type (`str`, *optional*):
            Set to `"dataset"` or `"space"` if updating to a dataset or space,
            `None` or `"model"` if updating to a model. Default is `None`.
        overwrite (`bool`, *optional*, defaults to `False`):
            If set to `True` an existing field can be overwritten, otherwise
            attempting to overwrite an existing field will cause an error.
        token (`str`, *optional*):
            The Hugging Face authentication token.
        commit_message (`str`, *optional*):
            The summary / title / first line of the generated commit. Defaults to
            `f"Update metadata with huggingface_hub"`
        commit_description (`str` *optional*)
            The description of the generated commit
        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 from `revision` with that commit.
            Defaults to `False`.
        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.
    Returns:
        `str`: URL of the commit which updated the card metadata.

    Example:
        ```python
        >>> from huggingface_hub import metadata_update
        >>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF',
        ...             'results': [{'dataset': {'name': 'ReactionGIF',
        ...                                      'type': 'julien-c/reactiongif'},
        ...                           'metrics': [{'name': 'Recall',
        ...                                        'type': 'recall',
        ...                                        'value': 0.7762102282047272}],
        ...                          'task': {'name': 'Text Classification',
        ...                                   'type': 'text-classification'}}]}]}
        >>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata)

        ```
    Nz$Update metadata with huggingface_hubr   r�   r“   zUnknown repo_type: )rS   rR   zJCannot update metadata on a Space that doesn't contain a `README.md` file.rµ   Únamer   r»   Fz6You passed a new value for the existing metric 'name: z, type: z6'. Set `overwrite=True` to overwrite existing metrics.Tz9You passed a new value for the existing meta data field 'z7'. Set `overwrite=True` to overwrite existing metadata.)rS   rR   rg   rh   rj   ri   rk   )rˆ   r�   r   r7   rY   r   r   r   ÚitemsÚgetattrr   r(   r¼   r»   Zis_equal_except_valuer¶   r·   r¸   r¹   rº   ÚappendÚgetrn   )rf   r¿   rR   r¾   rS   rg   rh   ri   rj   rk   Z
card_classZcardÚkeyÚvaluer»   Znew_resultsZexisting_resultsZ
new_resultZresult_foundZexisting_resultr    r    r!   Úmetadata_update¨  sh    D

ÿ*
ÿørÇ   )9rž   ÚreÚpathlibr   Útypingr   r   r   r   r   r   r_   r3   Zhuggingface_hub.file_downloadr	   Zhuggingface_hub.hf_apir
   Zhuggingface_hub.repocard_datar   r   r   r   r   r   r   Zhuggingface_hub.utilsr   r   r   rD   r   Úerrorsr   Úutilsr   r   r   Z
get_loggerr€   r8   Ú__file__rJ   rƒ   r‘   Úcompiler/   r   rˆ   r�   r’   rN   r&   r›   r¦   r„   r½   rÇ   r    r    r    r!   Ú<module>   sŽ    $	

  *QA*ñð õô