U
    9%e??                     @   s   d Z ddlZddlZddlmZ ddlmZmZmZm	Z	m
Z
 ddlZddlmZmZ ddlmZmZ eeZdd	iZdd
ddiZdddZdZdZdZdZdZG dd deZdS )z& Tokenization classes for XLNet model.    N)copyfile)AnyDictListOptionalTuple   )
AddedTokenPreTrainedTokenizer)SPIECE_UNDERLINElogging
vocab_filezspiece.modelzAhttps://huggingface.co/xlnet-base-cased/resolve/main/spiece.modelzBhttps://huggingface.co/xlnet-large-cased/resolve/main/spiece.model)zxlnet-base-casedzxlnet-large-cased         c                       sd  e Zd ZdZeZeZeZ	dZ
dddddddd	d
dddgdfeeeef  dd fddZedd Zdd Zdd Zdd Zdd Zeee dddZdd  Zd!d" Zd#d$ Zd3ee eeeed%d&d'Zd4ee eee  ee d(d)d*Zd5ee eee  eee d+ fd,d-Zd6ee eee  ee d(d.d/Z d7eee e!e d0d1d2Z"  Z#S )8XLNetTokenizera-  
    Construct an XLNet tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).

    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`):
            [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
            contains the vocabulary necessary to instantiate a tokenizer.
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether to lowercase the input when tokenizing.
        remove_space (`bool`, *optional*, defaults to `True`):
            Whether to strip the text when tokenizing (removing excess spaces before and after the string).
        keep_accents (`bool`, *optional*, defaults to `False`):
            Whether to keep accents when tokenizing.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

            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 `cls_token`.

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

            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 `sep_token`.

            </Tip>

        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.
        additional_special_tokens (`List[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
            Additional special tokens used by the tokenizer.
        sp_model_kwargs (`dict`, *optional*):
            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
            to set:

            - `enable_sampling`: Enable subword regularization.
            - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.

              - `nbest_size = {0,1}`: No sampling is performed.
              - `nbest_size > 1`: samples from the nbest_size results.
              - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
                using forward-filtering-and-backward-sampling algorithm.

            - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
              BPE-dropout.

    Attributes:
        sp_model (`SentencePieceProcessor`):
            The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
    leftFTz<s>z</s>z<unk>z<sep>z<pad>z<cls>z<mask>z<eop>z<eod>N)sp_model_kwargsreturnc                    s   t |trt|dddn|}|d kr(i n|| _|| _|| _|| _|| _tj	f | j| _
| j
| t jf ||||||||	|
||| jd| d| _d S )NTF)lstriprstrip)do_lower_caseremove_spacekeep_accents	bos_token	eos_token	unk_token	sep_token	pad_token	cls_token
mask_tokenadditional_special_tokensr   r   )
isinstancestrr	   r   r   r   r   r   spmSentencePieceProcessorsp_modelLoadsuper__init__Z_pad_token_type_id)selfr   r   r   r   r   r   r   r   r   r   r    r!   r   kwargs	__class__ k/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/xlnet/tokenization_xlnet.pyr)      s2    zXLNetTokenizer.__init__c                 C   s
   t | jS )N)lenr&   r*   r.   r.   r/   
vocab_size   s    zXLNetTokenizer.vocab_sizec                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r.   )convert_ids_to_tokens).0ir1   r.   r/   
<dictcomp>   s      z,XLNetTokenizer.get_vocab.<locals>.<dictcomp>)ranger2   updateadded_tokens_encoder)r*   Zvocabr.   r1   r/   	get_vocab   s    zXLNetTokenizer.get_vocabc                 C   s   | j  }d |d< |S )Nr&   )__dict__copy)r*   stater.   r.   r/   __getstate__   s    
zXLNetTokenizer.__getstate__c                 C   s8   || _ t| dsi | _tjf | j| _| j| j d S )Nr   )r;   hasattrr   r$   r%   r&   r'   r   )r*   dr.   r.   r/   __setstate__   s
    
zXLNetTokenizer.__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)r4   cr.   r.   r/   
<listcomp>   s     
 z2XLNetTokenizer.preprocess_text.<locals>.<listcomp>)
r   joinstripsplitreplacer   rE   	normalizer   lower)r*   inputsoutputsr.   r.   r/   preprocess_text   s    zXLNetTokenizer.preprocess_text)textr   c                 C   s   |  |}| jj|t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  |
| q"|	| q"|S )	zTokenize a string.)Zout_typer   ,NrD   r   )rQ   r&   encoder#   r0   isdigitZEncodeAsPiecesrL   r   appendextend)r*   rR   piecesZ
new_piecesZpieceZ
cur_piecesr.   r.   r/   	_tokenize   s    
(zXLNetTokenizer._tokenizec                 C   s   | j |S )z0Converts a token (str) in an id using the vocab.)r&   Z	PieceToId)r*   tokenr.   r.   r/   _convert_token_to_id   s    z#XLNetTokenizer._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#XLNetTokenizer._convert_id_to_tokenc                 C   s   d |td }|S )zIConverts a sequence of tokens (strings for sub-words) in a single string.rD   rB   )rI   rL   r   rJ   )r*   tokensZ
out_stringr.   r.   r/   convert_tokens_to_string   s    z'XLNetTokenizer.convert_tokens_to_string)	token_idsskip_special_tokensclean_up_tokenization_spacesspaces_between_special_tokensr   c                 K   s   | dd| _| j||d}g }g }|D ]L}	|r<|	| jkr<q(|	| jkrj|r^|| | g }||	 q(||	 q(|r|| | d|}
|d k	r|n| j}|r| 	|
}|S |
S d S )NZuse_source_tokenizerF)rc   rD   )
popZ_decode_use_source_tokenizerr3   Zall_special_idsr9   rX   ra   rI   rd   Zclean_up_tokenization)r*   rb   rc   rd   re   r+   Zfiltered_tokensZ	sub_textsZcurrent_sub_textr\   rR   Z
clean_textr.   r.   r/   _decode   s0    


zXLNetTokenizer._decode)token_ids_0token_ids_1r   c                 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 XLNet sequence has the following format:

        - single sequence: `X <sep> <cls>`
        - pair of sequences: `A <sep> B <sep> <cls>`

        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)sep_token_idZcls_token_id)r*   rh   ri   sepclsr.   r.   r/    build_inputs_with_special_tokens*  s
    z/XLNetTokenizer.build_inputs_with_special_tokens)rh   ri   already_has_special_tokensr   c                    s^   |rt  j||ddS |dk	rHdgt| dg dgt|  ddg S dgt| d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   rn   Nr   r   )r(   get_special_tokens_maskr0   )r*   rh   ri   rn   r,   r.   r/   ro   C  s      *z&XLNetTokenizer.get_special_tokens_maskc                 C   sT   | j g}d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. An XLNet
        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).
        r   Nr   r   )rj   r0   )r*   rh   ri   rk   Zcls_segment_idr.   r.   r/   $create_token_type_ids_from_sequences_  s
    z3XLNetTokenizer.create_token_type_ids_from_sequences)save_directoryfilename_prefixr   c              	   C   s   t j|s"td| d d S t j||r6|d ndtd  }t j| jt j|krzt j	| jrzt
| j| n8t j	| jst|d}| j }|| W 5 Q R X |fS )NzVocabulary path (z) should be a directory-rD   r   wb)ospathisdirloggererrorrI   VOCAB_FILES_NAMESabspathr   isfiler   openr&   Zserialized_model_protowrite)r*   rq   rr   Zout_vocab_filefiZcontent_spiece_modelr.   r.   r/   save_vocabulary}  s     (
zXLNetTokenizer.save_vocabulary)FNT)N)NF)N)N)$__name__
__module____qualname____doc__rz   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_map&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesZpadding_sider   r   r#   r   r)   propertyr2   r:   r>   rA   rQ   r   r[   r]   r_   ra   intboolrg   rm   ro   rp   r   r   __classcell__r.   r.   r,   r/   r   5   s|   J0

   .  
    
   
r   )r   ru   rE   shutilr   typingr   r   r   r   r   Zsentencepiecer$   Ztokenization_utilsr	   r
   utilsr   r   Z
get_loggerr   rx   rz   r   r   ZSEG_ID_AZSEG_ID_BZ
SEG_ID_CLSZ
SEG_ID_SEPZ
SEG_ID_PADr   r.   r.   r.   r/   <module>   s.   
