U
    ,-e7                     @   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 ddl	Z
ddlmZmZ ddlmZ eeZdd	d
Zddddddddddddd
ZddddddZe dd Zdd ZG dd deZdS )z$Tokenization classes for OpenAI GPT.    N)	lru_cache)ListOptionalTuple   )
AddedTokenPreTrainedTokenizer)loggingz
vocab.jsonz
merges.txt)
vocab_filemerges_filez3https://huggingface.co/gpt2/resolve/main/vocab.jsonz:https://huggingface.co/gpt2-medium/resolve/main/vocab.jsonz9https://huggingface.co/gpt2-large/resolve/main/vocab.jsonz6https://huggingface.co/gpt2-xl/resolve/main/vocab.jsonz9https://huggingface.co/distilgpt2/resolve/main/vocab.json)Zgpt2zgpt2-mediumz
gpt2-largezgpt2-xlZ
distilgpt2z3https://huggingface.co/gpt2/resolve/main/merges.txtz:https://huggingface.co/gpt2-medium/resolve/main/merges.txtz9https://huggingface.co/gpt2-large/resolve/main/merges.txtz6https://huggingface.co/gpt2-xl/resolve/main/merges.txtz9https://huggingface.co/distilgpt2/resolve/main/merges.txti   c                  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   k/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/gpt2/tokenization_gpt2.py
<listcomp>S   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_pairsW   s    r)   c                       s   e Zd ZdZeZe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&ee eee  eee d fddZdd Zdd Zdd Zdd Zd'eee ee dddZd(d d!Zed"d# Z  ZS ))GPT2Tokenizera  
    Construct a GPT-2 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 GPT2Tokenizer

    >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
    >>> 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.
        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. (GPT2 tokenizer detect beginning of words by the preceding space).
    Z	input_idsZattention_maskreplace<|endoftext|>NFc
              
      sf  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|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 )NF)lstriprstriputf-8encodingc                 S   s   i | ]\}}||qS r   r   r   kvr   r   r   
<dictcomp>   s      z*GPT2Tokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r   r   r2   r   r   r   r5      s      
r   c                 S   s   g | ]}t | qS r   )tuplesplit)r   merger   r   r   r      s     z*GPT2Tokenizer.__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)
isinstancestrr   rA   openjsonloadencoderitemsdecoderr;   r#   byte_encoderbyte_decoderreadr9   r   r   r   len	bpe_rankscacher@   recompilepatsuper__init__)selfr
   r   r;   r<   r=   r>   r?   r@   rA   kwargsZvocab_handleZmerges_handleZ
bpe_merges	__class__r   r   rT      s:     zGPT2Tokenizer.__init__c                 C   s
   t | jS N)rM   rG   rU   r   r   r   
vocab_size   s    zGPT2Tokenizer.vocab_sizec                 C   s   t | jf| jS rY   )r   rG   Zadded_tokens_encoderrZ   r   r   r   	get_vocab   s    zGPT2Tokenizer.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)rN   getfloat)pairrZ   r   r   <lambda>       z#GPT2Tokenizer.bpe.<locals>.<lambda>keyr   r       )rO   r8   r)   minrN   rM   index
ValueErrorextendr   join)
rU   tokenr&   r'   ZbigramfirstsecondZnew_wordijr   rZ   r   bpe   sB    


2




zGPT2Tokenizer.bpec                 C   s4   | j r| jg}ng }|| }|d kr(|S || | S rY   )rA   Zbos_token_id)rU   token_ids_0token_ids_1Zbos_token_idsoutputr   r   r    build_inputs_with_special_tokens   s    
z.GPT2Tokenizer.build_inputs_with_special_tokens)rr   rs   already_has_special_tokensreturnc                    sr   |rt  j||ddS | js.t  j||ddS |dkrJdgdgt|  S dgdgt|  dg dgt|  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)rr   rs   rv   FNr   r   )rS   get_special_tokens_maskrA   rM   )rU   rr   rs   rv   rW   r   r   rx   	  s        z%GPT2Tokenizer.get_special_tokens_maskc                    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 rY   )rJ   )r   r"   rZ   r   r   	<genexpr>-  s    z*GPT2Tokenizer._tokenize.<locals>.<genexpr>r/   c                 s   s   | ]
}|V  qd S rY   r   )r   Z	bpe_tokenr   r   r   rz   0  s     rf   )rP   findallrR   rk   encoderj   rq   r9   )rU   text
bpe_tokensrl   r   rZ   r   	_tokenize)  s    "zGPT2Tokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)rG   r^   r<   )rU   rl   r   r   r   _convert_token_to_id3  s    z"GPT2Tokenizer._convert_token_to_idc                 C   s   | j |S )z=Converts an index (integer) in a token (str) using the vocab.)rI   r^   )rU   rh   r   r   r   _convert_id_to_token7  s    z"GPT2Tokenizer._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.ry   c                    s   g | ]} j | qS r   )rK   )r   crZ   r   r   r   >  s     z:GPT2Tokenizer.convert_tokens_to_string.<locals>.<listcomp>r/   )r;   )rk   	bytearraydecoder;   )rU   tokensr}   r   rZ   r   convert_tokens_to_string;  s    
"z&GPT2Tokenizer.convert_tokens_to_string)save_directoryfilename_prefixrw   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-ry   r
   r   wr/   r0   re   TF)indent	sort_keysensure_asciir6   r   z#version: 0.2
c                 S   s   | d S )Nr   r   )kvr   r   r   ra   R  rb   z/GPT2Tokenizer.save_vocabulary.<locals>.<lambda>rc   zSaving vocabulary to zZ: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!rf   r   )ospathisdirloggererrorrk   VOCAB_FILES_NAMESrD   writerE   dumpsrG   sortedrN   rH   warning)
rU   r   r   r
   Z
merge_filefrh   writerr~   Ztoken_indexr   r   r   save_vocabularyA  s2      (

zGPT2Tokenizer.save_vocabularyc                 K   s&   | d| j}|s|rd| }||fS )Nr@   rf   )popr@   )rU   r}   Zis_split_into_wordsrV   r@   r   r   r   prepare_for_tokenization^  s    z&GPT2Tokenizer.prepare_for_tokenizationc                 C   s   dS )zv
        A simple chat template that ignores role information and just concatenates messages with EOS tokens.
        zM{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}r   rZ   r   r   r   default_chat_templated  s    z#GPT2Tokenizer.default_chat_template)r+   r,   r,   r,   NFF)N)NF)N)F) __name__
__module____qualname____doc__r   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_map&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesZmodel_input_namesrT   propertyr[   r\   rq   ru   r   intr   boolrx   r   r   r   r   rC   r   r   r   r   __classcell__r   r   rW   r   r*   e   sD   1       /
*
    
  

r*   )r   rE   r   	functoolsr   typingr   r   r   regexrP   Ztokenization_utilsr   r   utilsr	   Z
get_loggerr   r   r   r   r   r#   r)   r*   r   r   r   r   <module>   sD   
	
