U
    &cr                     @   s  d Z ddlZddlZddlZddlZddlmZmZ ddlm	Z	 ddl
mZmZ eeZddiZdd	d
dddddddddddddddddiZdddddddddddddddddddZddiddiddiddiddiddiddiddiddiddiddiddiddiddiddiddiddiddidZd d! Zd"d# ZG d$d% d%eZG d&d' d'eZG d(d) d)eZd*d+ Zd,d- Zd.d/ ZG d0d1 d1eZdS )2zTokenization classes.    N)ListOptional)BertWordPieceTokenizer   )PreTrainedTokenizerPreTrainedTokenizerFast
vocab_filez	vocab.txtzOhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txtzPhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txtzMhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txtzNhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txtz\https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txtzZhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txtzOhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txtzfhttps://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txtzchttps://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txtzahttps://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txtzshttps://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txtzqhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txtz\https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txtzZhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-cased-vocab.txtz\https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-uncased-vocab.txtzahttps://s3.amazonaws.com/models.huggingface.co/bert/TurkuNLP/bert-base-finnish-cased-v1/vocab.txtzchttps://s3.amazonaws.com/models.huggingface.co/bert/TurkuNLP/bert-base-finnish-uncased-v1/vocab.txtz\https://s3.amazonaws.com/models.huggingface.co/bert/wietsedv/bert-base-dutch-cased/vocab.txt)zbert-base-uncasedzbert-large-uncasedzbert-base-casedzbert-large-casedzbert-base-multilingual-uncasedzbert-base-multilingual-casedzbert-base-chinesezbert-base-german-casedz%bert-large-uncased-whole-word-maskingz#bert-large-cased-whole-word-maskingz5bert-large-uncased-whole-word-masking-finetuned-squadz3bert-large-cased-whole-word-masking-finetuned-squadzbert-base-cased-finetuned-mrpczbert-base-german-dbmdz-casedzbert-base-german-dbmdz-uncasedzbert-base-finnish-cased-v1zbert-base-finnish-uncased-v1zbert-base-dutch-casedi   do_lower_caseTFc              	   C   sR   t  }t| ddd}| }W 5 Q R X t|D ]\}}|d}|||< q2|S )z*Loads a vocabulary file into a dictionary.rutf-8encoding
)collectionsOrderedDictopen	readlines	enumeraterstrip)r   vocabreadertokensindextoken r   B/tmp/pip-unpacked-wheel-ymerj3tt/transformers/tokenization_bert.py
load_vocabc   s    

r   c                 C   s   |   } | sg S |  }|S )z@Runs basic whitespace cleaning and splitting on a piece of text.)stripsplit)textr   r   r   r   whitespace_tokenizen   s
    r    c                	       s   e Zd ZdZe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 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 )&BertTokenizeray	  
    Constructs a BERT tokenizer. Based on WordPiece.

    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`):
            File containing the vocabulary.
        do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to lowercase the input when tokenizing.
        do_basic_tokenize (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to do basic tokenization before WordPiece.
        never_split (:obj:`bool`, `optional`, defaults to :obj:`True`):
            List of tokens which will never be split during tokenization. Only has an effect when
            :obj:`do_basic_tokenize=True`
        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.
        tokenize_chinese_chars (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to tokenize Chinese characters.
            This should likely be deactivated for Japanese:
            see: https://github.com/huggingface/transformers/issues/328
    TN[UNK][SEP][PAD][CLS][MASK]c                    s   t  jf |||||	d| tj|s8td|t|| _t	
dd | j D | _|| _|rxt|||
d| _t| j| jd| _d S )N	unk_token	sep_token	pad_token	cls_token
mask_tokenzCan't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`c                 S   s   g | ]\}}||fqS r   r   ).0tokidsr   r   r   
<listcomp>   s     z*BertTokenizer.__init__.<locals>.<listcomp>r	   never_splittokenize_chinese_chars)r   r(   )super__init__ospathisfile
ValueErrorformatr   r   r   r   itemsids_to_tokensdo_basic_tokenizeBasicTokenizerbasic_tokenizerWordpieceTokenizerr(   wordpiece_tokenizer)selfr   r	   r=   r2   r(   r)   r*   r+   r,   r3   kwargs	__class__r   r   r5      s2    	
  zBertTokenizer.__init__c                 C   s
   t | jS N)lenr   rB   r   r   r   
vocab_size   s    zBertTokenizer.vocab_sizec                 C   s   t | jf| jS rF   )dictr   Zadded_tokens_encoderrH   r   r   r   	get_vocab   s    zBertTokenizer.get_vocabc                 C   sP   g }| j r@| jj|| jdD ] }| j|D ]}|| q,qn| j|}|S )N)r2   )r=   r?   tokenizeZall_special_tokensrA   append)rB   r   split_tokensr   Z	sub_tokenr   r   r   	_tokenize   s    zBertTokenizer._tokenizec                 C   s   | j || j | jS )z2 Converts a token (str) in an id using the vocab. )r   getr(   )rB   r   r   r   r   _convert_token_to_id   s    z"BertTokenizer._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)r<   rP   r(   )rB   r   r   r   r   _convert_id_to_token   s    z"BertTokenizer._convert_id_to_tokenc                 C   s   d |dd }|S )z< Converts a sequence of tokens (string) in a single string.  z ## )joinreplacer   )rB   r   Z
out_stringr   r   r   convert_tokens_to_string   s    z&BertTokenizer.convert_tokens_to_string)token_ids_0token_ids_1returnc                 C   s@   |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 BERT 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cls_token_idsep_token_id)rB   rX   rY   clssepr   r   r    build_inputs_with_special_tokens   s
    z.BertTokenizer.build_inputs_with_special_tokensF)rX   rY   already_has_special_tokensrZ   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 formated with special tokens for the model.c                    s   |  j  jfkrdS dS )Nr   r   )r]   r\   )xrH   r   r   <lambda>      z7BertTokenizer.get_special_tokens_mask.<locals>.<lambda>r   r   )r9   listmaprG   )rB   rX   rY   ra   r   rH   r   get_special_tokens_mask   s    .z%BertTokenizer.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.
        A BERT 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 (0's).

        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\   rG   )rB   rX   rY   r_   r^   r   r   r   $create_token_type_ids_from_sequences  s
    z2BertTokenizer.create_token_type_ids_from_sequencesc              	   C   s   d}t j|r$t j|td }n|}t|dddX}t| j dd dD ]:\}}||krrt	
d	| |}||d
  |d7 }qNW 5 Q R X |fS )a.  
        Save the sentencepiece vocabulary (copy original file) and special tokens file to a directory.

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

        Returns:
            :obj:`Tuple(str)`: Paths to the files saved.
        r   r   wr   r   c                 S   s   | d S )Nr   r   )kvr   r   r   rc   N  rd   z/BertTokenizer.save_vocabulary.<locals>.<lambda>)keyzsSaving vocabulary to {}: vocabulary indices are not consecutive. Please check that the vocabulary is not corrupted!r   r   )r6   r7   isdirrU   VOCAB_FILES_NAMESr   sortedr   r;   loggerwarningr:   write)rB   Z
vocab_pathr   r   writerr   Ztoken_indexr   r   r   save_vocabulary=  s     zBertTokenizer.save_vocabulary)	TTNr"   r#   r$   r%   r&   T)N)NF)N)__name__
__module____qualname____doc__rm   vocab_files_namesPRETRAINED_VOCAB_FILES_MAPpretrained_vocab_files_mapPRETRAINED_INIT_CONFIGURATIONpretrained_init_configuration&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESmax_model_input_sizesr5   propertyrI   rK   rO   rQ   rR   rW   r   intr   r`   boolrg   rh   rs   __classcell__r   r   rD   r   r!   w   sV   &         %

  
    
    
r!   c                   @   sN   e Zd ZdZdddZdddZdd	 Zdd
dZdd Zdd Z	dd Z
dS )r>   zDRuns basic tokenization (punctuation splitting, lower casing, etc.).TNc                 C   s"   |dkrg }|| _ || _|| _dS )a   Constructs a BasicTokenizer.

        Args:
            **do_lower_case**: Whether to lower case the input.
            **never_split**: (`optional`) list of str
                Kept for backward compatibility purposes.
                Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`)
                List of token not to split.
            **tokenize_chinese_chars**: (`optional`) boolean (default True)
                Whether to tokenize Chinese characters.
                This should likely be deactivated for Japanese:
                see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328
        Nr1   )rB   r	   r2   r3   r   r   r   r5   ]  s
    zBasicTokenizer.__init__c                 C   s   | j |dk	r|ng  }| |}| jr0| |}t|}g }|D ]6}| jrd||krd| }| |}|| 	|| q@td
|}|S )a   Basic Tokenization of a piece of text.
            Split on "white spaces" only, for sub-word tokenization, see WordPieceTokenizer.

        Args:
            **never_split**: (`optional`) list of str
                Kept for backward compatibility purposes.
                Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`)
                List of token not to split.
        NrS   )r2   _clean_textr3   _tokenize_chinese_charsr    r	   lower_run_strip_accentsextend_run_split_on_puncrU   )rB   r   r2   Zorig_tokensrN   r   output_tokensr   r   r   rL   q  s    



zBasicTokenizer.tokenizec                 C   sB   t d|}g }|D ]"}t |}|dkr,q|| qd|S )z$Strips accents from a piece of text.ZNFDZMnrT   )unicodedata	normalizecategoryrM   rU   )rB   r   outputcharcatr   r   r   r     s    
z!BasicTokenizer._run_strip_accentsc                 C   s   |dk	r||kr|gS t |}d}d}g }|t|k r|| }t|rX||g d}n |rf|g  d}|d | |d7 }q*dd |D S )	z&Splits punctuation on a piece of text.Nr   TFr   c                 S   s   g | ]}d  |qS )rT   )rU   )r-   rb   r   r   r   r0     s     z5BasicTokenizer._run_split_on_punc.<locals>.<listcomp>)re   rG   _is_punctuationrM   )rB   r   r2   charsiZstart_new_wordr   r   r   r   r   r     s"    

z!BasicTokenizer._run_split_on_puncc                 C   sT   g }|D ]@}t |}| |r>|d || |d q|| qd|S )z)Adds whitespace around any CJK character.rS   rT   )ord_is_chinese_charrM   rU   rB   r   r   r   cpr   r   r   r     s    


z&BasicTokenizer._tokenize_chinese_charsc                 C   s   |dkr|dks|dkr |dks|dkr0|dks|dkr@|dks|d	krP|d
ks|dkr`|dks|dkrp|dks|dkr|dkrdS dS )z6Checks whether CP is the codepoint of a CJK character.i N  i  i 4  iM  i   iߦ i  i? i@ i i  i i   i  i  i TFr   )rB   r   r   r   r   r     sD    
zBasicTokenizer._is_chinese_charc                 C   sX   g }|D ]D}t |}|dks|dkst|r.qt|rB|d q|| qd|S )zBPerforms invalid character removal and whitespace cleanup on text.r   i  rS   rT   )r   _is_control_is_whitespacerM   rU   r   r   r   r   r     s    zBasicTokenizer._clean_text)TNT)N)N)rt   ru   rv   rw   r5   rL   r   r   r   r   r   r   r   r   r   r>   Z  s   


r>   c                   @   s"   e Zd ZdZdddZdd ZdS )	r@   zRuns WordPiece tokenization.d   c                 C   s   || _ || _|| _d S rF   )r   r(   max_input_chars_per_word)rB   r   r(   r   r   r   r   r5     s    zWordpieceTokenizer.__init__c                 C   s   g }t |D ]}t|}t|| jkr4|| j qd}d}g }|t|k rt|}d}	||k rd||| }
|dkrd|
 }
|
| jkr|
}	q|d8 }qX|	dkrd}q||	 |}q@|r|| j q|| q|S )a  Tokenizes a piece of text into its word pieces.

        This uses a greedy longest-match-first algorithm to perform tokenization
        using the given vocabulary.

        For example:
          input = "unaffable"
          output = ["un", "##aff", "##able"]

        Args:
          text: A single token or whitespace separated tokens. This should have
            already been passed through `BasicTokenizer`.

        Returns:
          A list of wordpiece tokens.
        Fr   NrT   ##r   T)	r    re   rG   r   rM   r(   rU   r   r   )rB   r   r   r   r   Zis_badstartZ
sub_tokensendZ
cur_substrsubstrr   r   r   rL     s:    


zWordpieceTokenizer.tokenizeN)r   )rt   ru   rv   rw   r5   rL   r   r   r   r   r@     s   
r@   c                 C   s>   | dks | dks | dks | dkr$dS t | }|dkr:dS dS )z1Checks whether `chars` is a whitespace character.rS   	r   TZsF)r   r   r   r   r   r   r   r      s     
r   c                 C   s8   | dks| dks| dkrdS t | }|dr4dS dS )z.Checks whether `chars` is a control character.r   r   r   FCT)r   r   
startswithr   r   r   r   r   ,  s    

r   c                 C   sh   t | }|dkr|dksH|dkr(|dksH|dkr8|dksH|dkrL|dkrLd	S t| }|d
rdd	S dS )z2Checks whether `chars` is a punctuation character.!   /   :   @   [   `   {   ~   TPF)r   r   r   r   )r   r   r   r   r   r   r   8  s    @

r   c                
       s<   e Zd ZdZeZeZeZ	e
Zd fd	d
	ZdddZ  ZS )BertTokenizerFastaY
  
    Constructs a "Fast" BERT tokenizer (backed by HuggingFace's `tokenizers` library).

    Bert tokenization is Based on WordPiece.

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

    Args:
        vocab_file (:obj:`string`):
            File containing the vocabulary.
        do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to lowercase the input when tokenizing.
        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.
        tokenize_chinese_chars (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to tokenize Chinese characters.
            This should likely be deactivated for Japanese:
            see: https://github.com/huggingface/transformers/issues/328
        clean_text (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to clean the text before tokenization by removing any control characters and
            replacing all whitespaces by the classic one.
        tokenize_chinese_chars (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to tokenize Chinese characters.
            This should likely be deactivated for Japanese:
            see: https://github.com/huggingface/transformers/issues/328
    Tr"   r#   r$   r%   r&   r   c                    s@   t  jt||||||	|
||d	f|||||d| || _d S )N)	r   r(   r)   r+   
clean_textZhandle_chinese_charsstrip_accentsZ	lowercasewordpieces_prefixr'   )r4   r5   r   r	   )rB   r   r	   r(   r)   r*   r+   r,   r   r3   r   r   rC   rD   r   r   r5   w  s,    zBertTokenizerFast.__init__Nc                 C   s,   | j g| | jg }|r(||| jg 7 }|S rF   r[   )rB   rX   rY   r   r   r   r   r`     s    z2BertTokenizerFast.build_inputs_with_special_tokens)
Tr"   r#   r$   r%   r&   TTTr   )N)rt   ru   rv   rw   rm   rx   ry   rz   r{   r|   r}   r~   r5   r`   r   r   r   rD   r   r   G  s"   *          %r   )rw   r   loggingr6   r   typingr   r   Z
tokenizersr   Ztokenization_utilsr   r   	getLoggerrt   ro   rm   ry   r}   r{   r   r    r!   objectr>   r@   r   r   r   r   r   r   r   r   <module>   s   
	 d <