§
    }Štj‹  ã                   ó  — d dl Z d dlZd dlmZ d dlmZ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mZmZmZmZ d dlmZmZ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 j"        e#¦  «        Z$ ee%¦  «        j&        dz  dz  Z' ee%¦  «        j&        dz  dz  Z( ej)        d¦  «        Z* G d„ d¦  «        Z+ G d„ de+¦  «        Z, G d„ de+¦  «        Z- G d„ de+¦  «        Z.de/ded         fd„Z0de/ez  de1dz  fd„Z2de/ez  de1ddfd„Z3dd ddddd!œd"e/d#e/d$e/d%e/d&e/d'ed(e/d)e/d*e/dz  d+e4d,e/dz  d-e/dz  d.e/dz  d/e/dz  de1fd0„Z5e!dd ddddd dd1œd2e/d3e1d4e/dz  d5e4d6e/dz  d7e/dz  d8e/dz  d9e/dz  d:e4d;e/dz  de/fd<„¦   «         Z6dS )=é    N)ÚPath)ÚAnyÚLiteral)Úhf_hub_download)Úupload_file)ÚCardDataÚDatasetCardDataÚ
EvalResultÚModelCardDataÚSpaceCardDataÚeval_results_to_model_indexÚmodel_index_to_eval_results)ÚHfHubHTTPErrorÚget_sessionÚhf_raise_for_statusÚis_jinja_availableÚ	yaml_dumpé   )Ú	constants)ÚEntryNotFoundError)ÚSoftTemporaryDirectoryÚloggingÚvalidate_hf_hub_argsÚ	templateszmodelcard_template.mdzdatasetcard_template.mdzE^(\s*---(?:\r\n|\r|\n))([\S\s]*?)((?:\r\n|\r|\n)---[ \t]*(\r\n|\n|$))c                   ón  — e Zd ZeZeZdZddede	fd„Z
ed„ ¦   «         Zej        defd„¦   «         Zd„ Zd	eez  fd
„Ze	 	 	 ddeez  dedz  dedz  de	fd„¦   «         Zddedz  fd„Z	 	 	 	 	 	 	 ddededz  dedz  dedz  dedz  dedz  de	dz  dedz  fd„Ze	 	 d dededz  dedz  fd„¦   «         ZdS )!ÚRepoCardÚmodelFÚcontentÚignore_metadata_errorsc                 ó"   — || _         || _        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   s      úV/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/huggingface_hub/repocard.pyÚ__init__zRepoCard.__init__*   s   € ðD '=ˆÔ#ØˆŒˆˆó    c                 ó’   — t          | j        ¦  «        pd}d|› | j                             || j        ¬¦  «        › |› d|› | j        › �S )zLThe content of the RepoCard, including the YAML block and the Markdown body.ú
ú---)Ú
line_breakÚoriginal_order)Ú_detect_line_endingÚ_contentÚdataÚto_yamlÚ_original_orderÚtext)r!   r(   s     r"   r   zRepoCard.contentO   sƒ   € õ )¨¬Ñ7Ô7Ð?¸4ˆ
ð W�Zð  W ¤×!2Ò!2¸jÐY]ÔYmÐ!2Ñ!nÔ!nð  WÐpzð  Wð  Wð  @Jð  Wð  LPô  LUð  Wð  Wð  	Wr$   c                 óú  — || _         t                               |¦  «        }|rs|                     d¦  «        }||                     ¦   «         d…         | _        t          j        |¦  «        }|€i }t          |t          ¦  «        st          d¦  «        ‚n#t                               d¦  «         i }|| _         | j        di |¤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_blockÚ	data_dicts        r"   r   zRepoCard.contentU   sú   € ð  ˆŒå ×'Ò'¨Ñ0Ô0ˆØð 	 àŸš Q™œˆJØ §	¢	¡¤  Ô.ˆDŒIÝœ zÑ2Ô2ˆIàÐ Ø�	õ ˜i­Ñ.Ô.ð NÝ Ð!LÑMÔMÐMðNõ �NŠNÐ_Ñ`Ô`Ð`ØˆIØˆDŒIà(�DÔ(ÐiÐi¨9ÐiÐiÈTÔMhÐiÐiÐiˆŒ	Ý# I§N¢NÑ$4Ô$4Ñ5Ô5ˆÔÐÐr$   c                 ó   — | j         S ©N)r   )r!   s    r"   Ú__str__zRepoCard.__str__p   s
   € ØŒ|Ðr$   Úfilepathc                 óø   — t          |¦  «        }|j                             dd¬¦  «         t          |ddd¬¦  «        5 }|                     t          | ¦  «        ¦  «         ddd¦  «         dS # 1 swxY w Y   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!   rH   Úfs      r"   ÚsavezRepoCard.saves   sº   € õ ˜‘>”>ˆØŒ×Ò d°TÐÑ:Ô:Ð:å�( ¨b¸7ÐCÑCÔCð 	ÀqØ�GŠG•C˜‘I”IÑÔÐð	ð 	ð 	ñ 	ô 	ð 	ð 	ð 	ð 	ð 	ð 	ð 	øøøð 	ð 	ð 	ð 	ð 	ð 	s   ¿#A/Á/A3Á6A3NÚrepo_id_or_pathÚ	repo_typeÚtokenc                 óº  — t          |¦  «                             ¦   «         rt          |¦  «        }nZt          |t          ¦  «        r2t          t	          |t
          j        |p| j        |¬¦  «        ¦  «        }nt          d|› d�¦  «        ‚| 	                    ddd¬¦  «        5 } | | 
                    ¦   «         |¬¦  «        cd	d	d	¦  «         S # 1 swxY w Y   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 "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"]

            ```
        )r[   r\   z.Cannot load RepoCard: path not found on disk (z).ÚrrM   rN   rO   )r   N)r   Úis_filer:   rW   r   r   ÚREPOCARD_NAMEr[   r<   rU   Úread)ÚclsrZ   r[   r\   r   Ú	card_pathrX   s          r"   ÚloadzRepoCard.load‡   sB  € õH �Ñ Ô ×(Ò(Ñ*Ô*ð 	cÝ˜_Ñ-Ô-ˆIˆIÝ˜­Ñ-Ô-ð 
	cÝÝØ#ÝÔ+Ø'Ð8¨3¬=Øð	ñ ô ñô ˆIˆIõ ÐaÈoÐaÐaÐaÑbÔbÐbð �^Š^ ¨b¸7ˆ^ÑCÔCð 	PÀqØ�3�q—v’v‘x”xÐ8NÐOÑOÔOð	Pð 	Pð 	Pð 	Pñ 	Pô 	Pð 	Pð 	Pð 	Pð 	Pð 	Pð 	Pøøøð 	Pð 	Pð 	Pð 	Pð 	Pð 	Ps   Â$CÃCÃCc                 ó  — |p| j         }|t          | ¦  «        dœ}ddi}	 t          ¦   «                              d||¬¦  «        }t	          |¦  «         dS # t
          $ r&}|j        dk    rt          |j        ¦  «        ‚|‚d}~ww xY w)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.
        )ÚrepoTyper   ÚAcceptz
text/plainz(https://huggingface.co/api/validate-yaml)ÚjsonÚheadersi�  N)	r[   rW   r   Úpostr   r   Ústatus_coder<   r/   )r!   r[   Úbodyri   ÚresponseÚexcs         r"   ÚvalidatezRepoCard.validate½   s²   € ð( Ð/ ¤ˆ	ð "Ý˜4‘y”yð
ð 
ˆð ˜\Ð*ˆð	Ý"‘}”}×)Ò)Ð*TÐ[_ÐipÐ)ÑqÔqˆHÝ Ñ)Ô)Ð)Ð)Ð)øÝð 	ð 	ð 	ØÔ# sÒ*Ð*Ý  ¤Ñ/Ô/Ð/à�	øøøøð		øøøs   ¡3A Á
BÁ !BÂBÚrepo_idÚcommit_messageÚcommit_descriptionÚrevisionÚ	create_prÚparent_commitc	                 óp  — |p| j         }|                      |¬¦  «         t          ¦   «         5 }	t          |	¦  «        t          j        z  }
|
                     t          | ¦  «        d¬¦  «         t          t          |
¦  «        t          j        ||||||||¬¦
  «
        }ddd¦  «         n# 1 swxY w Y   |S )aB  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 too concurrently.
        Returns:
            `str`: URL of the commit which updated the card metadata.
        )r[   rN   )rR   )
Úpath_or_fileobjÚpath_in_reporp   r\   r[   rq   rr   rt   rs   ru   N)	r[   ro   r   r   r   r`   Ú
write_textrW   r   )r!   rp   r\   r[   rq   rr   rs   rt   ru   ÚtmpdirÚtmp_pathÚurls               r"   Úpush_to_hubzRepoCard.push_to_hubâ   sù   € ðR Ð/ ¤ˆ	ð 	�Š 	ˆÑ*Ô*Ð*å#Ñ%Ô%ð 	¨Ý˜F‘|”|¥iÔ&=Ñ=ˆHØ×Ò¥ D¡	¤	°GÐÑ<Ô<Ð<ÝÝ # H¡¤Ý&Ô4ØØØ#Ø-Ø#5Ø#Ø!Ø+ðñ ô ˆCð	ð 	ð 	ñ 	ô 	ð 	ð 	ð 	ð 	ð 	ð 	øøøð 	ð 	ð 	ð 	ð ˆ
s   ®A1B+Â+B/Â2B/Ú	card_dataÚtemplate_pathÚtemplate_strc                 óÔ  — t          ¦   «         rddl}nt          d¦  «        ‚|                     ¦   «                              ¦   «         }|                     |¦  «         |�!t          |¦  «                             ¦   «         }|€&t          | j        ¦  «                             ¦   «         }| 	                    |¦  «        } |j
        d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.
            template_str (`str`, *optional*):
                A raw Jinja template string with optional variables. Used when neither `template_path`
                nor the default template is appropriate. Ignored if `template_path` is also provided.

        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`.r~   r3   )r   Újinja2ÚImportErrorÚto_dictÚcopyÚupdater   Ú	read_textÚdefault_template_pathÚTemplateÚrenderr-   )	rb   r~   r   r€   Útemplate_kwargsr‚   ÚkwargsÚtemplater   s	            r"   Úfrom_templatezRepoCard.from_template!  sí   € õ6 ÑÔð 	ØˆMˆMˆMˆMåð9ñô ð ð
 ×"Ò"Ñ$Ô$×)Ò)Ñ+Ô+ˆØ�Š�oÑ&Ô&Ð&àÐ$Ý Ñ.Ô.×8Ò8Ñ:Ô:ˆLØÐÝ Ô 9Ñ:Ô:×DÒDÑFÔFˆLØ—?’? <Ñ0Ô0ˆØ!�(”/ÐJÐJ¨I×,=Ò,=Ñ,?Ô,?ÐJÀ6ÐJÐJˆØˆs�7‰|Œ|Ðr$   )F)NNFrF   )NNNNNNN©NN)Ú__name__Ú
__module__Ú__qualname__r   r?   ÚTEMPLATE_MODELCARD_PATHrˆ   r[   rW   Úboolr#   Úpropertyr   ÚsetterrG   r   rY   Úclassmethodrd   ro   r}   rŽ   r3   r$   r"   r   r   %   s>  € € € € € Ø€OØ3ÐØ€Ið#ð # ð #¸Tð #ð #ð #ð #ðJ ðWð Wñ „XðWð
 „^ð6˜sð 6ð 6ð 6ñ „^ð6ð4ð ð ð˜T C™Zð ð ð ð ð( ð !%Ø Ø',ð3Pð 3Pà˜t™ð3Pð ˜‘:ð3Pð �T‰zð	3Pð
 !%ð3Pð 3Pð 3Pñ „[ð3Pðj#ð # #¨¡*ð #ð #ð #ð #ðP !Ø $Ø%)Ø)-Ø#Ø!%Ø$(ð=ð =àð=ð �T‰zð=ð ˜‘:ð	=ð
 ˜d™
ð=ð   $™Jð=ð ˜‘*ð=ð ˜$‘;ð=ð ˜T‘zð=ð =ð =ð =ð~ ð %)Ø#'ð	+ð +àð+ð ˜T‘zð+ð ˜D‘jð	+ð +ð +ñ „[ð+ð +ð +r$   r   c            	       óZ   ‡ — e Zd ZeZeZdZe	 	 ddede	dz  de	dz  fˆ fd„¦   «         Z
ˆ xZS )Ú	ModelCardr   Nr~   r   r€   c                 ó<   •—  t          ¦   «         j        |||fi |¤Ž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.
            template_str (`str`, *optional*):
                A raw Jinja template string with optional variables. Used when neither `template_path`
                nor the default template is appropriate. Ignored if `template_path` is also provided.

        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Ž   ©rb   r~   r   r€   r‹   Ú	__class__s        €r"   rŽ   zModelCard.from_templateU  s)   ø€ ðX %�u‰wŒwÔ$ Y°¸|Ð_Ð_ÈÐ_Ð_Ð_r$   r�   )r�   r‘   r’   r   r?   r“   rˆ   r[   r—   rW   rŽ   Ú__classcell__©rž   s   @r"   r™   r™   P  s¤   ø€ € € € € Ø#€OØ3ÐØ€Iàð %)Ø#'ð	K`ð K`à ðK`ð ˜T‘zðK`ð ˜D‘jð	K`ð K`ð K`ð K`ð K`ñ „[ðK`ð K`ð K`ð K`ð K`r$   r™   c            	       óZ   ‡ — e Zd ZeZeZdZe	 	 ddede	dz  de	dz  fˆ fd„¦   «         Z
ˆ xZS )ÚDatasetCardÚdatasetNr~   r   r€   c                 ó<   •—  t          ¦   «         j        |||fi |¤Ž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.
            template_str (`str`, *optional*):
                A raw Jinja template string with optional variables. Used when neither `template_path`
                nor the default template is appropriate. Ignored if `template_path` is also provided.

        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�   s        €r"   rŽ   zDatasetCard.from_template©  s)   ø€ ðx %�u‰wŒwÔ$ Y°¸|Ð_Ð_ÈÐ_Ð_Ð_r$   r�   )r�   r‘   r’   r	   r?   ÚTEMPLATE_DATASETCARD_PATHrˆ   r[   r—   rW   rŽ   rŸ   r    s   @r"   r¢   r¢   ¤  s–   ø€ € € € € Ø%€OØ5ÐØ€Iàð %)Ø#'ð	;`ð ;`à"ð;`ð ˜T‘zð;`ð ˜D‘jð	;`ð ;`ð ;`ð ;`ð ;`ñ „[ð;`ð ;`ð ;`ð ;`ð ;`r$   r¢   c                   ó   — e Zd ZeZeZdZdS )Ú	SpaceCardÚspaceN)r�   r‘   r’   r   r?   r“   rˆ   r[   r3   r$   r"   r§   r§   è  s   € € € € € Ø#€OØ3ÐØ€I€I€Ir$   r§   r   Úreturn)úr&   ú
Nc                 óÆ   — |                       d¦  «        }|                       d¦  «        }|                       d¦  «        }||z   dk    rdS ||k    r||k    rdS ||k    r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ÚlfÚcrlfs       r"   r*   r*   î  sr   € ð 
�Š�tÑ	Ô	€BØ	�Š�tÑ	Ô	€BØ�=Š=˜Ñ Ô €DØ	ˆB�w�!‚|€|ØˆtØˆr‚z€z�d˜b’j�jØˆvØ	ˆB‚w€wØˆtàˆtr$   Ú
local_pathc                 ó"  — t          | ¦  «                             ¦   «         }t                               |¦  «        }|rQ|                     d¦  «        }t          j        |¦  «        }|�t          |t          ¦  «        r|S t          d¦  «        ‚d S )Nr1   r2   )
r   r‡   r4   r5   r6   r8   r9   r:   r;   r<   )r±   r   rB   rC   r,   s        r"   Úmetadata_loadr³     s€   € Ý�:ÑÔ×(Ò(Ñ*Ô*€GÝ×#Ò# GÑ,Ô,€EØð Ø—[’[ ‘^”^ˆ
ÝŒ~˜jÑ)Ô)ˆØˆ<�: d­DÑ1Ô1ˆ<ØˆKÝÐDÑEÔEÐEàˆtr$   r,   c                 ó  — d}d}t           j                             | ¦  «        r‡t          | dd¬¦  «        5 }|                     ¦   «         }t          |j        t          ¦  «        r|j        d         }n!t          |j        t          ¦  «        r|j        }ddd¦  «         n# 1 swxY w Y   t          | ddd¬¦  «        5 }t          |d|¬	¦  «        }t                               |¦  «        }|rE|d|                     ¦   «         …         d
|› |› d
|› �z   ||                     ¦   «         d…         z   }nd
|› |› d
|› |› �}|                     |¦  «         |                     ¦   «          ddd¦  «         dS # 1 swxY w Y   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&   rM   Úutf8)rQ   rR   r   NrL   F)Ú	sort_keysr(   r'   )ÚosÚpathÚexistsrU   ra   r:   ÚnewlinesÚtuplerW   r   r4   r5   Ústartr7   rV   Úclose)r±   r,   r(   r   ÚreadmeÚ	data_yamlrB   Úoutputs           r"   Úmetadata_saverÁ     s  € ð €JØ€Gå	„w‡~‚~�jÑ!Ô!ð -Ý�* b°6Ð:Ñ:Ô:ð 	-¸fØ—k’k‘m”mˆGÝ˜&œ/­5Ñ1Ô1ð -Ø#œ_¨QÔ/�
�
Ý˜FœO­SÑ1Ô1ð -Ø#œ_�
ð	-ð 	-ð 	-ñ 	-ô 	-ð 	-ð 	-ð 	-ð 	-ð 	-ð 	-øøøð 	-ð 	-ð 	-ð 	-õ 
ˆj˜# r°FÐ	;Ñ	;Ô	;ð 
¸vÝ˜d¨eÀ
ÐKÑKÔKˆ	å ×'Ò'¨Ñ0Ô0ˆØð 	KØ˜_˜uŸ{š{™}œ}˜_Ô-Ð0\°jÐ0\À)Ð0\Ð0\ÐPZÐ0\Ð0\Ñ\Ð_fÐgl×gpÒgpÑgrÔgrÐgtÐgtÔ_uÑuˆFˆFàJ˜:ÐJ yÐJÐJ°ZÐJÀÐJÐJˆFà�Š�VÑÔÐØ�Š‰Œˆð
ð 
ð 
ñ 
ô 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
øøøð 
ð 
ð 
ð 
ð 
ð 
s%   ¶AB Â B$Â'B$Â>B)E4Å4E8Å;E8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Ç   c                 ó^   — dt          | t          |||||||||	||
||¬¦  «        g¬¦  «        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)Ú	task_nameÚ	task_typeÚmetric_nameÚmetric_typeÚmetric_valueÚdataset_nameÚdataset_typeÚ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Ç   s                 r"   Úmetadata_eval_resultrÞ   0  se   € ðR 	Õ2Ø(åØ.Ø%Ø 3Ø *Ø!.Ø!4Ø!+Ø"0Ø-Ø!;Ø#1Ø"/Ø%5ðñ ô ðð
ñ 
ô 
ðð r$   )r[   Ú	overwriter\   rq   rr   rs   rt   ru   rp   Úmetadatar[   rß   r\   rq   rr   rs   rt   ru   c          
      ób  — |�|nd}|�|dk    rt           }
n.|dk    rt          }
n |dk    rt          }
nt          d|› �¦  «        ‚	 |
                     | ||¬¦  «        }nF# t
          $ r9 |dk    rt          d¦  «        ‚|
                     t          ¦   «         ¦  «        }Y nw xY w|                     ¦   «         D �]Y\  }}|d	k    röd
|d         vrt          |d| ¦  «        |d         d
<   t          |¦  «        \  }}|j        j        €||j        _        ||j        _        Œg|j        j        }|D ]Š}d}|D ]b}|                     |¦  «        rK||k    r"|s t          d|j        › d|j        › d�¦  «        ‚d}|j        |_        |j        du r|j        |_        Œc|s|j        j                             |¦  «         Œ‹�Œ|j                             |¦  «        �3|s1|j                             |¦  «        |k    rt          d|› d�¦  «        ‚||j        |<   �Œ[|                     | |||||||	¬¦  «        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
    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 too 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: )r\   r[   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.)r\   r[   rq   rr   rt   rs   ru   )r™   r¢   r   r<   rd   r   rŽ   r   ÚitemsÚgetattrr   r,   rÝ   rÜ   Úis_equal_except_valuerÔ   rÕ   rÖ   rÚ   rÛ   ÚappendÚgetr}   )rp   rà   r[   rß   r\   rq   rr   rs   rt   ru   Ú
card_classÚcardÚkeyÚvaluerÜ   Únew_resultsÚexisting_resultsÚ
new_resultÚresult_foundÚexisting_results                       r"   Úmetadata_updaterñ   °  s÷  € ðH (6Ð'A�^�^ÐGm€Nð Ð˜I¨Ò0Ð0Ýˆ
ˆ
Ø	�iÒ	Ð	Ý ˆ
ˆ
Ø	�gÒ	Ð	Ýˆ
ˆ
åÐ:¨yÐ:Ð:Ñ;Ô;Ð;ð4Ø�Š˜w¨e¸yˆÑIÔIˆˆøÝð 4ð 4ð 4Ø˜ÒÐÝÐiÑjÔjÐjð ×'Ò'­©
¬
Ñ3Ô3ˆˆˆð4øøøð —n’nÑ&Ô&ð +'ñ +'‰
ˆˆUØ�-ÒÐà˜U 1œXÐ%Ð%Ý#*¨4°¸wÑ#GÔ#G��a”˜Ñ Ý&AÀ%Ñ&HÔ&HÑ#ˆJ˜ØŒyÔ%Ð-Ø)4�”	Ô&Ø'1�”	Ô$Ð$à#'¤9Ô#9Ð ð #.ð Bð B�JØ#(�LØ+;ð Wð W˜Ø%×;Ò;¸OÑLÔLð WØ)¨_Ò<Ð<ÀYÐ<Ý&0ð%FØ/9Ô/Eð%Fð %Fà'1Ô'=ð%Fð %Fð %Fñ'"ô '"ð !"ð ,0˜LØ;EÔ;R˜OÔ8Ø.Ô7¸4Ð?Ð?Ø?IÔ?V Ô <øØ'ð BØœ	Ô.×5Ò5°jÑAÔAÐAøñ!Bð& Œy�}Š}˜SÑ!Ô!Ð-°iÐ-ÀDÄIÇMÂMÐRUÑDVÔDVÐZ_ÒD_ÐD_Ý ðLÐPSð Lð Lð Lñô ð ð
 "'�”	˜#‘‘à×ÒØØØØ%Ø-ØØØ#ð ñ 	ô 	ð 	s   ÁA ÁA B"Â!B")7r·   ÚreÚpathlibr   Útypingr   r   r8   Úhuggingface_hub.file_downloadr   Úhuggingface_hub.hf_apir   Úhuggingface_hub.repocard_datar   r	   r
   r   r   r   r   Úhuggingface_hub.utilsr   r   r   r   r   rM   r   Úerrorsr   Úutilsr   r   r   Ú
get_loggerr�   r=   Ú__file__rS   r“   r¥   Úcompiler4   r   r™   r¢   r§   rW   r*   r;   r³   rÁ   r”   rÞ   rñ   r3   r$   r"   ú<module>rþ      s¿  ðØ 	€	€	€	Ø 	€	€	€	Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ð Ð à €€€à 9Ð 9Ð 9Ð 9Ð 9Ð 9Ø .Ð .Ð .Ð .Ð .Ð .ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð rÐ qÐ qÐ qÐ qÐ qÐ qÐ qÐ qÐ qÐ qÐ qÐ qÐ qà Ð Ð Ð Ð Ð Ø &Ð &Ð &Ð &Ð &Ð &Ø HÐ HÐ HÐ HÐ HÐ HÐ HÐ HÐ HÐ Hð 
ˆÔ	˜HÑ	%Ô	%€ð ˜$˜x™.œ.Ô/°+Ñ=Ð@WÑWÐ Ø ˜D ™NœNÔ1°KÑ?ÐB[Ñ[Ð ð �2”:ÐfÑgÔgÐ ðhð hð hð hð hñ hô hð hðV	Q`ð Q`ð Q`ð Q`ð Q`�ñ Q`ô Q`ð Q`ðhA`ð A`ð A`ð A`ð A`�(ñ A`ô A`ð A`ðHð ð ð ð �ñ ô ð ð ð ¨Ð1IÔ)Jð ð ð ð ð*
˜c D™jð 
¨T°D©[ð 
ð 
ð 
ð 
ð˜c D™jð °ð ¸ð ð ð ð ðT "&Ø"Ø!%Ø $Ø#'Ø-1ð}ð }ð }àð}ð ð}ð ð	}ð
 ð}ð ð}ð ð}ð ð}ð ð}ð ˜$‘Jð}ð ð}ð ˜$‘Jð}ð ˜‘:ð}ð ˜D‘jð}ð !$ d¡
ð}ð  
ð!}ð }ð }ð }ð@ ð
 !ØØØ!%Ø%)ØØØ $ðRð Rð RØðRàðRð �T‰zð	Rð
 ðRð �‰:ðRð ˜$‘JðRð ˜d™
ðRð �D‰jðRð ðRð ˜‘:ðRð 	ðRð Rð Rñ ÔðRð Rð Rr$   