U
    ,-eaX                     @   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mZ ddlmZ eeZddiZdd	d
iiZd	diZd	ddii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S )zTokenization classes for MPNet.    N)ListOptionalTuple   )
AddedTokenPreTrainedTokenizer_is_control_is_punctuation_is_whitespace)logging
vocab_filez	vocab.txtzmicrosoft/mpnet-basezBhttps://huggingface.co/microsoft/mpnet-base/resolve/main/vocab.txti   do_lower_caseTc              	   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   m/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/mpnet/tokenization_mpnet.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_tokenize9   s
    r$   c                       s  e Zd ZdZeZeZeZ	e
Zddg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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 ),MPNetTokenizeraz  

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

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        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`
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pre-training. 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>

        sep_token (`str`, *optional*, defaults to `"</s>"`):
            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.
        cls_token (`str`, *optional*, defaults to `"<s>"`):
            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.
        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.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
        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).
    Z	input_idsZattention_maskTN<s></s>[UNK]<pad><mask>c                    sh  t |trt|dddn|}t |tr4t|dddn|}t |trPt|dddn|}t |trlt|dddn|}t |	trt|	dddn|	}	t |
trt|
dddn|
}
t |trt|dddn|}tj|std| dt|| _t	
dd | j D | _|| _|r$t||||d| _t| jt|	d	| _t jf ||||||	|||
|||d
| d S )NF)lstripr   Tz&Can't find a vocabulary file at path 'z'. To load the vocabulary from a Google pretrained model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`c                 S   s   g | ]\}}||fqS r   r   ).0tokZidsr   r   r   
<listcomp>   s     z+MPNetTokenizer.__init__.<locals>.<listcomp>)r   never_splittokenize_chinese_charsstrip_accents)r   	unk_token)r   do_basic_tokenizer/   	bos_token	eos_tokenr2   	sep_token	cls_token	pad_token
mask_tokenr0   r1   )
isinstancestrr   ospathisfile
ValueErrorr    r   r   r   itemsids_to_tokensr3   BasicTokenizerbasic_tokenizerWordpieceTokenizerwordpiece_tokenizersuper__init__)selfr   r   r3   r/   r4   r5   r6   r7   r2   r8   r9   r0   r1   kwargs	__class__r   r   rG      sL    

zMPNetTokenizer.__init__c                 C   s   | j jS N)rC   r   rH   r   r   r   r      s    zMPNetTokenizer.do_lower_casec                 C   s
   t | jS rL   )lenr   rM   r   r   r   
vocab_size   s    zMPNetTokenizer.vocab_sizec                 C   s   | j  }|| j |S rL   )r   copyupdateZadded_tokens_encoder)rH   r   r   r   r   	get_vocab   s    
zMPNetTokenizer.get_vocabc                 C   s\   g }| j rL| jj|| jdD ],}|| jjkr8|| q|| j|7 }qn| j|}|S )N)r/   )r3   rC   tokenizeZall_special_tokensr/   appendrE   )rH   r#   split_tokensr   r   r   r   	_tokenize   s    zMPNetTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r   getr2   )rH   r   r   r   r   _convert_token_to_id   s    z#MPNetTokenizer._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)rA   rW   r2   )rH   r   r   r   r   _convert_id_to_token   s    z#MPNetTokenizer._convert_id_to_tokenc                 C   s   d |dd }|S )z:Converts a sequence of tokens (string) in a single string. z ## )joinreplacer!   )rH   r   Z
out_stringr   r   r   convert_tokens_to_string   s    z'MPNetTokenizer.convert_tokens_to_string)token_ids_0token_ids_1returnc                 C   sD   |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 MPNet sequence has the following format:

        - single sequence: `<s> X </s>`
        - pair of sequences: `<s> A </s></s> B </s>`

        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)rH   r_   r`   clssepr   r   r    build_inputs_with_special_tokens   s
    z/MPNetTokenizer.build_inputs_with_special_tokensF)r_   r`   already_has_special_tokensra   c                    sh   |rt  j||ddS |dkr8dgdgt|  dg S dgdgt|  d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` methods.

        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`):
                Set to True if 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)r_   r`   rg   N   r   )rF   get_special_tokens_maskrN   )rH   r_   r`   rg   rJ   r   r   ri     s      z&MPNetTokenizer.get_special_tokens_maskc                 C   sP   | j g}| jg}|dkr.t|| | dg S t|| | | | | dg S )a  
        Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not
        make use of token type ids, therefore a list of zeros is returned.

        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 zeros.
        Nr   )rc   rb   rN   )rH   r_   r`   re   rd   r   r   r   $create_token_type_ids_from_sequences  s
    z3MPNetTokenizer.create_token_type_ids_from_sequences)save_directoryfilename_prefixra   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   -r[   r   wr   r   c                 S   s   | d S )Nrh   r   )kvr   r   r   <lambda><      z0MPNetTokenizer.save_vocabulary.<locals>.<lambda>)keyzSaving vocabulary to z\: vocabulary indices are not consecutive. Please check that the vocabulary is not corrupted!r   rh   )r<   r=   isdirr\   VOCAB_FILES_NAMESr   sortedr   r@   loggerwarningwrite)rH   rk   rl   r   r   writerr   Ztoken_indexr   r   r   save_vocabulary3  s"     
zMPNetTokenizer.save_vocabulary)TTNr&   r'   r'   r&   r(   r)   r*   TN)N)NF)N)N)!__name__
__module____qualname____doc__rt   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_mapPRETRAINED_INIT_CONFIGURATIONZpretrained_init_configuration&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesZmodel_input_namesrG   propertyr   rO   rR   rV   rX   rY   r^   r   intr   rf   boolri   rj   r;   r   rz   __classcell__r   r   rJ   r   r%   B   sb   <            <

  
    
   
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 )rB   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 rL   )r   setr/   r0   r1   do_split_on_punc)rH   r   r/   r0   r1   r   r   r   r   rG   `  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.
        NFCFrZ   )r/   unionr   _clean_textr0   _tokenize_chinese_charsunicodedata	normalizer$   r   lowerr1   _run_strip_accentsextend_run_split_on_puncr\   )rH   r#   r/   Zunicode_normalized_textZorig_tokensrU   r   output_tokensr   r   r   rS   p  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Mnr[   )r   r   categoryrT   r\   )rH   r#   outputcharcatr   r   r   r     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   TFrh   c                 S   s   g | ]}d  |qS )r[   )r\   )r,   xr   r   r   r.     s     z5BasicTokenizer._run_split_on_punc.<locals>.<listcomp>)r   listrN   r	   rT   )rH   r#   r/   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.rZ   r[   )ord_is_chinese_charrT   r\   rH   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   )rH   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  rZ   r[   )r   r   r
   rT   r\   r   r   r   r   r     s    zBasicTokenizer._clean_text)TNTNT)N)N)r{   r|   r}   r~   rG   rS   r   r   r   r   r   r   r   r   r   rB   I  s        

&
rB   c                   @   s"   e Zd ZdZdddZdd ZdS )	rD   zRuns WordPiece tokenization.d   c                 C   s   || _ || _|| _d S rL   )r   r2   max_input_chars_per_word)rH   r   r2   r   r   r   r   rG     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   Nr[   z##rh   T)	r$   r   rN   r   rT   r2   r\   r   r   )rH   r#   r   r   r   Zis_badstartZ
sub_tokensendZ
cur_substrsubstrr   r   r   rS     s:    


zWordpieceTokenizer.tokenizeN)r   )r{   r|   r}   r~   rG   rS   r   r   r   r   rD     s   
rD   )r~   r   r<   r   typingr   r   r   Ztokenization_utilsr   r   r   r	   r
   utilsr   Z
get_loggerr{   rv   rt   r   r   r   r    r$   r%   objectrB   rD   r   r   r   r   <module>   s6   
   	  	 #