U
    4Af@                     @   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ZddlmZmZmZmZ ere rvddlZe rddlZddlmZmZ eeZdd	d
Ze dd Zdd ZG dd deZ dS )z Tokenization classes for CodeGen    N)	lru_cache)TYPE_CHECKINGListOptionalTupleUnion   )is_tf_availableis_torch_availablelogging	to_py_obj)
AddedTokenPreTrainedTokenizerz
vocab.jsonz
merges.txt)
vocab_filemerges_filec                  C   s   t ttdtdd t ttdtdd  t ttdtdd  } | dd }d	}td
D ],}|| krf| | |d
|  |d7 }qfdd |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.
    !~      ¡   ¬   ®   ÿNr      c                 S   s   g | ]}t |qS  )chr).0nr   r   T/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/codegen/tokenization_codegen.py
<listcomp>B   s     z$bytes_to_unicode.<locals>.<listcomp>)listrangeordappenddictzip)bscsr   br   r   r   bytes_to_unicode-   s    L

r(   c                 C   s6   t  }| d }| dd D ]}|||f |}q|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pairsZ	prev_charcharr   r   r   	get_pairsF   s    r.   c                       s   e Zd ZdZeZddgZd* fdd		Zed
d Z	dd Z
dd Zd+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 dddZd.d d!Zd/eeee d"d#d$f eeeee  ed% fd&d'Zd(d) Z  ZS )0CodeGenTokenizera`
  
    Construct a CodeGen 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 CodeGenTokenizer

    >>> tokenizer = CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono")
    >>> tokenizer("Hello world")["input_ids"]
    [15496, 995]

    >>> tokenizer(" Hello world")["input_ids"]
    [18435, 995]
    ```

    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 `"<|endoftext|>"`):
            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 `"<|endoftext|>"`):
            The end of sequence token.
        pad_token (`str`, *optional*):
            The token used for padding, for example when batching sequences of different lengths.
        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. (CodeGen tokenizer detect beginning of words by the preceding space).
        add_bos_token (`bool`, *optional*, defaults to `False`):
            Whether to add a beginning of sequence token at the start of sequences.
        return_token_type_ids (`bool`, *optional*, defaults to `False`):
            Whether to return token type IDs.
    Z	input_idsZattention_maskreplace<|endoftext|>NFc                    sx  t |trt|ddn|}t |tr0t|ddn|}t |trJt|ddn|}t |trdt|ddn|}|	| _|
| _| jr| jd t|dd}t	|| _
W 5 Q R X dd | j
 D | _|| _t | _dd | j D | _t|dd}| d	d
d }W 5 Q R X dd |D }tt|tt|| _i | _|| _td| _t jf |||||||	|
d| d S )NT)specialZtoken_type_idsutf-8encodingc                 S   s   i | ]\}}||qS r   r   r   kvr   r   r   
<dictcomp>   s      z-CodeGenTokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r   r   r6   r   r   r   r9      s      
r   c                 S   s   g | ]}t | qS r   )tuplesplit)r   merger   r   r   r      s     z-CodeGenTokenizer.__init__.<locals>.<listcomp>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return_token_type_ids)
isinstancestrr   rE   rF   model_input_namesr"   openjsonloadencoderitemsdecoderr?   r(   byte_encoderbyte_decoderreadr=   r#   r$   r    len	bpe_rankscacherD   recompilepatsuper__init__)selfr   r   r?   r@   rA   rB   rC   rD   rE   rF   kwargsZvocab_handleZmerges_handleZ
bpe_merges	__class__r   r   rZ      sB     	zCodeGenTokenizer.__init__c                 C   s
   t | jS N)rS   rM   r[   r   r   r   
vocab_size   s    zCodeGenTokenizer.vocab_sizec                 C   s   t | jf| jS r_   )r#   rM   Zadded_tokens_encoderr`   r   r   r   	get_vocab   s    zCodeGenTokenizer.get_vocabc           
         sd  | j kr j | S t|}t|}|s,|S t| fddd}| jkrNqL|\}}g }d}|t|k r"z|||}	W n, tk
r   |||d   Y q"Y nX ||||	  |	}|| |kr
|t|d k r
||d  |kr
|	||  |d7 }q^|	||  |d7 }q^t|}|}t|dkrBqLq,t|}q,d
|}| j |< |S )Nc                    s    j | tdS )Ninf)rT   getfloat)pairr`   r   r   <lambda>       z&CodeGenTokenizer.bpe.<locals>.<lambda>keyr   r       )rU   r<   r.   minrT   rS   index
ValueErrorextendr"   join)
r[   tokenr+   r,   ZbigramfirstsecondZnew_wordijr   r`   r   bpe   sB    


2




zCodeGenTokenizer.bpec                 C   s4   | j r| jg}ng }|| }|d kr(|S || | S r_   )rE   Zbos_token_id)r[   token_ids_0token_ids_1Zbos_token_idsoutputr   r   r    build_inputs_with_special_tokens   s    
z1CodeGenTokenizer.build_inputs_with_special_tokensc                    sZ   g }t  j|D ]B}d fdd|dD }|dd  |dD  q|S )zTokenize a string. c                 3   s   | ]} j | V  qd S r_   )rP   )r   r'   r`   r   r   	<genexpr>  s    z-CodeGenTokenizer._tokenize.<locals>.<genexpr>r3   c                 s   s   | ]
}|V  qd S r_   r   )r   Z	bpe_tokenr   r   r   r}     s     rl   )rV   findallrX   rq   encoderp   rw   r=   )r[   text
bpe_tokensrr   r   r`   r   	_tokenize   s    "zCodeGenTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)rM   rd   r@   )r[   rr   r   r   r   _convert_token_to_id	  s    z%CodeGenTokenizer._convert_token_to_idc                 C   s   | j |S )z=Converts an index (integer) in a token (str) using the vocab.)rO   rd   )r[   rn   r   r   r   _convert_id_to_token  s    z%CodeGenTokenizer._convert_id_to_tokenc                    s0   d |}t fdd|D jd jd}|S )z:Converts a sequence of tokens (string) in a single string.r|   c                    s   g | ]} j | qS r   )rQ   )r   cr`   r   r   r     s     z=CodeGenTokenizer.convert_tokens_to_string.<locals>.<listcomp>r3   )r?   )rq   	bytearraydecoder?   )r[   tokensr   r   r`   r   convert_tokens_to_string  s    
"z)CodeGenTokenizer.convert_tokens_to_string)rx   ry   returnc                 C   sr   | j dk	r| j gng }| j dk	r(| jgng }|dkrJt|| | 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 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   )Zsep_token_idZcls_token_idrS   )r[   rx   ry   sepclsr   r   r   $create_token_type_ids_from_sequences  s
    z5CodeGenTokenizer.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||rX|d ndtd  }t|ddd	$}|t	j
| jd
dddd  W 5 Q R X d}t|ddd	j}|d t| j dd dD ]B\}}	||	krtd| d |	}|d|d  |d7 }qW 5 Q R X ||fS )NzVocabulary path (z) should be a directory-r|   r   r   wr3   r4   rk   TF)indent	sort_keysensure_asciir:   r   z#version: 0.2
c                 S   s   | d S )Nr   r   )kvr   r   r   rg   E  rh   z2CodeGenTokenizer.save_vocabulary.<locals>.<lambda>ri   zSaving vocabulary to zZ: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!rl   r   )ospathisdirloggererrorrq   VOCAB_FILES_NAMESrJ   writerK   dumpsrM   sortedrT   rN   warning)
r[   r   r   r   Z
merge_filefrn   writerr   Ztoken_indexr   r   r   save_vocabulary4  s2      (

z CodeGenTokenizer.save_vocabularyc                 K   s&   | d| j}|s|rd| }||fS )NrD   rl   )poprD   )r[   r   Zis_split_into_wordsr\   rD   r   r   r   prepare_for_tokenizationQ  s    z)CodeGenTokenizer.prepare_for_tokenizationz
np.ndarrayztorch.Tensorz	tf.Tensor)	token_idsskip_special_tokensclean_up_tokenization_spacestruncate_before_patternr   c                    sF   t |}t jf |||d|}|dk	rBt|dkrB| ||}|S )a  
        Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
        tokens and clean up tokenization spaces.

        Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.

        Args:
            token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
                List of tokenized input ids. Can be obtained using the `__call__` method.
            skip_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not to remove special tokens in the decoding.
            clean_up_tokenization_spaces (`bool`, *optional*):
                Whether or not to clean up the tokenization spaces. If `None`, will default to
                `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
            truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
                A list of regular expression strings that will be used to truncate the returned string. This can be
                used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
                of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "


"]`.
            kwargs (additional keyword arguments, *optional*):
                Will be passed to the underlying model specific decode method.

        Returns:
            `str`: The decoded sentence.
        )r   r   r   Nr   )r   rY   _decoderS   truncate)r[   r   r   r   r   r\   Zdecoded_textr]   r   r   r   W  s    !zCodeGenTokenizer.decodec                    s   dd dd |D }t td tj}t|dkrJ d |d    t td tj}t|dkr~ d |d    dd	d  fd
d|D D }t|dkr d t| S  S d S )Nc                 S   s   | | |}|r| S dS )Nr;   )searchstart)stringpattern	start_posmr   r   r   find_re  s    z*CodeGenTokenizer.truncate.<locals>.find_rec                 S   s   g | ]}t |t jqS r   )rV   rW   	MULTILINE)r   r   r   r   r   r     s     z-CodeGenTokenizer.truncate.<locals>.<listcomp>z^printr   z^defr   c                 S   s   g | ]}|d kr|qS )r;   r   )r   posr   r   r   r     s     c                    s   g | ]} |qS r   r   )r   Zterminal
completionr   r   r   r   r     s     )r   rV   finditerr   rS   r   rm   )r[   r   r   Z	terminalsZprintsZdefsZterminals_posr   r   r   r     s    zCodeGenTokenizer.truncate)r0   r1   r1   r1   NFFF)N)N)N)F)FNN)__name__
__module____qualname____doc__r   Zvocab_files_namesrI   rZ   propertyra   rb   rw   r{   r   r   r   r   r   intr   r   rH   r   r   r   r   boolr   r   __classcell__r   r   r]   r   r/   T   sP   7        2
*

  

	   
/r/   )!r   rK   r   	functoolsr   typingr   r   r   r   r   ZnumpynpregexrV   utilsr	   r
   r   r   ZtorchZ
tensorflowtfZtokenization_utilsr   r   Z
get_loggerr   r   r   r(   r.   r/   r   r   r   r   <module>   s*   

