
    g8                         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  ej        e          Zdd	iZd
Z G d de          ZdS )z$Tokenization classes for FNet model.    N)copyfile)AnyDictListOptionalTuple   )
AddedTokenPreTrainedTokenizer)logging
vocab_filezspiece.modelu   ▁c                       e Zd ZdZeZddgZ	 	 	 	 	 	 	 	 	 d'deee	e
f                  ddf fdZed             Zd Zd Zd Zd Zde	dee	         fdZd Zd Zd Z	 	 	 d(dee         dededede	f
 fdZ	 d)dee         deee                  dee         fd Z	 d*dee         deee                  d!edee         f fd"Z	 d)dee         deee                  dee         fd#Zd)d$e	d%ee	         dee	         fd&Z xZS )+FNetTokenizera  
    Construct an FNet tokenizer. Adapted from [`AlbertTokenizer`]. 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 `False`):
            Whether or not to lowercase the input when tokenizing.
        remove_space (`bool`, *optional*, defaults to `True`):
            Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
        keep_accents (`bool`, *optional*, defaults to `True`):
            Whether or not to keep accents when tokenizing.
        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.
        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).
    	input_idstoken_type_idsFT<unk>[SEP]<pad>[CLS][MASK]Nsp_model_kwargsreturnc                 R   t          |	t                    rt          |	dd          n|	}	t          |t                    rt          |d          n|}t          |t                    rt          |d          n|}t          |	t                    rt          |	d          n|	}	|
i n|
| _        || _        || _        || _        || _        t          j	        di | j        | _
        | j
                            |            t                      j        d||||||||	| j        d	| d S )NT)lstripspecial)r   )	do_lower_caseremove_spacekeep_accents	unk_token	sep_token	pad_token	cls_token
mask_tokenr    )
isinstancestrr
   r   r   r   r   r   spmSentencePieceProcessorsp_modelLoadsuper__init__)selfr   r   r   r   r   r    r!   r"   r#   r   kwargs	__class__s               f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/fnet/tokenization_fnet.pyr,   zFNetTokenizer.__init__Z   sb     KUU_adJeJeuZ
4FFFFku
;EiQT;U;UdJy$7777[d	;EiQT;U;UdJy$7777[d	=G
TW=X=XhZ
D9999^h
%4%<rr/*(($2JJT5IJJ:&&& 	
'%%! 0	
 	
 	
 	
 	
 	
 	
    c                 *    t          | j                  S N)lenr)   )r-   s    r0   
vocab_sizezFNetTokenizer.vocab_size   s    4=!!!r1   c                 |      fdt           j                  D             }|                     j                   |S )Nc                 <    i | ]}                     |          |S r$   )convert_ids_to_tokens).0ir-   s     r0   
<dictcomp>z+FNetTokenizer.get_vocab.<locals>.<dictcomp>   s)    RRRa++A..RRRr1   )ranger5   updateadded_tokens_encoder)r-   vocabs   ` r0   	get_vocabzFNetTokenizer.get_vocab   s@    RRRR5;Q;QRRRT.///r1   c                 B    | j                                         }d |d<   |S )Nr)   )__dict__copy)r-   states     r0   __getstate__zFNetTokenizer.__getstate__   s$    ""$$ jr1   c                     || _         t          | d          si | _        t          j        di | j        | _        | j                            | j                   d S )Nr   r$   )rB   hasattrr   r'   r(   r)   r*   r   )r-   ds     r0   __setstate__zFNetTokenizer.__setstate__   s_     t.// 	&#%D 2JJT5IJJ4?+++++r1   c                    | j         r:d                    |                                                                          }n|}|                    dd                              dd          }| j        s4t          j        d|          }d                    d |D                       }| j        r|	                                }|S )N z``"z''NFKD c                 :    g | ]}t          j        |          |S r$   )unicodedata	combining)r9   cs     r0   
<listcomp>z1FNetTokenizer.preprocess_text.<locals>.<listcomp>   s(    RRRQ9Nq9Q9QRqRRRr1   )
r   joinstripsplitreplacer   rP   	normalizer   lower)r-   inputsoutputss      r0   preprocess_textzFNetTokenizer.preprocess_text   s     	hhv||~~335566GGG//$,,44T3??  	T!+FG<<GggRR'RRRSSG 	&mmooGr1   textc                    |                      |          }| j                            |t                    }g }|D ]*}t	          |          dk    r|d         t          d          k    r|d                                         r| j                            |dd                             t          d                    }|d         t          k    rN|d         d         t          k    r7t	          |d                   dk    r|dd         }n|d         dd         |d<   |	                    |d                    |
                    |           |	                    |           ,|S )	zTokenize a string.)out_type   ,NrN   r   )r\   r)   encoder&   r4   isdigitEncodeAsPiecesrW   SPIECE_UNDERLINEappendextend)r-   r]   pieces
new_piecespiece
cur_piecess         r0   	_tokenizezFNetTokenizer._tokenize   sV   ##D))%%dS%99
 	) 	)E5zzA~~%)s3xx"7"7E"I<M<M<O<O"7!]99%*:L:LM]_a:b:bcc
8///JqM!4DHX4X4X:a=))Q..%/^

(21abb(9
1!!%),,,!!*----!!%((((r1   c                 6    | j                             |          S )z0Converts a token (str) in an id using the vocab.)r)   	PieceToId)r-   tokens     r0   _convert_token_to_idz"FNetTokenizer._convert_token_to_id       }&&u---r1   c                 6    | j                             |          S )z=Converts an index (integer) in a token (str) using the vocab.)r)   	IdToPiece)r-   indexs     r0   _convert_id_to_tokenz"FNetTokenizer._convert_id_to_token   rs   r1   c                    g }d}d}|D ]N}|| j         v r,|s|dz  }|| j                            |          |z   z  }d}g }7|                    |           d}O|| j                            |          z  }|                                S )z:Converts a sequence of tokens (string) in a single string.rN   FrK   T)all_special_tokensr)   decoderh   rU   )r-   tokenscurrent_sub_tokens
out_stringprev_is_specialrq   s         r0   convert_tokens_to_stringz&FNetTokenizer.convert_tokens_to_string   s    
 
	( 
	(E///& &#%Jdm223EFFNN
"&%'"""))%000"'dm**+=>>>
!!!r1   	token_idsskip_special_tokensclean_up_tokenization_spacesspaces_between_special_tokensc                 t     t                      j        d||||d|}|s|                    dd          }|S )N)r   r   r   r   z<unk> r   r$   )r+   _decoderW   )r-   r   r   r   r   r.   r]   r/   s          r0   r   zFNetTokenizer._decode   s^     uww 
 3)E*G	
 

 
 
 - 	3<<'22Dr1   token_ids_0token_ids_1c                 R    | j         g}| j        g}|||z   |z   S ||z   |z   |z   |z   S )a  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. An FNet 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.
        )sep_token_idcls_token_idr-   r   r   sepclss        r0    build_inputs_with_special_tokensz.FNetTokenizer.build_inputs_with_special_tokens   sJ    &  ! !$s**[ 3&4s::r1   already_has_special_tokensc                     |r$t                                          ||d          S |3dgdgt          |          z  z   dgz   dgt          |          z  z   dgz   S dgdgt          |          z  z   dgz   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)r   r   r   Nr`   r   )r+   get_special_tokens_maskr4   )r-   r   r   r   r/   s       r0   r   z%FNetTokenizer.get_special_tokens_mask
  s    & & 	7722'[]a 3    "31#K 0 001QC7A3[AQAQ;QRVWUXXXsqcC,,,-33r1   c                     | j         g}| j        g}|t          ||z   |z             dgz  S t          ||z   |z             dgz  t          ||z             dgz  z   S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet 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   r`   )r   r   r4   r   s        r0   $create_token_type_ids_from_sequencesz2FNetTokenizer.create_token_type_ids_from_sequences&  sw    ,  ! !s[(3.//1#553$s*++qc1Cc8I4J4JaS4PPPr1   save_directoryfilename_prefixc                    t           j                            |          s t                              d| d           d S t           j                            ||r|dz   ndt          d         z             }t           j                            | j                  t           j                            |          k    r:t           j        	                    | j                  rt          | j        |           nzt           j        	                    | j                  sVt          |d          5 }| j                                        }|                    |           d d d            n# 1 swxY w Y   |fS )NzVocabulary path (z) should be a directory-rN   r   wb)ospathisdirloggererrorrT   VOCAB_FILES_NAMESabspathr   isfiler   openr)   serialized_model_protowrite)r-   r   r   out_vocab_fileficontent_spiece_models         r0   save_vocabularyzFNetTokenizer.save_vocabularyC  sw   w}}^,, 	LLT^TTTUUUFoM_s222QbcoQpp
 
 7??4?++rw~/N/NNNSUSZSaSabfbqSrSrNT_n555500 	/nd++ /r'+}'K'K'M'M$-.../ / / / / / / / / / / / / / /   s   (/E##E'*E')	FTTr   r   r   r   r   N)FNFr3   )NF) __name__
__module____qualname____doc__r   vocab_files_namesmodel_input_namesr   r   r&   r   r,   propertyr5   r@   rE   rI   r\   r   rn   rr   rw   r   intboolr   r   r   r   r   r   __classcell__)r/   s   @r0   r   r   #   s       1 1f *$&67
 48)
 )
 "$sCx.1)
 
)
 )
 )
 )
 )
 )
V " " X"  
  
, , ,  c d3i    (. . .. . .
" " ", %*-1.3 9 " '+	
 (, 
     , JN; ;9;3;DI3F;	c; ; ; ;4 sx4 4943;DI3F4ko4	c4 4 4 4 4 4: JNQ Q9Q3;DI3FQ	cQ Q Q Q:! !c !HSM !]bcf]g ! ! ! ! ! ! ! !r1   r   )r   r   rP   shutilr   typingr   r   r   r   r   sentencepiecer'   tokenization_utilsr
   r   utilsr   
get_loggerr   r   r   rg   r   r$   r1   r0   <module>r      s    + * 				           3 3 3 3 3 3 3 3 3 3 3 3 3 3     A A A A A A A A       
	H	%	%!>2   o! o! o! o! o!' o! o! o! o! o!r1   