U
    &ºc‰'  ã                   @   sp   d Z ddlZddlZ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mZ e e¡ZG dd„ dƒZdS )z( Configuration base class and utilities.é    Né   )Ú!ALL_PRETRAINED_CONFIG_ARCHIVE_MAP)ÚCONFIG_NAMEÚMODEL_CARD_NAMEÚTF2_WEIGHTS_NAMEÚWEIGHTS_NAMEÚcached_pathÚhf_bucket_urlÚis_remote_urlc                   @   sl   e Zd ZdZdd„ Zdd„ Zedd„ ƒZedd	„ ƒZed
d„ ƒZ	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ ZdS )Ú	ModelCarda{   Structured Model Card class.
        Store model card as well as methods for loading/downloading/saving model cards.

        Please read the following paper for details and explanation on the sections:
            "Model Cards for Model Reporting"
                by Margaret Mitchell, Simone Wu,
                Andrew Zaldivar, Parker Barnes, Lucy Vasserman, Ben Hutchinson, Elena Spitzer,
                Inioluwa Deborah Raji and Timnit Gebru for the proposal behind model cards.
            Link: https://arxiv.org/abs/1810.03993

        Note:
            A model card can be loaded and saved to disk.

        Parameters:
    c                 K   sà   |  di ¡| _|  di ¡| _|  di ¡| _|  di ¡| _|  di ¡| _|  di ¡| _|  di ¡| _|  di ¡| _|  d	i ¡| _	| 
¡ D ]T\}}zt| ||ƒ W q† tk
rØ } zt d
 ||| ¡¡ |‚W 5 d }~X Y q†X q†d S )NÚmodel_detailsÚintended_useÚfactorsÚmetricsÚevaluation_dataÚtraining_dataÚquantitative_analysesÚethical_considerationsÚcaveats_and_recommendationsz!Can't set {} with value {} for {})Úpopr   r   r   r   r   r   r   r   r   ÚitemsÚsetattrÚAttributeErrorÚloggerÚerrorÚformat)ÚselfÚkwargsÚkeyÚvalueÚerr© r!   ú:/tmp/pip-unpacked-wheel-ymerj3tt/transformers/modelcard.pyÚ__init__7   s    zModelCard.__init__c                 C   s>   t j |¡rt j |t¡}n|}|  |¡ t d |¡¡ dS )zU Save a model card object to the directory or file `save_directory_or_file`.
        zModel card saved in {}N)	ÚosÚpathÚisdirÚjoinr   Úto_json_filer   Úinfor   )r   Zsave_directory_or_fileZoutput_model_card_filer!   r!   r"   Úsave_pretrainedK   s
    
zModelCard.save_pretrainedc              	   K   sª  |  dd¡}|  dd¡}|  dd¡}|  dd¡}|tkrBt| }nDtj |¡r^tj |t¡}n(tj |¡srt|ƒrx|}nt	|tdd}|s’|tkr¶| 
tt¡}| 
tt¡}| 
tt¡}zXt||d|dd	}|dkrÖt‚||krðt d
 |¡¡ nt d ||¡¡ |  |¡}	W n" ttjfk
r0   | ƒ }	Y nX g }
| ¡ D ],\}}t|	|ƒr>t|	||ƒ |
 |¡ q>|
D ]}|  |d¡ qpt dt|	ƒ¡ |r¢|	|fS |	S dS )a,   Instantiate a :class:`~transformers.ModelCard` from a pre-trained model model card.

        Parameters:
            pretrained_model_name_or_path: either:

                - a string with the `shortcut name` of a pre-trained model card to load from cache or download, e.g.: ``bert-base-uncased``.
                - a string with the `identifier name` of a pre-trained model card that was user-uploaded to our S3, e.g.: ``dbmdz/bert-base-german-cased``.
                - a path to a `directory` containing a model card file saved using the :func:`~transformers.ModelCard.save_pretrained` method, e.g.: ``./my_model_directory/``.
                - a path or url to a saved model card JSON `file`, e.g.: ``./my_model_directory/modelcard.json``.

            cache_dir: (`optional`) string:
                Path to a directory in which a downloaded pre-trained model
                card should be cached if the standard cache should not be used.

            kwargs: (`optional`) dict: key/value pairs with which to update the ModelCard object after loading.

                - The values in kwargs of any keys which are model card attributes will be used to override the loaded values.
                - Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the `return_unused_kwargs` keyword parameter.

            proxies: (`optional`) dict, default None:
                A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.
                The proxies are used on each request.

            find_from_standard_name: (`optional`) boolean, default True:
                If the pretrained_model_name_or_path ends with our standard model or config filenames, replace them with our standard modelcard filename.
                Can be used to directly feed a model/config url and access the colocated modelcard.

            return_unused_kwargs: (`optional`) bool:

                - If False, then this function returns just the final model card object.
                - If True, then this functions returns a tuple `(model card, unused_kwargs)` where `unused_kwargs` is a dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of kwargs which has not been used to update `ModelCard` and is otherwise ignored.

        Examples::

            modelcard = ModelCard.from_pretrained('bert-base-uncased')    # Download model card from S3 and cache.
            modelcard = ModelCard.from_pretrained('./test/saved_model/')  # E.g. model card was saved using `save_pretrained('./test/saved_model/')`
            modelcard = ModelCard.from_pretrained('./test/saved_model/modelcard.json')
            modelcard = ModelCard.from_pretrained('bert-base-uncased', output_attention=True, foo=False)

        Ú	cache_dirNÚproxiesÚfind_from_standard_nameTÚreturn_unused_kwargsF)ÚfilenameZuse_cdn)r+   Zforce_downloadr,   Zresume_downloadzloading model card file {}z+loading model card file {} from cache at {}zModel card: %s)r   r   r$   r%   r&   r'   r   Úisfiler
   r	   Úreplacer   r   r   r   ÚEnvironmentErrorr   r)   r   Úfrom_json_fileÚjsonÚJSONDecodeErrorr   Úhasattrr   ÚappendÚstr)ÚclsZpretrained_model_name_or_pathr   r+   r,   r-   r.   Zmodel_card_fileZresolved_model_card_fileZ	modelcardZ	to_remover   r   r!   r!   r"   Úfrom_pretrainedW   sX    *
    ÿ
ÿzModelCard.from_pretrainedc                 C   s
   | f |ŽS )z@Constructs a `ModelCard` from a Python dictionary of parameters.r!   )r9   Zjson_objectr!   r!   r"   Ú	from_dict¹   s    zModelCard.from_dictc              	   C   s6   t |ddd}| ¡ }W 5 Q R X t |¡}| f |ŽS )z8Constructs a `ModelCard` from a json file of parameters.Úrúutf-8©Úencoding)ÚopenÚreadr4   Úloads)r9   Z	json_fileÚreaderÚtextÚdict_objr!   r!   r"   r3   ¾   s    
zModelCard.from_json_filec                 C   s   | j |j kS ©N)Ú__dict__)r   Úotherr!   r!   r"   Ú__eq__Æ   s    zModelCard.__eq__c                 C   s   t |  ¡ ƒS rF   )r8   Úto_json_string©r   r!   r!   r"   Ú__repr__É   s    zModelCard.__repr__c                 C   s   t  | j¡}|S )z0Serializes this instance to a Python dictionary.)ÚcopyÚdeepcopyrG   )r   Úoutputr!   r!   r"   Úto_dictÌ   s    zModelCard.to_dictc                 C   s   t j|  ¡ dddd S )z*Serializes this instance to a JSON string.é   T)ÚindentÚ	sort_keysÚ
)r4   ÚdumpsrP   rK   r!   r!   r"   rJ   Ñ   s    zModelCard.to_json_stringc              	   C   s,   t |ddd}| |  ¡ ¡ W 5 Q R X dS )z# Save this instance to a json file.Úwr=   r>   N)r@   ÚwriterJ   )r   Zjson_file_pathÚwriterr!   r!   r"   r(   Õ   s    zModelCard.to_json_fileN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r#   r*   Úclassmethodr:   r;   r3   rI   rL   rP   rJ   r(   r!   r!   r!   r"   r   &   s   
a

r   )r\   rM   r4   Úloggingr$   Zconfiguration_autor   Z
file_utilsr   r   r   r   r   r	   r
   Ú	getLoggerrY   r   r   r!   r!   r!   r"   Ú<module>   s   $
