U
    &cU7                  
   @   s   d 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 ddl	m
Z
 eeZddiZdd	d
dddddddiZdddddddddZdZG dd de
ZdS )z' Tokenization classes for ALBERT model.    N)copyfile)ListOptional   )PreTrainedTokenizer
vocab_filezspiece.modelzOhttps://s3.amazonaws.com/models.huggingface.co/bert/albert-base-v1-spiece.modelzPhttps://s3.amazonaws.com/models.huggingface.co/bert/albert-large-v1-spiece.modelzQhttps://s3.amazonaws.com/models.huggingface.co/bert/albert-xlarge-v1-spiece.modelzRhttps://s3.amazonaws.com/models.huggingface.co/bert/albert-xxlarge-v1-spiece.modelzOhttps://s3.amazonaws.com/models.huggingface.co/bert/albert-base-v2-spiece.modelzPhttps://s3.amazonaws.com/models.huggingface.co/bert/albert-large-v2-spiece.modelzQhttps://s3.amazonaws.com/models.huggingface.co/bert/albert-xlarge-v2-spiece.modelzRhttps://s3.amazonaws.com/models.huggingface.co/bert/albert-xxlarge-v2-spiece.model)zalbert-base-v1zalbert-large-v1zalbert-xlarge-v1zalbert-xxlarge-v1zalbert-base-v2zalbert-large-v2zalbert-xlarge-v2zalbert-xxlarge-v2i   u   ▁c                
       s   e Zd ZdZeZeZeZ	d( fd	d
	Z
edd Zdd Zdd Zdd Zdd Zd)ddZ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d&d' Z  ZS )-AlbertTokenizerar  
    Constructs an ALBERT tokenizer. Based on `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:`string`):
            `SentencePiece <https://github.com/google/sentencepiece>`__ file (generally has a .spm extension) that
            contains the vocabulary necessary to instantiate a tokenizer.
        do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to lowercase the input when tokenizing.
        remove_space (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to strip the text when tokenizing (removing excess spaces before and after the string).
        keep_accents (:obj:`bool`, `optional`, defaults to :obj:`False`):
            Whether to keep accents when tokenizing.
        bos_token (:obj:`string`, `optional`, defaults to "[CLS]"):
            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 "[SEP]"):
            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`.
        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.
        sep_token (:obj:`string`, `optional`, defaults to "[SEP]"):
            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.
        pad_token (:obj:`string`, `optional`, defaults to "<pad>"):
            The token used for padding, for example when batching sequences of different lengths.
        cls_token (:obj:`string`, `optional`, defaults to "[CLS]"):
            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.
        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.

    Attributes:
        sp_model (:obj:`SentencePieceProcessor`):
            The `SentencePiece` processor that is used for every conversion (string, tokens and IDs).
    TF[CLS][SEP]<unk><pad>[MASK]c              
      s   t  jf |||||	|
|d| zdd l}W n  tk
rN   td  Y nX || _|| _|| _|| _	|
 | _| j| d S )N)	bos_token	eos_token	unk_token	sep_token	pad_token	cls_token
mask_tokenr   zYou need to install SentencePiece to use AlbertTokenizer: https://github.com/google/sentencepiecepip install sentencepiece)super__init__sentencepieceImportErrorloggerwarningdo_lower_caseremove_spacekeep_accentsr   SentencePieceProcessorsp_modelLoad)selfr   r   r   r   r   r   r   r   r   r   r   kwargsspm	__class__ D/tmp/pip-unpacked-wheel-ymerj3tt/transformers/tokenization_albert.pyr   r   s0    
zAlbertTokenizer.__init__c                 C   s
   t | jS )N)lenr    r"   r'   r'   r(   
vocab_size   s    zAlbertTokenizer.vocab_sizec                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r'   )Zconvert_ids_to_tokens).0ir*   r'   r(   
<dictcomp>   s      z-AlbertTokenizer.get_vocab.<locals>.<dictcomp>)ranger+   updateZadded_tokens_encoder)r"   Zvocabr'   r*   r(   	get_vocab   s    zAlbertTokenizer.get_vocabc                 C   s   | j  }d |d< |S )Nr    )__dict__copy)r"   stater'   r'   r(   __getstate__   s    
zAlbertTokenizer.__getstate__c                 C   sP   || _ zdd l}W n  tk
r2   td  Y nX | | _| j| j d S )Nr   r   )	r2   r   r   r   r   r   r    r!   r   )r"   dr$   r'   r'   r(   __setstate__   s    
zAlbertTokenizer.__setstate__c                 C   sj   | j rd|  }n|}|dddd}| jsXtd|}ddd |D }| jrf|	 }|S )	N z``"z''ZNFKD c                 S   s   g | ]}t |s|qS r'   )unicodedata	combining)r,   cr'   r'   r(   
<listcomp>   s     
 z3AlbertTokenizer.preprocess_text.<locals>.<listcomp>)
r   joinstripsplitreplacer   r;   	normalizer   lower)r"   inputsoutputsr'   r'   r(   preprocess_text   s    zAlbertTokenizer.preprocess_textc                 C   s   |  |}|s| j|}n| j|dd}g }|D ]}t|dkr|d tdkr|d  r| j|dd td}|d	 tkr|d	 d	 tkrt|d	 dkr|dd }n|d	 dd |d	< |	|d  |
| q4|	| q4|S )
z Tokenize a string. @   g?r   ,Nr:   r   )rG   r    ZEncodeAsPiecesZSampleEncodeAsPiecesr)   strisdigitrB   SPIECE_UNDERLINEappendextend)r"   textsamplepiecesZ
new_piecesZpieceZ
cur_piecesr'   r'   r(   	_tokenize   s     
(zAlbertTokenizer._tokenizec                 C   s   | j |S )z2 Converts a token (str) in an id using the vocab. )r    Z	PieceToId)r"   tokenr'   r'   r(   _convert_token_to_id   s    z$AlbertTokenizer._convert_token_to_idc                 C   s   | j |S )z=Converts an index (integer) in a token (str) using the vocab.)r    Z	IdToPiece)r"   indexr'   r'   r(   _convert_id_to_token   s    z$AlbertTokenizer._convert_id_to_tokenc                 C   s   d |td }|S )Nr:   r8   )r?   rB   rN   r@   )r"   tokensZ
out_stringr'   r'   r(   convert_tokens_to_string   s    z(AlbertTokenizer.convert_tokens_to_stringN)token_ids_0token_ids_1returnc                 C   s8   | j g}| jg}|dkr$|| | S || | | | S )a  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks
        by concatenating and adding special tokens.
        An ALBERT sequence has the following format:

        - single sequence: ``[CLS] X [SEP]``
        - pair of sequences: ``[CLS] A [SEP] B [SEP]``

        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sep_token_idcls_token_idr"   r[   r\   sepclsr'   r'   r(    build_inputs_with_special_tokens   s
    z0AlbertTokenizer.build_inputs_with_special_tokens)r[   r\   already_has_special_tokensr]   c                    sz   |r*|dk	rt dtt fdd|S |dk	r`dgdgt|  dg dgt|  dg S 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 formatted with special tokens for the model.c                    s   |  j  jfkrdS dS )Nr   r   r^   )xr*   r'   r(   <lambda>      z9AlbertTokenizer.get_special_tokens_mask.<locals>.<lambda>r   r   )
ValueErrorlistmapr)   )r"   r[   r\   re   r'   r*   r(   get_special_tokens_mask  s    .z'AlbertTokenizer.get_special_tokens_maskc                 C   sV   | j g}| jg}|dkr.t|| | dg S t|| | dg t|| dg  S )a  
        Creates a mask from the two sequences passed to be used in a sequence-pair classification task.
        An ALBERT sequence pair mask has the following format:

        ::

            0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
            | first sequence    | second sequence |

        if token_ids_1 is None, only returns the first portion of the mask (0s).

        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 `token type IDs <../glossary.html#token-type-ids>`_ according to the given
            sequence(s).
        Nr   r   )r_   r`   r)   ra   r'   r'   r(   $create_token_type_ids_from_sequences$  s
    z4AlbertTokenizer.create_token_type_ids_from_sequencesc                 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formatr?   VOCAB_FILES_NAMESabspathr   r   )r"   Zsave_directoryZout_vocab_filer'   r'   r(   save_vocabularyC  s    zAlbertTokenizer.save_vocabulary)
TTFr	   r
   r   r
   r   r	   r   )F)N)NF)N)__name__
__module____qualname____doc__rs   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_map&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesr   propertyr+   r1   r5   r7   rG   rT   rV   rX   rZ   r   intr   rd   boolrl   rm   ru   __classcell__r'   r'   r%   r(   r   9   s\   4          +

  
    
    
r   )ry   loggingrn   r;   shutilr   typingr   r   Ztokenization_utilsr   	getLoggerrv   r   rs   rz   r{   rN   r   r'   r'   r'   r(   <module>   s<   
