U
    &ºc[/  ã                   @   s’   d Z 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 e e¡Zdd	iZdd
diiZd
diZddgZG dd„ deƒZdS )z* Tokenization classes for Camembert model.é    N)Úcopyfile)ÚListÚOptionalé   )ÚPreTrainedTokenizer)ÚSPIECE_UNDERLINEÚ
vocab_filezsentencepiece.bpe.modelzcamembert-basezZhttps://s3.amazonaws.com/models.huggingface.co/bert/camembert-base-sentencepiece.bpe.modelz'Musixmatch/umberto-commoncrawl-cased-v1z'Musixmatch/umberto-wikipedia-uncased-v1c                	       sú   e Zd ZdZeZeZeZ	dgZ
ddddddddd	gf‡ fd
d„	Zd&ee eee  ee dœdd„Zd'ee eee  eee dœdd„Zd(ee eee  ee dœdd„Zedd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$d%„ Z‡  ZS ))ÚCamembertTokenizera!  
        Adapted from RobertaTokenizer and XLNetTokenizer
        SentencePiece based tokenizer. Peculiarities:

        - requires `SentencePiece <https://github.com/google/sentencepiece>`_

    This tokenizer inherits from :class:`~transformers.PreTrainedTokenizer` which contains most of the methods. Users
    should refer to the superclass for more information regarding methods.

    Args:
        vocab_file (:obj:`str`):
            Path to the vocabulary file.
        bos_token (:obj:`string`, `optional`, defaults to "<s>"):
            The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.

            .. note::

                When building a sequence using special tokens, this is not the token that is used for the beginning
                of sequence. The token used is the :obj:`cls_token`.
        eos_token (:obj:`string`, `optional`, defaults to "</s>"):
            The end of sequence token.

            .. note::

                When building a sequence using special tokens, this is not the token that is used for the end
                of sequence. The token used is the :obj:`sep_token`.
        sep_token (:obj:`string`, `optional`, defaults to "</s>"):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
            for sequence classification or for a text and a question for question answering.
            It is also used as the last token of a sequence built with special tokens.
        cls_token (:obj:`string`, `optional`, defaults to "<s>"):
            The classifier token which is used when doing sequence classification (classification of the whole
            sequence instead of per-token classification). It is the first token of the sequence when built with
            special tokens.
        unk_token (:obj:`string`, `optional`, defaults to "<unk>"):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        pad_token (:obj:`string`, `optional`, defaults to "<pad>"):
            The token used for padding, for example when batching sequences of different lengths.
        mask_token (:obj:`string`, `optional`, defaults to "<mask>"):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        additional_special_tokens (:obj:`List[str]`, `optional`, defaults to :obj:`["<s>NOTUSED", "</s>NOTUSED"]`):
            Additional special tokens used by the tokenizer.

    Attributes:
        sp_model (:obj:`SentencePieceProcessor`):
            The `SentencePiece` processor that is used for every conversion (string, tokens and IDs).
    Zattention_maskz<s>z</s>ú<unk>ú<pad>ú<mask>ú
<s>NOTUSEDú</s>NOTUSEDc
                    s–   t ƒ jf d||||||||	dœ	|
—Ž t ¡ | _| j t|ƒ¡ || _dddddœ| _t	| jƒ| _
t	| jƒt	| jƒ | jd< d	d
„ | j ¡ D ƒ| _d S )Ni   )	Úmax_lenÚ	bos_tokenÚ	eos_tokenÚ	unk_tokenÚ	sep_tokenÚ	cls_tokenÚ	pad_tokenÚ
mask_tokenÚadditional_special_tokensr   r   é   é   )r   r   r   r
   r   c                 S   s   i | ]\}}||“qS © r   )Ú.0ÚkÚvr   r   úG/tmp/pip-unpacked-wheel-ymerj3tt/transformers/tokenization_camembert.pyÚ
<dictcomp>Œ   s      z/CamembertTokenizer.__init__.<locals>.<dictcomp>)ÚsuperÚ__init__ÚspmÚSentencePieceProcessorÚsp_modelÚLoadÚstrr   Úfairseq_tokens_to_idsÚlenÚfairseq_offsetÚitemsÚfairseq_ids_to_tokens)Úselfr   r   r   r   r   r   r   r   r   Úkwargs©Ú	__class__r   r   r!   k   s(    ÷
ö
zCamembertTokenizer.__init__N)Útoken_ids_0Útoken_ids_1Úreturnc                 C   sD   |dkr| j g| | jg S | j g}| jg}|| | | | | S )aÓ  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks
        by concatenating and adding special tokens.
        A CamemBERT sequence has the following format:

        - single sequence: ``<s> X </s>``
        - pair of sequences: ``<s> A </s></s> B </s>``

        Args:
            token_ids_0 (:obj:`List[int]`):
                List of IDs to which the special tokens will be added
            token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
                Optional second list of IDs for sequence pairs.

        Returns:
            :obj:`List[int]`: list of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
        N)Úcls_token_idÚsep_token_id)r,   r0   r1   ÚclsÚsepr   r   r   Ú build_inputs_with_special_tokensŽ   s
    z3CamembertTokenizer.build_inputs_with_special_tokensF)r0   r1   Úalready_has_special_tokensr2   c                    s|   |r*|dk	rt dƒ‚tt‡ fdd„|ƒƒS |dkrLdgdgt|ƒ  dg S dgdgt|ƒ  ddg dgt|ƒ  dg S )a  
        Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer ``prepare_for_model`` or ``encode_plus`` methods.

        Args:
            token_ids_0 (:obj:`List[int]`):
                List of ids.
            token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
                Set to True if the token list is already formatted with special tokens for the model

        Returns:
            :obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        Nz~You should not supply a second sequence if the provided sequence of ids is already formated with special tokens for the model.c                    s   | ˆ j ˆ jfkrdS dS )Nr   r   )r4   r3   )Úx©r,   r   r   Ú<lambda>Á   ó    z<CamembertTokenizer.get_special_tokens_mask.<locals>.<lambda>r   r   )Ú
ValueErrorÚlistÚmapr(   )r,   r0   r1   r8   r   r:   r   Úget_special_tokens_mask©   s    ÿz*CamembertTokenizer.get_special_tokens_maskc                 C   sP   | j g}| jg}|dkr.t|| | ƒdg S t|| | | | | ƒdg S )a  
        Creates a mask from the two sequences passed to be used in a sequence-pair classification task.
        CamemBERT, like RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.

        Args:
            token_ids_0 (:obj:`List[int]`):
                List of ids.
            token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
                Optional second list of IDs for sequence pairs.

        Returns:
            :obj:`List[int]`: List of zeros.

        Nr   )r4   r3   r(   )r,   r0   r1   r6   r5   r   r   r   Ú$create_token_type_ids_from_sequencesÇ   s
    z7CamembertTokenizer.create_token_type_ids_from_sequencesc                 C   s   t | jƒt | jƒ S ©N)r(   r'   r$   r:   r   r   r   Ú
vocab_sizeß   s    zCamembertTokenizer.vocab_sizec                 C   s   | j  |¡S rB   )r$   ZEncodeAsPieces)r,   Útextr   r   r   Ú	_tokenizeã   s    zCamembertTokenizer._tokenizec                 C   s<   || j kr| j | S | j |¡dkr*| jS | j| j |¡ S )z2 Converts a token (str) in an id using the vocab. r   )r'   r$   Z	PieceToIdZunk_token_idr)   )r,   Útokenr   r   r   Ú_convert_token_to_idæ   s
    

z'CamembertTokenizer._convert_token_to_idc                 C   s&   || j kr| j | S | j || j ¡S )z=Converts an index (integer) in a token (str) using the vocab.)r+   r$   Z	IdToPiecer)   )r,   Úindexr   r   r   Ú_convert_id_to_tokenï   s    

z'CamembertTokenizer._convert_id_to_tokenc                 C   s   | j  ¡ }d |d< |S )Nr$   )Ú__dict__Úcopy)r,   Ústater   r   r   Ú__getstate__õ   s    
zCamembertTokenizer.__getstate__c                 C   sP   || _ zdd l}W n  tk
r2   t d¡ ‚ Y nX | ¡ | _| j | j¡ d S )Nr   zzYou need to install SentencePiece to use AlbertTokenizer: https://github.com/google/sentencepiecepip install sentencepiece)	rJ   ÚsentencepieceÚImportErrorÚloggerÚwarningr#   r$   r%   r   )r,   Údr"   r   r   r   Ú__setstate__ú   s    ÿ
zCamembertTokenizer.__setstate__c                 C   s   d  |¡ td¡ ¡ }|S )zIConverts a sequence of tokens (strings for sub-words) in a single string.Ú ú )ÚjoinÚreplacer   Ústrip)r,   ÚtokensZ
out_stringr   r   r   Úconvert_tokens_to_string  s    z+CamembertTokenizer.convert_tokens_to_stringc                 C   s^   t j |¡s t d |¡¡ dS t j |td ¡}t j | j	¡t j |¡krXt
| j	|ƒ |fS )a2  
        Save the sentencepiece vocabulary (copy original file) and special tokens file to a directory.

        Args:
            save_directory (:obj:`str`):
                The directory in which to save the vocabulary.

        Returns:
            :obj:`Tuple(str)`: Paths to the files saved.
        z*Vocabulary path ({}) should be a directoryNr   )ÚosÚpathÚisdirrP   ÚerrorÚformatrV   ÚVOCAB_FILES_NAMESÚabspathr   r   )r,   Zsave_directoryZout_vocab_filer   r   r   Úsave_vocabulary  s    z"CamembertTokenizer.save_vocabulary)N)NF)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r`   Zvocab_files_namesÚPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_mapÚ&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesZmodel_input_namesr!   r   Úintr   r7   Úboolr@   rA   ÚpropertyrC   rE   rG   rI   rM   rS   rZ   rb   Ú__classcell__r   r   r.   r   r	   3   sV   2ö$ ÿ 
þ   ÿ 
 þ ÿ 
þ
	r	   )rf   Úloggingr[   Úshutilr   Útypingr   r   rN   r"   Ztokenization_utilsr   Ztokenization_xlnetr   Ú	getLoggerrc   rP   r`   rg   rh   ZSHARED_MODEL_IDENTIFIERSr	   r   r   r   r   Ú<module>   s*   
 ÿÿ ÿü