U
    ”Ê¹j"…  ã                   @   sN  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 d dlmZmZ e e¡ZeG dd„ dƒƒZeG dd	„ d	ƒƒZe	eeee f  e	e ee d
œdd„ZG dd„ deƒZG dd„ deƒZG dd„ deƒZeeeef  e
eee f dœdd„Zdd„ Zeee eeeef  dœdd„Ze	ee  e	ee  dœdd„ZdS )é    N)Údefaultdict)Ú	dataclass)ÚAnyÚDictÚListÚOptionalÚTupleÚUnion)ÚloggingÚ	yaml_dumpc                   @   s:  e Zd ZU dZeed< eed< eed< eed< eed< dZee ed< dZ	ee ed	< dZ
ee ed
< dZee ed< dZeeeef  ed< dZee ed< dZee ed< dZeeeef  ed< dZee ed< dZee ed< dZee ed< dZee ed< eedœdd„ƒZd edœdd„Zddœdd„ZdS )Ú
EvalResultuï  
    Flattened representation of individual evaluation results found in model-index of Model Cards.

    For more information on the model-index spec, see https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1.

    Args:
        task_type (`str`):
            The task identifier. Example: "image-classification".
        dataset_type (`str`):
            The dataset identifier. Example: "common_voice". Use dataset id from https://hf.co/datasets.
        dataset_name (`str`):
            A pretty name for the dataset. Example: "Common Voice (French)".
        metric_type (`str`):
            The metric identifier. Example: "wer". Use metric id from https://hf.co/metrics.
        metric_value (`Any`):
            The metric value. Example: 0.9 or "20.0 Â± 1.2".
        task_name (`str`, *optional*):
            A pretty name for the task. Example: "Speech Recognition".
        dataset_config (`str`, *optional*):
            The name of the dataset configuration used in `load_dataset()`.
            Example: fr in `load_dataset("common_voice", "fr")`. See the `datasets` docs for more info:
            https://hf.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name
        dataset_split (`str`, *optional*):
            The split used in `load_dataset()`. Example: "test".
        dataset_revision (`str`, *optional*):
            The revision (AKA Git Sha) of the dataset used in `load_dataset()`.
            Example: 5503434ddd753f426f4b38109466949a1217c2bb
        dataset_args (`Dict[str, Any]`, *optional*):
            The arguments passed during `Metric.compute()`. Example for `bleu`: `{"max_order": 4}`
        metric_name (`str`, *optional*):
            A pretty name for the metric. Example: "Test WER".
        metric_config (`str`, *optional*):
            The name of the metric configuration used in `load_metric()`.
            Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
            See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations
        metric_args (`Dict[str, Any]`, *optional*):
            The arguments passed during `Metric.compute()`. Example for `bleu`: max_order: 4
        verified (`bool`, *optional*):
            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.
        verify_token (`str`, *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.
        source_name (`str`, *optional*):
            The name of the source of the evaluation result. Example: "Open LLM Leaderboard".
        source_url (`str`, *optional*):
            The URL of the source of the evaluation result. Example: "https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard".
    Ú	task_typeÚdataset_typeÚdataset_nameÚmetric_typeÚmetric_valueNÚ	task_nameÚdataset_configÚdataset_splitÚdataset_revisionÚdataset_argsÚmetric_nameÚmetric_configÚmetric_argsÚverifiedÚverify_tokenÚsource_nameÚ
source_url©Úreturnc                 C   s   | j | j| j| j| jfS )z9Returns a tuple that uniquely identifies this evaluation.)r   r   r   r   r   ©Úself© r"   ú\/var/www/html/bwave/python/venv/lib/python3.8/site-packages/huggingface_hub/repocard_data.pyÚunique_identifier†   s    ûzEvalResult.unique_identifier)Úotherr   c                 C   sD   | j  ¡ D ]4\}}|dkrq
|dkr
t| |ƒt||ƒkr
 dS q
dS )zx
        Return True if `self` and `other` describe exactly the same metric but with a
        different value.
        r   r   FT)Ú__dict__ÚitemsÚgetattr)r!   r%   ÚkeyÚ_r"   r"   r#   Úis_equal_except_value‘   s    z EvalResult.is_equal_except_valuec                 C   s    | j d k	r| jd krtdƒ‚d S )NzAIf `source_name` is provided, `source_url` must also be provided.)r   r   Ú
ValueErrorr    r"   r"   r#   Ú__post_init__Ÿ   s    zEvalResult.__post_init__)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚstrÚ__annotations__r   r   r   r   r   r   r   r   r   r   r   r   Úboolr   r   r   ÚpropertyÚtupler$   r+   r-   r"   r"   r"   r#   r      s,   
3
r   c                   @   sÂ   e Zd ZdZd"edœdd„Zdd„ Zdd	„ Zd#ee	e
  e
dœdd„Zdd„ Zdd„ Zd$e
eedœdd„Zd%e
eedœdd„Ze
edœdd„Ze
ed
dœdd„Ze
edœdd„Zedœd d!„Zd
S )&ÚCardDataa¦  Structure containing metadata from a RepoCard.

    [`CardData`] is the parent class of [`ModelCardData`] and [`DatasetCardData`].

    Metadata can be exported as a dictionary or YAML. Export can be customized to alter the representation of the data
    (example: flatten evaluation results). `CardData` behaves as a dictionary (can get, pop, set values) but do not
    inherit from `dict` to allow this export step.
    F)Úignore_metadata_errorsc                 K   s   | j  |¡ d S ©N)r&   Úupdate)r!   r8   Úkwargsr"   r"   r#   Ú__init__¯   s    zCardData.__init__c                 C   s(   t  | j¡}|  |¡ dd„ | ¡ D ƒS )zÂConverts CardData to a dict.

        Returns:
            `dict`: CardData represented as a dictionary ready to be dumped to a YAML
            block for inclusion in a README.md file.
        c                 S   s   i | ]\}}|d k	r||“qS r9   r"   )Ú.0r)   Úvaluer"   r"   r#   Ú
<dictcomp>¼   s       z$CardData.to_dict.<locals>.<dictcomp>)ÚcopyÚdeepcopyr&   Ú_to_dictr'   ©r!   Z	data_dictr"   r"   r#   Úto_dict²   s    
zCardData.to_dictc                 C   s   dS )zÍUse this method in child classes to alter the dict representation of the data. Alter the dict in-place.

        Args:
            data_dict (`dict`): The raw dict representation of the card data.
        Nr"   rC   r"   r"   r#   rB   ¾   s    zCardData._to_dictN)Úoriginal_orderr   c                    sH   |r2‡ fdd„|t tˆ j ¡ ƒt|ƒ ƒ D ƒˆ _tˆ  ¡ d|d� ¡ S )a
  Dumps CardData to a YAML block for inclusion in a README.md file.

        Args:
            line_break (str, *optional*):
                The line break to use when dumping to yaml.

        Returns:
            `str`: CardData represented as a YAML block.
        c                    s"   i | ]}|ˆ j kr|ˆ j | “qS r"   ©r&   )r=   Úkr    r"   r#   r?   Ñ   s   
þ z$CardData.to_yaml.<locals>.<dictcomp>F)Ú	sort_keysÚ
line_break)ÚlistÚsetr&   Úkeysr   rD   Ústrip)r!   rI   rE   r"   r    r#   Úto_yamlÆ   s
    

þzCardData.to_yamlc                 C   s
   t | jƒS r9   )Úreprr&   r    r"   r"   r#   Ú__repr__Ø   s    zCardData.__repr__c                 C   s   |   ¡ S r9   )rN   r    r"   r"   r#   Ú__str__Û   s    zCardData.__str__)r)   Údefaultr   c                 C   s   | j  |¡}|dkr|S |S )ú#Get value for a given metadata key.N)r&   Úget)r!   r)   rR   r>   r"   r"   r#   rT   Þ   s    zCardData.getc                 C   s   | j  ||¡S )z#Pop value for a given metadata key.)r&   Úpop)r!   r)   rR   r"   r"   r#   rU   ã   s    zCardData.pop)r)   r   c                 C   s
   | j | S )rS   rF   ©r!   r)   r"   r"   r#   Ú__getitem__ç   s    zCardData.__getitem__)r)   r>   r   c                 C   s   || j |< dS )z#Set value for a given metadata key.NrF   )r!   r)   r>   r"   r"   r#   Ú__setitem__ë   s    zCardData.__setitem__c                 C   s
   || j kS )z%Check if a given metadata key is set.rF   rV   r"   r"   r#   Ú__contains__ï   s    zCardData.__contains__r   c                 C   s
   t | jƒS )z'Return the number of metadata keys set.)Úlenr&   r    r"   r"   r#   Ú__len__ó   s    zCardData.__len__)F)NN)N)N)r.   r/   r0   r1   r4   r<   rD   rB   r   r   r2   rN   rP   rQ   r   rT   rU   rW   rX   rY   Úintr[   r"   r"   r"   r#   r7   ¤   s   	r7   )Úeval_resultsÚ
model_namer   c                 C   s`   | d krg S t | tƒr| g} t | tƒr8tdd„ | D ƒƒsLtdt| ƒ› d�ƒ‚|d kr\tdƒ‚| S )Nc                 s   s   | ]}t |tƒV  qd S r9   )Ú
isinstancer   )r=   Úrr"   r"   r#   Ú	<genexpr>   s     z)_validate_eval_results.<locals>.<genexpr>zM`eval_results` should be of type `EvalResult` or a list of `EvalResult`, got Ú.z7Passing `eval_results` requires `model_name` to be set.)r_   r   rJ   Úallr,   Útype)r]   r^   r"   r"   r#   Ú_validate_eval_resultsø   s    
ÿre   c                       sÄ   e Zd ZdZddddddddddddddœeeeee f  eeeee f  eee  eeeee f  ee ee ee ee eee  ee ee eee  e	dœ‡ fdd„Z
dd„ Z‡  ZS )	ÚModelCardDataaQ  Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md

    Args:
        base_model (`str` or `List[str]`, *optional*):
            The identifier of the base model from which the model derives. This is applicable for example if your model is a
            fine-tune or adapter of an existing model. The value must be the ID of a model on the Hub (or a list of IDs
            if your model derives from multiple models). Defaults to None.
        datasets (`Union[str, List[str]]`, *optional*):
            Dataset or list of datasets that were used to train this model. Should be a dataset ID
            found on https://hf.co/datasets. Defaults to None.
        eval_results (`Union[List[EvalResult], EvalResult]`, *optional*):
            List of `huggingface_hub.EvalResult` that define evaluation results of the model. If provided,
            `model_name` is used to as a name on PapersWithCode's leaderboards. Defaults to `None`.
        language (`Union[str, List[str]]`, *optional*):
            Language of model's training data or metadata. It must be an ISO 639-1, 639-2 or
            639-3 code (two/three letters), or a special value like "code", "multilingual". Defaults to `None`.
        library_name (`str`, *optional*):
            Name of library used by this model. Example: keras or any library from
            https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts.
            Defaults to None.
        license (`str`, *optional*):
            License of this model. Example: apache-2.0 or any license from
            https://huggingface.co/docs/hub/repositories-licenses. Defaults to None.
        license_name (`str`, *optional*):
            Name of the license of this model. Defaults to None. To be used in conjunction with `license_link`.
            Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a name. In that case, use `license` instead.
        license_link (`str`, *optional*):
            Link to the license of this model. Defaults to None. To be used in conjunction with `license_name`.
            Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a link. In that case, use `license` instead.
        metrics (`List[str]`, *optional*):
            List of metrics used to evaluate this model. Should be a metric name that can be found
            at https://hf.co/metrics. Example: 'accuracy'. Defaults to None.
        model_name (`str`, *optional*):
            A name for this model. It is used along with
            `eval_results` to construct the `model-index` within the card's metadata. The name
            you supply here is what will be used on PapersWithCode's leaderboards. If None is provided
            then the repo name is used as a default. Defaults to None.
        pipeline_tag (`str`, *optional*):
            The pipeline tag associated with the model. Example: "text-classification".
        tags (`List[str]`, *optional*):
            List of tags to add to your model that can be used when filtering on the Hugging
            Face Hub. Defaults to None.
        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.
        kwargs (`dict`, *optional*):
            Additional metadata that will be added to the model card. Defaults to None.

    Example:
        ```python
        >>> from huggingface_hub import ModelCardData
        >>> card_data = ModelCardData(
        ...     language="en",
        ...     license="mit",
        ...     library_name="timm",
        ...     tags=['image-classification', 'resnet'],
        ... )
        >>> card_data.to_dict()
        {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']}

        ```
    NF)Ú
base_modelÚdatasetsr]   ÚlanguageÚlibrary_nameÚlicenseÚlicense_nameÚlicense_linkÚmetricsr^   Úpipeline_tagÚtagsr8   c             
      sF  || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
t|ƒ| _| dd ¡}|rÈzt|ƒ\}
}|
| _	|| _W nN ttfk
rÆ } z,|ržt d¡ ntd|j› d|› d�ƒ‚W 5 d }~X Y nX tƒ jf |Ž | j�rBzt| j| j	ƒ| _W nN tk
�r@ } z.|�r t d|› d�¡ ntd|› �ƒ|‚W 5 d }~X Y nX d S )Númodel-indexz<Invalid model-index. Not loading eval results into CardData.z4Invalid `model_index` in metadata cannot be parsed: ú z–. Pass `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning: some information will be lost. Use it at your own risk.z!Failed to validate eval_results: z). Not loading eval results into CardData.)rg   rh   r]   ri   rj   rk   rl   rm   rn   r^   ro   Ú_to_unique_listrp   rU   Úmodel_index_to_eval_resultsÚKeyErrorÚ	TypeErrorÚloggerÚwarningr,   Ú	__class__Úsuperr<   re   Ú	Exception)r!   rg   rh   r]   ri   rj   rk   rl   rm   rn   r^   ro   rp   r8   r;   Úmodel_indexÚerrorÚe©ry   r"   r#   r<   I  s@    

ÿzModelCardData.__init__c                 C   s,   | j dk	r(t| j| j ƒ|d< |d= |d= dS )z[Format the internal data dict. In this case, we convert eval results to a valid model indexNrq   r]   r^   )r]   Úeval_results_to_model_indexr^   rC   r"   r"   r#   rB   ƒ  s    
zModelCardData._to_dict)r.   r/   r0   r1   r   r	   r2   r   r   r4   r<   rB   Ú__classcell__r"   r"   r   r#   rf   	  s<   Bñ


ñ:rf   c                       s  e Zd ZdZdddddddddddddddœeeeee f  eeeee f  eeeee f  eeeee f  eeeee f  eeeee f  eee  eeeee f  eeeee f  ee ee ee eeeee f  e	dœ‡ fdd„Z
dd„ Z‡  ZS )	ÚDatasetCardDataa×	  Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md

    Args:
        language (`List[str]`, *optional*):
            Language of dataset's data or metadata. It must be an ISO 639-1, 639-2 or
            639-3 code (two/three letters), or a special value like "code", "multilingual".
        license (`Union[str, List[str]]`, *optional*):
            License(s) of this dataset. Example: apache-2.0 or any license from
            https://huggingface.co/docs/hub/repositories-licenses.
        annotations_creators (`Union[str, List[str]]`, *optional*):
            How the annotations for the dataset were created.
            Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'no-annotation', 'other'.
        language_creators (`Union[str, List[str]]`, *optional*):
            How the text-based data in the dataset was created.
            Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'other'
        multilinguality (`Union[str, List[str]]`, *optional*):
            Whether the dataset is multilingual.
            Options are: 'monolingual', 'multilingual', 'translation', 'other'.
        size_categories (`Union[str, List[str]]`, *optional*):
            The number of examples in the dataset. Options are: 'n<1K', '1K<n<10K', '10K<n<100K',
            '100K<n<1M', '1M<n<10M', '10M<n<100M', '100M<n<1B', '1B<n<10B', '10B<n<100B', '100B<n<1T', 'n>1T', and 'other'.
        source_datasets (`List[str]]`, *optional*):
            Indicates whether the dataset is an original dataset or extended from another existing dataset.
            Options are: 'original' and 'extended'.
        task_categories (`Union[str, List[str]]`, *optional*):
            What categories of task does the dataset support?
        task_ids (`Union[str, List[str]]`, *optional*):
            What specific tasks does the dataset support?
        paperswithcode_id (`str`, *optional*):
            ID of the dataset on PapersWithCode.
        pretty_name (`str`, *optional*):
            A more human-readable name for the dataset. (ex. "Cats vs. Dogs")
        train_eval_index (`Dict`, *optional*):
            A dictionary that describes the necessary spec for doing evaluation on the Hub.
            If not provided, it will be gathered from the 'train-eval-index' key of the kwargs.
        config_names (`Union[str, List[str]]`, *optional*):
            A list of the available dataset configs for the dataset.
    NF)ri   rk   Úannotations_creatorsÚlanguage_creatorsÚmultilingualityÚsize_categoriesÚsource_datasetsÚtask_categoriesÚtask_idsÚpaperswithcode_idÚpretty_nameÚtrain_eval_indexÚconfig_namesr8   c                   sl   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
|| _|pV| dd ¡| _tƒ jf |Ž d S )Nútrain-eval-index)rƒ   r„   ri   rk   r…   r†   r‡   rˆ   r‰   rŠ   r‹   r�   rU   rŒ   rz   r<   )r!   ri   rk   rƒ   r„   r…   r†   r‡   rˆ   r‰   rŠ   r‹   rŒ   r�   r8   r;   r   r"   r#   r<   ²  s    zDatasetCardData.__init__c                 C   s   |  d¡|d< d S )NrŒ   rŽ   )rU   rC   r"   r"   r#   rB   Ö  s    zDatasetCardData._to_dict)r.   r/   r0   r1   r   r	   r2   r   r   r4   r<   rB   r�   r"   r"   r   r#   r‚   Š  s@   *ð
ð$r‚   c                       s�   e Zd ZdZdddddddddddddœee ee ee ee ee ee ee ee eee  eee  eee  edœ‡ fdd„Z	‡  Z
S )ÚSpaceCardDataaè	  Space Card Metadata that is used by Hugging Face Hub when included at the top of your README.md

    To get an exhaustive reference of Spaces configuration, please visit https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference.

    Args:
        title (`str`, *optional*)
            Title of the Space.
        sdk (`str`, *optional*)
            SDK of the Space (one of `gradio`, `streamlit`, `docker`, or `static`).
        sdk_version (`str`, *optional*)
            Version of the used SDK (if Gradio/Streamlit sdk).
        python_version (`str`, *optional*)
            Python version used in the Space (if Gradio/Streamlit sdk).
        app_file (`str`, *optional*)
            Path to your main application file (which contains either gradio or streamlit Python code, or static html code).
            Path is relative to the root of the repository.
        app_port (`str`, *optional*)
            Port on which your application is running. Used only if sdk is `docker`.
        license (`str`, *optional*)
            License of this model. Example: apache-2.0 or any license from
            https://huggingface.co/docs/hub/repositories-licenses.
        duplicated_from (`str`, *optional*)
            ID of the original Space if this is a duplicated Space.
        models (List[`str`], *optional*)
            List of models related to this Space. Should be a dataset ID found on https://hf.co/models.
        datasets (`List[str]`, *optional*)
            List of datasets related to this Space. Should be a dataset ID found on https://hf.co/datasets.
        tags (`List[str]`, *optional*)
            List of tags to add to your Space that can be used when filtering on the Hub.
        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.
        kwargs (`dict`, *optional*):
            Additional metadata that will be added to the space card.

    Example:
        ```python
        >>> from huggingface_hub import SpaceCardData
        >>> card_data = SpaceCardData(
        ...     title="Dreambooth Training",
        ...     license="mit",
        ...     sdk="gradio",
        ...     duplicated_from="multimodalart/dreambooth-training"
        ... )
        >>> card_data.to_dict()
        {'title': 'Dreambooth Training', 'sdk': 'gradio', 'license': 'mit', 'duplicated_from': 'multimodalart/dreambooth-training'}
        ```
    NF)ÚtitleÚsdkÚsdk_versionÚpython_versionÚapp_fileÚapp_portrk   Úduplicated_fromÚmodelsrh   rp   r8   c                   sX   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	t
|ƒ| _tƒ jf |Ž d S r9   )r�   r‘   r’   r“   r”   r•   rk   r–   r—   rh   rs   rp   rz   r<   )r!   r�   r‘   r’   r“   r”   r•   rk   r–   r—   rh   rp   r8   r;   r   r"   r#   r<     s    
zSpaceCardData.__init__)r.   r/   r0   r1   r   r2   r\   r   r4   r<   r�   r"   r"   r   r#   r�   Ú  s6   4ò


òr�   )r|   r   c                 C   sF  g }| D �]2}|d }|d }|D �]}|d d }|d   d¡}|d d }|d d }	|d   d¡}
|d   d¡}|d   d¡}|d   d	¡}|  d
i ¡  d¡}|  d
i ¡  d¡}|d D ]z}|d }|d }|  d¡}|  d	¡}|  d¡}|  d¡}|  d¡}t|||	||||
||||||||||d�}| |¡ q¾q"q||fS )aÂ  Takes in a model index and returns the model name and a list of `huggingface_hub.EvalResult` objects.

    A detailed spec of the model index can be found here:
    https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1

    Args:
        model_index (`List[Dict[str, Any]]`):
            A model index data structure, likely coming from a README.md file on the
            Hugging Face Hub.

    Returns:
        model_name (`str`):
            The name of the model as found in the model index. This is used as the
            identifier for the model on leaderboards like PapersWithCode.
        eval_results (`List[EvalResult]`):
            A list of `huggingface_hub.EvalResult` objects containing the metrics
            reported in the provided model_index.

    Example:
        ```python
        >>> from huggingface_hub.repocard_data import model_index_to_eval_results
        >>> # Define a minimal model index
        >>> model_index = [
        ...     {
        ...         "name": "my-cool-model",
        ...         "results": [
        ...             {
        ...                 "task": {
        ...                     "type": "image-classification"
        ...                 },
        ...                 "dataset": {
        ...                     "type": "beans",
        ...                     "name": "Beans"
        ...                 },
        ...                 "metrics": [
        ...                     {
        ...                         "type": "accuracy",
        ...                         "value": 0.9
        ...                     }
        ...                 ]
        ...             }
        ...         ]
        ...     }
        ... ]
        >>> model_name, eval_results = model_index_to_eval_results(model_index)
        >>> model_name
        'my-cool-model'
        >>> eval_results[0].task_type
        'image-classification'
        >>> eval_results[0].metric_type
        'accuracy'

        ```
    ÚnameÚresultsÚtaskrd   ÚdatasetÚconfigÚsplitÚrevisionÚargsÚsourceÚurlrn   r>   r   ÚverifyToken)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )rT   r   Úappend)r|   r]   Úelemr˜   r™   Úresultr   r   r   r   r   r   r   r   r   r   Zmetricr   r   r   r   r   r   r   Úeval_resultr"   r"   r#   rt   +  sX    8






ïrt   c                 C   sR   t | tttfƒr&t| ƒdd„ | D ƒƒS t | tƒrJt| ƒdd„ |  ¡ D ƒƒS | S dS )zk
    Recursively remove `None` values from a dict. Borrowed from: https://stackoverflow.com/a/20558778
    c                 s   s   | ]}|d k	rt |ƒV  qd S r9   ©Ú_remove_none)r=   Úxr"   r"   r#   ra   ˜  s      z_remove_none.<locals>.<genexpr>c                 s   s2   | ]*\}}|d k	r|d k	rt |ƒt |ƒfV  qd S r9   r§   )r=   rG   Úvr"   r"   r#   ra   š  s       N)r_   rJ   r6   rK   rd   Údictr'   )Úobjr"   r"   r#   r¨   “  s
    
r¨   )r^   r]   r   c           
   	   C   sÄ   t tƒ}|D ]}||j  |¡ qg }| ¡ D ]€}|d }|j|jdœ|j|j|j	|j
|j|jdœdd„ |D ƒdœ}|jdk	r¤d|ji}|jdk	rœ|j|d	< ||d
< | |¡ q.| |dœg}	t|	ƒS )a°  Takes in given model name and list of `huggingface_hub.EvalResult` and returns a
    valid model-index that will be compatible with the format expected by the
    Hugging Face Hub.

    Args:
        model_name (`str`):
            Name of the model (ex. "my-cool-model"). This is used as the identifier
            for the model on leaderboards like PapersWithCode.
        eval_results (`List[EvalResult]`):
            List of `huggingface_hub.EvalResult` objects containing the metrics to be
            reported in the model-index.

    Returns:
        model_index (`List[Dict[str, Any]]`): The eval_results converted to a model-index.

    Example:
        ```python
        >>> from huggingface_hub.repocard_data import eval_results_to_model_index, EvalResult
        >>> # Define minimal eval_results
        >>> eval_results = [
        ...     EvalResult(
        ...         task_type="image-classification",  # Required
        ...         dataset_type="beans",  # Required
        ...         dataset_name="Beans",  # Required
        ...         metric_type="accuracy",  # Required
        ...         metric_value=0.9,  # Required
        ...     )
        ... ]
        >>> eval_results_to_model_index("my-cool-model", eval_results)
        [{'name': 'my-cool-model', 'results': [{'task': {'type': 'image-classification'}, 'dataset': {'name': 'Beans', 'type': 'beans'}, 'metrics': [{'type': 'accuracy', 'value': 0.9}]}]}]

        ```
    r   )rd   r˜   )r˜   rd   rœ   r�   rž   rŸ   c              
   S   s.   g | ]&}|j |j|j|j|j|j|jd œ‘qS ))rd   r>   r˜   rœ   rŸ   r   r¢   )r   r   r   r   r   r   r   )r=   r¥   r"   r"   r#   Ú
<listcomp>Ú  s   
øùz/eval_results_to_model_index.<locals>.<listcomp>)rš   r›   rn   Nr¡   r˜   r    )r˜   r™   )r   rJ   r$   r£   Úvaluesr   r   r   r   r   r   r   r   r   r   r¨   )
r^   r]   Ztask_and_ds_types_mapr¦   Zmodel_index_datar™   Zsample_resultÚdatar    r|   r"   r"   r#   r€   Ÿ  sB    %þú
öó
 ÿ

þÿr€   )rp   r   c                 C   s0   | d kr| S g }| D ]}||kr|  |¡ q|S r9   )r£   )rp   Zunique_tagsÚtagr"   r"   r#   rs   û  s    rs   )r@   Úcollectionsr   Údataclassesr   Útypingr   r   r   r   r   r	   Zhuggingface_hub.utilsr
   r   Z
get_loggerr.   rw   r   r7   r2   re   rf   r‚   r�   rt   r¨   r€   rs   r"   r"   r"   r#   Ú<module>   s,    
 Tý PQ(h"\