U
    &ce5                     @   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m	Z	 ddl
mZ eeZdd	iZdd
ddddddiZdddddddZG dd de	ZdS )z, Tokenization classes for XLM-RoBERTa model.    N)copyfile)ListOptional   )PreTrainedTokenizer)SPIECE_UNDERLINE
vocab_filezsentencepiece.bpe.modelz\https://s3.amazonaws.com/models.huggingface.co/bert/xlm-roberta-base-sentencepiece.bpe.modelz]https://s3.amazonaws.com/models.huggingface.co/bert/xlm-roberta-large-sentencepiece.bpe.modelzuhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-roberta-large-finetuned-conll02-dutch-sentencepiece.bpe.modelzwhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-roberta-large-finetuned-conll02-spanish-sentencepiece.bpe.modelzwhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-roberta-large-finetuned-conll03-english-sentencepiece.bpe.modelzvhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-roberta-large-finetuned-conll03-german-sentencepiece.bpe.model)zxlm-roberta-basezxlm-roberta-largez)xlm-roberta-large-finetuned-conll02-dutchz+xlm-roberta-large-finetuned-conll02-spanishz+xlm-roberta-large-finetuned-conll03-englishz*xlm-roberta-large-finetuned-conll03-germani   c                       s   e Zd ZdZeZeZeZ	dgZ
d& fdd		Zd
d Z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  ZS )*XLMRobertaTokenizera!  
        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_mask<s></s><unk><pad><mask>c	              
      s   t  jf |||||||d|	 zdd l}
W n  tk
rN   td  Y nX |
 | _| jt	| || _
ddddd| _d| _t| j| j | jd< d	d
 | j D | _d S )N)	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokenr   ~You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiecepip install sentencepiecer         )r
   r   r   r   r   c                 S   s   i | ]\}}||qS  r   ).0kvr   r   I/tmp/pip-unpacked-wheel-ymerj3tt/transformers/tokenization_xlm_roberta.py
<dictcomp>   s      z0XLMRobertaTokenizer.__init__.<locals>.<dictcomp>)super__init__sentencepieceImportErrorloggerwarningSentencePieceProcessorsp_modelLoadstrr   fairseq_tokens_to_idsfairseq_offsetlenitemsfairseq_ids_to_tokens)selfr   r   r   r   r   r   r   r   kwargsspm	__class__r   r   r    l   s2    
	zXLMRobertaTokenizer.__init__c                 C   s   | j  }d |d< |S )Nr&   )__dict__copy)r.   stater   r   r   __getstate__   s    
z XLMRobertaTokenizer.__getstate__c                 C   sP   || _ zdd l}W n  tk
r2   td  Y nX | | _| j| j d S )Nr   r   )	r3   r!   r"   r#   r$   r%   r&   r'   r   )r.   dr0   r   r   r   __setstate__   s    
z XLMRobertaTokenizer.__setstate__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 XLM-R 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.   r9   r:   clssepr   r   r    build_inputs_with_special_tokens   s
    z4XLMRobertaTokenizer.build_inputs_with_special_tokensF)r9   r:   already_has_special_tokensr;   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   )r=   r<   )xr.   r   r   <lambda>       z=XLMRobertaTokenizer.get_special_tokens_mask.<locals>.<lambda>r   r   )
ValueErrorlistmapr+   )r.   r9   r:   rA   r   rC   r   get_special_tokens_mask   s    z+XLMRobertaTokenizer.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.
        XLM-R 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   )r=   r<   r+   )r.   r9   r:   r?   r>   r   r   r   $create_token_type_ids_from_sequences   s
    z8XLMRobertaTokenizer.create_token_type_ids_from_sequencesc                 C   s   t | j| j d S )Nr   )r+   r&   r*   rC   r   r   r   
vocab_size  s    zXLMRobertaTokenizer.vocab_sizec                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r   )Zconvert_ids_to_tokens)r   irC   r   r   r   	  s      z1XLMRobertaTokenizer.get_vocab.<locals>.<dictcomp>)rangerK   updateZadded_tokens_encoder)r.   Zvocabr   rC   r   	get_vocab  s    zXLMRobertaTokenizer.get_vocabc                 C   s   | j |S )N)r&   ZEncodeAsPieces)r.   textr   r   r   	_tokenize  s    zXLMRobertaTokenizer._tokenizec                 C   s4   || j kr| j | S | j|}|r.|| j S | jS )z2 Converts a token (str) in an id using the vocab. )r)   r&   Z	PieceToIdr*   Zunk_token_id)r.   tokenZspm_idr   r   r   _convert_token_to_id  s    

z(XLMRobertaTokenizer._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(XLMRobertaTokenizer._convert_id_to_tokenc                 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,XLMRobertaTokenizer.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isdirr#   errorformatrX   VOCAB_FILES_NAMESabspathr   r   )r.   Zsave_directoryZout_vocab_filer   r   r   save_vocabulary$  s    z#XLMRobertaTokenizer.save_vocabulary)r
   r   r   r
   r   r   r   )N)NF)N)__name__
__module____qualname____doc__rb   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_map&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesZmodel_input_namesr    r6   r8   r   intr   r@   boolrI   rJ   propertyrK   rO   rQ   rS   rU   r\   rd   __classcell__r   r   r1   r   r	   4   sV   2       3  
    
    

	r	   )rh   loggingr]   shutilr   typingr   r   Ztokenization_utilsr   Ztokenization_xlnetr   	getLoggerre   r#   rb   ri   rj   r	   r   r   r   r   <module>   s2   

