
    g9                         d Z ddlZddlZddlmZ ddlmZmZmZ ddl	Z
ddlmZmZ ddlmZ dd	lmZ  ej        e          Zd
ddZ e            d             Zd Z G d de          ZdS )zTokenization class for CLVP.    N)	lru_cache)ListOptionalTuple   )
AddedTokenPreTrainedTokenizer)logging   )EnglishNormalizerz
vocab.jsonz
merges.txt)
vocab_filemerges_filec            	      \   t          t          t          d          t          d          dz                       t          t          t          d          t          d          dz                       z   t          t          t          d          t          d          dz                       z   } | dd         }d	}t          d
          D ]8}|| vr2|                     |           |                    d
|z              |dz  }9d |D             }t	          t          | |                    S )a8  
    Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
    characters the bpe code barfs on.

    The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
    if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
    decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
    tables between utf-8 bytes and unicode strings.
    !~r      ¡   ¬   ®   ÿNr      c                 ,    g | ]}t          |          S  )chr).0ns     f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/clvp/tokenization_clvp.py
<listcomp>z$bytes_to_unicode.<locals>.<listcomp>;   s    			Q#a&&			    )listrangeordappenddictzip)bscsr   bs       r   bytes_to_unicoder(   %   s    	U3s88SXX\**++d5TCIIPQM3R3R.S.SSVZ[`adeiajajloptluluxyly[z[zV{V{{  
AAAB	A4[[  B;;IIaLLLIIdQhFA		"			BBr   c                 ~    t                      }| d         }| dd         D ]}|                    ||f           |}|S )z
    Return set of symbol pairs in a word.

    Word is represented as tuple of symbols (symbols being variable-length strings).
    r   r   N)setadd)wordpairs	prev_charchars       r   	get_pairsr0   @   sP     EEEQIQRR  		9d#$$$		Lr   c            
           e Zd ZdZeZddgZ	 	 	 	 	 	 	 	 d fd		Zed
             Z	ed             Z
d Zd ZddZ	 ddee         deee                  dedee         f fdZd Zd Zd Zd Zd Zddedee         dee         fdZ xZS ) ClvpTokenizerae
  
    Construct a CLVP tokenizer. Based on byte-level Byte-Pair-Encoding.

    This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
    be encoded differently whether it is at the beginning of the sentence (without space) or not:

    ```python
    >>> from transformers import ClvpTokenizer

    >>> tokenizer = ClvpTokenizer.from_pretrained("susnato/clvp_dev")
    >>> tokenizer("Hello world")["input_ids"]
    [62, 84, 28, 2, 179, 79]

    >>> tokenizer(" Hello world")["input_ids"]
    [2, 62, 84, 28, 2, 179, 79]
    ```

    You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
    call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

    <Tip>

    When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).

    </Tip>

    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`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        errors (`str`, *optional*, defaults to `"replace"`):
            Paradigm to follow when decoding bytes to UTF-8. See
            [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
        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.
        bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
            The beginning of sequence token.
        eos_token (`str`, *optional*, defaults to `"[STOP]"`):
            The end of sequence token.
        pad_token (`str`, *optional*, defaults to `"[STOP]"`):
            The pad token of the sequence.
        add_prefix_space (`bool`, *optional*, defaults to `False`):
            Whether or not to add an initial space to the input. This allows to treat the leading word just as any
            other word. (CLVP tokenizer detect beginning of words by the preceding space).
        add_bos_token (`bool`, *optional*, defaults to `False`):
            Whether to add `bos_token` in front of the sequence when add_special_tokens=True.
        add_eos_token (`bool`, *optional*, defaults to `False`):
            Whether to add `eos_token` in end of the sequence when add_special_tokens=True.
    	input_idsattention_maskreplace[UNK]<|endoftext|>[STOP]Fc                    t          |t                    rt          |d          n|}t          |t                    rt          |d          n|}t          |t                    rt          |d          n|}t          |t                    rt          |d          n|}|	| _        |
| _        d | _        t          |d          5 }t          j        |          | _	        d d d            n# 1 swxY w Y   d | j	        
                                D             | _        || _        t                      | _        d | j        
                                D             | _        t          |d          5 }|                                                    d          dd	         }d d d            n# 1 swxY w Y   d
 |D             }t%          t'          |t)          t+          |                                        | _        i | _        || _        t3          j        d          | _         t9                      j        d|||||||	|
d| d S )NT)specialutf-8encodingc                     i | ]\  }}||	S r   r   r   kvs      r   
<dictcomp>z*ClvpTokenizer.__init__.<locals>.<dictcomp>   s    >>>A1>>>r   c                     i | ]\  }}||	S r   r   r?   s      r   rB   z*ClvpTokenizer.__init__.<locals>.<dictcomp>   s    HHHdaQHHHr   
r   c                 P    g | ]#}t          |                                          $S r   )tuplesplit)r   merges     r   r   z*ClvpTokenizer.__init__.<locals>.<listcomp>   s(    CCCueEKKMM**CCCr   zJ's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+)errors	unk_token	bos_token	eos_token	pad_tokenadd_prefix_spaceadd_bos_tokenadd_eos_tokenr   )
isinstancestrr   rP   rQ   _normalizeropenjsonloadencoderitemsdecoderrJ   r(   byte_encoderbyte_decoderreadrH   r#   r$   r    len	bpe_rankscacherO   recompilepatsuper__init__)selfr   r   rJ   rK   rL   rM   rN   rO   rP   rQ   kwargsvocab_handlemerges_handle
bpe_merges	__class__s                  r   re   zClvpTokenizer.__init__   s    <FiQT;U;UdJy$7777[d	;EiQT;U;UdJy$7777[d	;EiQT;U;UdJy$7777[d	;EiQT;U;UdJy$7777[d	***w/// 	3<9\22DL	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3>>););)=)=>>>,..HHd.?.E.E.G.GHHH+000 	@M&++--33D99!B$?J	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@CC
CCC
c*eC
OO.D.DEEFF
 0 :opp 
	
-''
	
 
	
 
	
 
	
 
	
 
	
 
	
s$   C..C25C240F00F47F4c                 *    t          | j                  S N)r^   rX   rf   s    r   
vocab_sizezClvpTokenizer.vocab_size   s    4<   r   c                 D    | j         t                      | _         | j         S rm   )rT   r   rn   s    r   
normalizerzClvpTokenizer.normalizer   s"    #022Dr   c                 0    t          | j        fi | j        S rm   )r#   rX   added_tokens_encoderrn   s    r   	get_vocabzClvpTokenizer.get_vocab   s    DL>>D$=>>>r   c                 f    | j         v r j         |         S t          |          }t          |          }|s|S 	 t          | fd          }| j        vrn8|\  }}g }d}|t          |          k     r	 |                    ||          }	|                    |||	                    |	}n-# t          $ r  |                    ||d                     Y nw xY w||         |k    rC|t          |          dz
  k     r-||dz            |k    r|	                    ||z              |dz  }n |	                    ||                    |dz  }|t          |          k     t          |          }|}t          |          dk    rnt          |          }Wd
                    |          }| j         |<   |S )NTc                 T    j                             | t          d                    S )Ninf)r_   getfloat)pairrf   s    r   <lambda>z#ClvpTokenizer.bpe.<locals>.<lambda>   s     1C1CD%PU,,1W1W r   keyr   r       )r`   rG   r0   minr_   r^   indexextend
ValueErrorr"   join)
rf   tokenr,   r-   bigramfirstsecondnew_wordijs
   `         r   bpezClvpTokenizer.bpe   s   DJ:e$$U||$ 	L	($W$W$W$WXXXFT^++"ME6HAc$ii--

5!,,A
 OOD1I...AA "   OODH---E 7e##CIIM(9(9d1q5kV>S>SOOEFN333FAAOODG,,,FA c$ii--  XHD4yyA~~!$9	(: xx~~ 
5s   7B- -'CCNc                 t    | j         r| j        gng }| j        r| j        gng }||z   |z   }|||z   |z   |z   }|S rm   )rP   bos_token_idrQ   eos_token_id)rf   token_ids_0token_ids_1r   r   outputs         r    build_inputs_with_special_tokensz.ClvpTokenizer.build_inputs_with_special_tokens   s`    .2.@H)**b.2.@H)**b+l:"l*[8<GFr   r   r   already_has_special_tokensreturnc                 6   |r$t                                          ||d          S | j        s$t                                          ||d          S |dgdgt          |          z  z   S dgdgt          |          z  z   dgz   dgt          |          z  z   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` or `encode_plus` 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`):
                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   FNr   r   )rd   get_special_tokens_maskrP   r^   )rf   r   r   r   rk   s       r   r   z%ClvpTokenizer.get_special_tokens_mask  s    $ & 	7722'[]a 3    ! 	7722'[]b 3    31#K 0 0011sqcC,,,-3sS=M=M7MNNr   c                 f    g }                      |          }t          j         j        |          D ]}}d                     fd|                    d          D                       }|                     fd                     |                              d          D                        ~|S )zTokenize a string. c              3   2   K   | ]}j         |         V  d S rm   )r[   )r   r'   rf   s     r   	<genexpr>z*ClvpTokenizer._tokenize.<locals>.<genexpr>)  s<        )*!!$     r   r;   c              3   b   K   | ])}|d k    rdj                                         v rdn|V  *dS )u   Ġ[SPACE]N)rX   keys)r   	bpe_tokenrf   s     r   r   z*ClvpTokenizer._tokenize.<locals>.<genexpr>.  s^         '(22yDLDUDUDWDW7W7W		]f     r   r   )	rq   ra   findallrc   r   encoder   r   rH   )rf   text
bpe_tokensr   s   `   r   	_tokenizezClvpTokenizer._tokenize$  s    
t$$Z$// 		 		EGG    .3ll7.C.C    E
     !%%!6!6s!;!;      
 r   c                 r    | j                             || j                             | j                            S )z0Converts a token (str) in an id using the vocab.)rX   rx   rK   )rf   r   s     r   _convert_token_to_idz"ClvpTokenizer._convert_token_to_id6  s,    |t|'7'7'G'GHHHr   c                 6    | j                             |          S )z=Converts an index (integer) in a token (str) using the vocab.)rZ   rx   )rf   r   s     r   _convert_id_to_tokenz"ClvpTokenizer._convert_id_to_token;  s    |&&&r   c                      d                     |          }t           fd|D                                           d j                  }|S )z:Converts a sequence of tokens (string) in a single string.r   c                 *    g | ]}j         |         S r   )r\   )r   crf   s     r   r   z:ClvpTokenizer.convert_tokens_to_string.<locals>.<listcomp>C  s!    ===1$+A.===r   r;   )rJ   )r   	bytearraydecoderJ   )rf   tokensr   s   `  r   convert_tokens_to_stringz&ClvpTokenizer.convert_tokens_to_string@  sP    wwv=======>>EEgVZVaEbbr   c                    d                     |          }t          | j                                                  t          | j                                                  z   }d|v r|                    dd          n|}d|v r|                    dd          n|}|                    | j        d                              dd                              dd          }|S )Nr   r   r   r8   z   z  )r   r   rX   r   rs   r5   rK   )rf   r   vocab_tokenss      r   clean_up_tokenizationz#ClvpTokenizer.clean_up_tokenizationF  s    wwt}}DL--//0048Q8V8V8X8X3Y3YY/8L/H/Ht||Is+++d.6,.F.Ft||Hc***D||DNB//77sCCKKDRUVVr   save_directoryfilename_prefixc           	         t           j                            |          s t                              d| d           d S t           j                            ||r|dz   ndt          d         z             }t           j                            ||r|dz   ndt          d         z             }t          |dd	          5 }|                    t          j
        | j        d
dd          dz              d d d            n# 1 swxY w Y   d}t          |dd	          5 }|                    d           t          | j                                        d           D ][\  }}	||	k    r t                              d| d           |	}|                    d                    |          dz              |dz  }\	 d d d            n# 1 swxY w Y   ||fS )NzVocabulary path (z) should be a directory-r   r   r   wr;   r<   r~   TF)indent	sort_keysensure_asciirD   r   z#version: 0.2
c                     | d         S )Nr   r   )kvs    r   r{   z/ClvpTokenizer.save_vocabulary.<locals>.<lambda>b  s    Y[\]Y^ r   r|   zSaving vocabulary to zZ: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!r   r   )ospathisdirloggererrorr   VOCAB_FILES_NAMESrU   writerV   dumpsrX   sortedr_   rY   warning)
rf   r   r   r   
merge_filefr   writerr   token_indexs
             r   save_vocabularyzClvpTokenizer.save_vocabularyQ  s   w}}^,, 	LLT^TTTUUUFW\\oM_s222QbcoQpp
 

 W\\oM_s222QbcpQqq
 

 *cG444 	cGGDJt|ATYZZZ]aabbb	c 	c 	c 	c 	c 	c 	c 	c 	c 	c 	c 	c 	c 	c 	c *cG444 
	LL*++++1$.2F2F2H2HN^N^+_+_+_  '
KK''NNM
 M M M   (ESXXj11D8999

	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 :%%s%   <4C<<D D BGG
G)r5   r6   r7   r8   r8   FFFrm   )NF)__name__
__module____qualname____doc__r   vocab_files_namesmodel_input_namesre   propertyro   rq   rt   r   r   r   intr   boolr   r   r   r   r   r   rS   r   r   __classcell__)rk   s   @r   r2   r2   N   s       5 5n * !1
 1
 1
 1
 1
 1
f ! ! X!     X 
? ? ?( ( (V	 	 	 	 sxO O9O3;DI3FOkoO	cO O O O O O@  $I I I
' ' '
    & &c &HSM &]bcf]g & & & & & & & &r   r2   )r   rV   r   	functoolsr   typingr   r   r   regexra   tokenization_utilsr   r	   utilsr
   number_normalizerr   
get_loggerr   r   r   r(   r0   r2   r   r   r   <module>r      s/   # "  				       ( ( ( ( ( ( ( ( ( (     A A A A A A A A       0 0 0 0 0 0 
	H	%	%      2  ^& ^& ^& ^& ^&' ^& ^& ^& ^& ^&r   