U
    4AfJZ                     @   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 ddlmZ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 REALM.    N)ListOptionalTuple   )PreTrainedTokenizer_is_control_is_punctuation_is_whitespace)BatchEncoding)PaddingStrategy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   [/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/deprecated/realm/tokenization_realm.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 Zdd Zdd Zdd Z 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 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 ),RealmTokenizera|
  
    Construct a REALM tokenizer.

    [`RealmTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting and
    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 = RealmTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`c                 S   s   g | ]\}}||fqS r   r   ).0tokidsr   r   r   
<listcomp>x   s     z+RealmTokenizer.__init__.<locals>.<listcomp>)do_lower_casenever_splittokenize_chinese_charsstrip_accents)r   	unk_token)
r/   do_basic_tokenizer0   r3   	sep_token	pad_token	cls_token
mask_tokenr1   r2   )ospathisfile
ValueErrorr    r   r   r   itemsids_to_tokensr4   BasicTokenizerbasic_tokenizerWordpieceTokenizerstrwordpiece_tokenizersuper__init__)selfr   r/   r4   r0   r3   r5   r6   r7   r8   r1   r2   kwargs	__class__r   r   rE   c   s:    

zRealmTokenizer.__init__c                 C   s   | j jS N)r@   r/   rF   r   r   r   r/      s    zRealmTokenizer.do_lower_casec                 C   s
   t | jS rJ   )lenr   rK   r   r   r   
vocab_size   s    zRealmTokenizer.vocab_sizec                 C   s   t | jf| jS rJ   )dictr   Zadded_tokens_encoderrK   r   r   r   	get_vocab   s    zRealmTokenizer.get_vocabc                 C   s\   g }| j rL| jj|| jdD ],}|| jjkr8|| q|| j|7 }qn| j|}|S )N)r0   )r4   r@   tokenizeZall_special_tokensr0   appendrC   )rF   r#   split_tokensr   r   r   r   	_tokenize   s    zRealmTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r   getr3   )rF   r   r   r   r   _convert_token_to_id   s    z#RealmTokenizer._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)r>   rT   r3   )rF   r   r   r   r   _convert_id_to_token   s    z#RealmTokenizer._convert_id_to_tokenc                 C   s   d |dd }|S )z:Converts a sequence of tokens (string) in a single string. z ## )joinreplacer!   )rF   r   Z
out_stringr   r   r   convert_tokens_to_string   s    z'RealmTokenizer.convert_tokens_to_stringc                    s   t j|d< |}|dd}|dd}g g g d}t|D ]\}}|dk	rT|| }	nd}	t j||	fddi|}
|
d}|
d}|
d}|dk	r|d | |dk	r|d | |dk	r:|d | q:d	d
 | D }t	||dS )a  
        Encode a batch of text or text pair. This method is similar to regular __call__ method but has the following
        differences:

            1. Handle additional num_candidate axis. (batch_size, num_candidates, text)
            2. Always pad the sequences to *max_length*.
            3. Must specify *max_length* in order to stack packs of candidates into a batch.

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

        Args:
            text (`List[List[str]]`):
                The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
                num_candidates, text).
            text_pair (`List[List[str]]`, *optional*):
                The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
                num_candidates, text).
            **kwargs:
                Keyword arguments of the __call__ method.

        Returns:
            [`BatchEncoding`]: Encoded text or text pair.

        Example:

        ```python
        >>> from transformers import RealmTokenizer

        >>> # batch_size = 2, num_candidates = 2
        >>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]

        >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder")
        >>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")
        ```paddingZ	text_pairNreturn_tensors)	input_idsattention_masktoken_type_idsr^   r_   r`   c                 S   s"   i | ]\}}t |d kr||qS )r   )rL   )r+   keyitemr   r   r   
<dictcomp>   s       z:RealmTokenizer.batch_encode_candidates.<locals>.<dictcomp>)Ztensor_type)
r   Z
MAX_LENGTHpopr   rD   __call__rT   rQ   r=   r
   )rF   r#   rG   Z
batch_textZbatch_text_pairr]   Zoutput_dataidxZcandidate_textZcandidate_text_pairZencoded_candidatesZencoded_input_idsZencoded_attention_maskZencoded_token_type_idsrH   r   r   batch_encode_candidates   s0    &




z&RealmTokenizer.batch_encode_candidates)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 REALM 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)rF   rh   ri   clssepr   r   r    build_inputs_with_special_tokens   s
    z/RealmTokenizer.build_inputs_with_special_tokensF)rh   ri   already_has_special_tokensrj   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)rh   ri   rp   N   r   )rD   get_special_tokens_maskrL   )rF   rh   ri   rp   rH   r   r   rr     s      .z&RealmTokenizer.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 REALM 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   rq   )rl   rk   rL   )rF   rh   ri   rn   rm   r   r   r   $create_token_type_ids_from_sequences3  s
    z3RealmTokenizer.create_token_type_ids_from_sequences)save_directoryfilename_prefixrj   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   -rX   r   wr   r   c                 S   s   | d S )Nrq   r   )kvr   r   r   <lambda>Y      z0RealmTokenizer.save_vocabulary.<locals>.<lambda>)ra   zSaving vocabulary to z\: vocabulary indices are not consecutive. Please check that the vocabulary is not corrupted!r   rq   )r9   r:   isdirrY   VOCAB_FILES_NAMESr   sortedr   r=   loggerwarningwrite)rF   rt   ru   r   r   writerr   Ztoken_indexr   r   r   save_vocabularyP  s"     
zRealmTokenizer.save_vocabulary)
TTNr&   r'   r(   r)   r*   TN)N)NF)N)N)__name__
__module____qualname____doc__r|   Zvocab_files_namesrE   propertyr/   rM   rO   rS   rU   rV   r[   rg   r   intr   ro   boolrr   rs   rB   r   r   __classcell__r   r   rH   r   r%   4   sX   ,          -

J  
    
   
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).
    TNc                 C   s,   |d krg }|| _ t|| _|| _|| _d S rJ   )r/   setr0   r1   r2   )rF   r/   r0   r1   r2   r   r   r   rE   y  s    
zBasicTokenizer.__init__c                 C   s   |r| j t|n| j }| |}| jr4| |}t|}g }|D ]R}||kr| jrt| }| j	dk	r| 
|}n| j	r| 
|}|| || qDtd|}|S )a  
        Basic Tokenization of a piece of text. Split on "white spaces" only, 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.
        FrW   )r0   unionr   _clean_textr1   _tokenize_chinese_charsr$   r/   lowerr2   _run_strip_accentsextend_run_split_on_puncrY   )rF   r#   r0   Zorig_tokensrR   r   output_tokensr   r   r   rP     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MnrX   )unicodedata	normalizecategoryrQ   rY   )rF   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   TFrq   c                 S   s   g | ]}d  |qS )rX   )rY   )r+   xr   r   r   r.     s     z5BasicTokenizer._run_split_on_punc.<locals>.<listcomp>)listrL   r   rQ   )rF   r#   r0   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.rW   rX   )ord_is_chinese_charrQ   rY   rF   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   )rF   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  rW   rX   )r   r   r	   rQ   rY   r   r   r   r   r     s    zBasicTokenizer._clean_text)TNTN)N)N)r   r   r   r   rE   rP   r   r   r   r   r   r   r   r   r   r?   e  s   

%
r?   c                   @   s"   e Zd ZdZdddZdd ZdS )	rA   zRuns WordPiece tokenization.d   c                 C   s   || _ || _|| _d S rJ   )r   r3   max_input_chars_per_word)rF   r   r3   r   r   r   r   rE     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   NrX   z##rq   T)	r$   r   rL   r   rQ   r3   rY   r   r   )rF   r#   r   r   r   Zis_badstartZ
sub_tokensendZ
cur_substrsubstrr   r   r   rP     s:    


zWordpieceTokenizer.tokenizeN)r   )r   r   r   r   rE   rP   r   r   r   r   rA     s   
rA   )r   r   r9   r   typingr   r   r   Ztokenization_utilsr   r   r   r	   Ztokenization_utils_baser
   utilsr   r   Z
get_loggerr   r~   r|   r    r$   r%   r?   rA   r   r   r   r   <module>   s"   
	  3 