U
    4AfP                     @   s   d Z ddlZddlZddlZddlmZmZmZ ddlm	Z	m
Z
mZmZ ddlmZ eeZddiZd	d
 Zdd ZG dd de	ZG dd dZG dd dZdS )zTokenization classes for Bert.    N)ListOptionalTuple   )PreTrainedTokenizer_is_control_is_punctuation_is_whitespace)logging
vocab_filez	vocab.txtc              	   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   N/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/bert/tokenization_bert.py
load_vocab   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_tokenize*   s
    r"   c                
       s   e Zd ZdZeZd% fd	d
	Zedd Ze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 fddZd)ee eee  ee dd d!Zd*eee ee d"d#d$Z  ZS )+BertTokenizera

  
    Construct a BERT tokenizer. Based on WordPiece.

    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
    this superclass for more information regarding those methods.

    Args:
        vocab_file (`str`):
            File containing the vocabulary.
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether or not to lowercase the input when tokenizing.
        do_basic_tokenize (`bool`, *optional*, defaults to `True`):
            Whether or not to do basic tokenization before WordPiece.
        never_split (`Iterable`, *optional*):
            Collection of tokens which will never be split during tokenization. Only has an effect when
            `do_basic_tokenize=True`
        unk_token (`str`, *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 (`str`, *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 (`str`, *optional*, defaults to `"[PAD]"`):
            The token used for padding, for example when batching sequences of different lengths.
        cls_token (`str`, *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 (`str`, *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 (`bool`, *optional*, defaults to `True`):
            Whether or not to tokenize Chinese characters.

            This should likely be deactivated for Japanese (see this
            [issue](https://github.com/huggingface/transformers/issues/328)).
        strip_accents (`bool`, *optional*):
            Whether or not to strip all accents. If this option is not specified, then it will be determined by the
            value for `lowercase` (as in the original BERT).
    TN[UNK][SEP][PAD][CLS][MASK]c                    s   t j|std| dt|| _tdd | j D | _	|| _
|r^t|||
|d| _t| jt|d| _t jf ||||||||	|
|d
| d S )Nz&Can't find a vocabulary file at path 'z'. 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>t   s     z*BertTokenizer.__init__.<locals>.<listcomp>)do_lower_casenever_splittokenize_chinese_charsstrip_accents)r   	unk_token)
r-   do_basic_tokenizer.   r1   	sep_token	pad_token	cls_token
mask_tokenr/   r0   )ospathisfile
ValueErrorr   r   r   r   itemsids_to_tokensr2   BasicTokenizerbasic_tokenizerWordpieceTokenizerstrwordpiece_tokenizersuper__init__)selfr   r-   r2   r.   r1   r3   r4   r5   r6   r/   r0   kwargs	__class__r   r   rC   _   s:    

zBertTokenizer.__init__c                 C   s   | j jS N)r>   r-   rD   r   r   r   r-      s    zBertTokenizer.do_lower_casec                 C   s
   t | jS rH   )lenr   rI   r   r   r   
vocab_size   s    zBertTokenizer.vocab_sizec                 C   s   t | jf| jS rH   )dictr   Zadded_tokens_encoderrI   r   r   r   	get_vocab   s    zBertTokenizer.get_vocabFc                 C   sd   g }| j rT| jj||s| jnd dD ],}|| jjkr@|| q$|| j|7 }q$n| j|}|S )N)r.   )r2   r>   tokenizeZall_special_tokensr.   appendrA   )rD   r!   Zsplit_special_tokenssplit_tokensr   r   r   r   	_tokenize   s     
zBertTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r   getr1   )rD   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<   rR   r1   )rD   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   )rD   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 (`List[int]`):
                List of IDs to which the special tokens will be added.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        N)cls_token_idsep_token_id)rD   rZ   r[   clssepr   r   r    build_inputs_with_special_tokens   s
    z.BertTokenizer.build_inputs_with_special_tokens)rZ   r[   already_has_special_tokensr\   c                    sf   |rt  j||ddS |dk	rLdgdgt|  dg dgt|  dg S dgdgt|  dg S )a  
        Retrieve 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` method.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        T)rZ   r[   rb   N   r   )rB   get_special_tokens_maskrJ   )rD   rZ   r[   rb   rF   r   r   rd      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  
        Create 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`, this method only returns the first portion of the mask (0s).

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
        Nr   rc   )r^   r]   rJ   )rD   rZ   r[   r`   r_   r   r   r   $create_token_type_ids_from_sequences   s
    z2BertTokenizer.create_token_type_ids_from_sequences)save_directoryfilename_prefixr\   c              	   C   s   d}t j|r4t j||r$|d ndtd  }n|r@|d nd| }t|dddZ}t| j dd	 d
D ]<\}}||krt	
d| d |}||d  |d7 }qnW 5 Q R X |fS )Nr   -rV   r   wr   r   c                 S   s   | d S )Nrc   r   )kvr   r   r   <lambda>      z/BertTokenizer.save_vocabulary.<locals>.<lambda>)keyzSaving vocabulary to z\: vocabulary indices are not consecutive. Please check that the vocabulary is not corrupted!r   rc   )r7   r8   isdirrW   VOCAB_FILES_NAMESr   sortedr   r;   loggerwarningwrite)rD   rf   rg   r   r   writerr   Ztoken_indexr   r   r   save_vocabulary  s"     
zBertTokenizer.save_vocabulary)
TTNr$   r%   r&   r'   r(   TN)F)N)NF)N)N)__name__
__module____qualname____doc__ro   Zvocab_files_namesrC   propertyr-   rK   rM   rQ   rS   rT   rY   r   intr   ra   boolrd   re   r@   r   ru   __classcell__r   r   rF   r   r#   3   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=   a  
    Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).

    Args:
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether or not to lowercase the input when tokenizing.
        never_split (`Iterable`, *optional*):
            Collection of tokens which will never be split during tokenization. Only has an effect when
            `do_basic_tokenize=True`
        tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
            Whether or not to tokenize Chinese characters.

            This should likely be deactivated for Japanese (see this
            [issue](https://github.com/huggingface/transformers/issues/328)).
        strip_accents (`bool`, *optional*):
            Whether or not to strip all accents. If this option is not specified, then it will be determined by the
            value for `lowercase` (as in the original BERT).
        do_split_on_punc (`bool`, *optional*, defaults to `True`):
            In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
            the full context of the words, such as contractions.
    TNc                 C   s2   |d krg }|| _ t|| _|| _|| _|| _d S rH   )r-   setr.   r/   r0   do_split_on_punc)rD   r-   r.   r/   r0   r   r   r   r   rC   3  s    
zBasicTokenizer.__init__c                 C   s   |r| j t|n| j }| |}| jr4| |}td|}t|}g }|D ]R}||kr| j	r|
 }| jdk	r| |}n| jr| |}|| || qPtd|}|S )aj  
        Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.

        Args:
            never_split (`List[str]`, *optional*)
                Kept for backward compatibility purposes. Now implemented directly at the base class level (see
                [`PreTrainedTokenizer.tokenize`]) List of token not to split.
        NFCFrU   )r.   unionr~   _clean_textr/   _tokenize_chinese_charsunicodedata	normalizer"   r-   lowerr0   _run_strip_accentsextend_run_split_on_puncrW   )rD   r!   r.   Zunicode_normalized_textZorig_tokensrP   r   output_tokensr   r   r   rN   C  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MnrV   )r   r   categoryrO   rW   )rD   r!   outputcharcatr   r   r   r   i  s    
z!BasicTokenizer._run_strip_accentsc                 C   s   | j r|dk	r||kr|gS t|}d}d}g }|t|k r|| }t|r^||g d}n |rl|g  d}|d | |d7 }q0dd |D S )	z&Splits punctuation on a piece of text.Nr   TFrc   c                 S   s   g | ]}d  |qS )rV   )rW   )r)   xr   r   r   r,     s     z5BasicTokenizer._run_split_on_punc.<locals>.<listcomp>)r   listrJ   r   rO   )rD   r!   r.   charsiZstart_new_wordr   r   r   r   r   r   t  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.rU   rV   )ord_is_chinese_charrO   rW   rD   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   )rD   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  rU   rV   )r   r   r	   rO   rW   r   r   r   r   r     s    zBasicTokenizer._clean_text)TNTNT)N)N)rv   rw   rx   ry   rC   rN   r   r   r   r   r   r   r   r   r   r=     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 rH   )r   r1   max_input_chars_per_word)rD   r   r1   r   r   r   r   rC     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"` wil return as 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   NrV   z##rc   T)	r"   r   rJ   r   rO   r1   rW   r   r   )rD   r!   r   r   r   Zis_badstartZ
sub_tokensendZ
cur_substrsubstrr   r   r   rN     s:    


zWordpieceTokenizer.tokenizeN)r   )rv   rw   rx   ry   rC   rN   r   r   r   r   r?     s   
r?   )ry   r   r7   r   typingr   r   r   Ztokenization_utilsr   r   r   r	   utilsr
   Z
get_loggerrv   rq   ro   r   r"   r#   r=   r?   r   r   r   r   <module>   s   
	 j "