a
    hI                     @   s   d dl Z d dlmZ d dlmZmZ d dlZddlm	Z	m
Z
mZ ddlmZ ddlmZ eeZdZd	d
dZg dg ddZddddddddZeddG dd deZdgZdS )    N)copyfile)AnyOptional   )
AddedTokenBatchEncodingPreTrainedTokenizer)logging)requiresu   ▁zsentencepiece.bpe.modelztokenizer.json)
vocab_filetokenizer_file)__java__
__python__	__en_XX__)r   r   r   __javascript____php____ruby____go__)basemultir   r   r   r   r   r   r   )javapythonen_XX
javascriptphprubygo)sentencepiece)backendsc                       s  e Zd ZU dZeZddgZg Zee	 e
d< g Zee	 e
d< dFeeeef  d fddZdd Zdd Zedd ZeedddZejeddddZdGee	 eee	  eee	 d fddZdHee	 eee	  ee	 d d!d"ZdIee	 eee	  ee	 d d#d$Zeee ee d%d&d'Zd(d) Zeee d*d+d,Zd-d. Zd/d0 Zd1d2 Z dJeee e!e d3d4d5Z"dKee eeee  ee#d8 fd9d:Z$d;d< Z%d=d> Z&ddd?d@Z'eddAdBdCZ(eedAdDdEZ)  Z*S )LPLBartTokenizera  
    Construct an PLBART tokenizer.

    Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
    [SentencePiece](https://github.com/google/sentencepiece).

    The tokenization method is `<tokens> <eos> <language code>` for source language documents, and `<language code>
    <tokens> <eos>` for target language documents.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        src_lang (`str`, *optional*):
            A string representing the source language.
        tgt_lang (`str`, *optional*):
            A string representing the target language.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The start of sequence token.
        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.
        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 cls token, which is a special token used as the first token for all tasks.
        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 masking tasks. This
            is only used in the `"base"` tokenizer type. For `"multi"` tokenizer, masking is never done for the
            downstream tasks.
        language_codes (`str`, *optional*, defaults to `"base"`):
            What language codes to use. Should be one of `"base"` or `"multi"`.
        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.

    Examples:

    ```python
    >>> from transformers import PLBartTokenizer

    >>> tokenizer = PLBartTokenizer.from_pretrained("uclanlp/plbart-python-en_XX", src_lang="python", tgt_lang="en_XX")
    >>> example_python_phrase = "def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])"
    >>> expected_translation_english = "Returns the maximum value of a b c."
    >>> inputs = tokenizer(example_python_phrase, text_target=expected_translation_english, return_tensors="pt")
    ```Z	input_idsZattention_maskprefix_tokenssuffix_tokens<s></s><unk><pad><mask>r   NT)sp_model_kwargsc                    s  t |trt|dddn|}|d u r(i n|_|}|}tjf i j_jt| |_	|	_
tj
 }ddddd_d_tj_fd	d
t|D _dd
 j D _j
dkrtjtj j jd< jj dd
 j D _tj  |d urJ  fdd|D  j
dkr~|_jd urtjj nj_n"|d ur|nd_jj _t jf ||||||||	|
|| j|d| |_j d S )NTF)lstriprstripr         r   )r"   r%   r#   r$   c                    s"   i | ]\}}| j |  j qS  )sp_model_sizefairseq_offset).0icodeselfr,   j/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/plbart/tokenization_plbart.py
<dictcomp>   s   z,PLBartTokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r,   r,   r/   kvr,   r,   r4   r5          r   r&   c                 S   s   i | ]\}}||qS r,   r,   r6   r,   r,   r4   r5      r9   c                    s   g | ]}| vr|qS r,   r,   )r/   t)_additional_special_tokensr,   r4   
<listcomp>   r9   z,PLBartTokenizer.__init__.<locals>.<listcomp>r   )	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokenlanguage_codesr   src_langtgt_langadditional_special_tokensr'   clean_up_tokenization_spaces)
isinstancestrr   r'   !_convert_lang_code_special_formatspmSentencePieceProcessorsp_modelLoadr   rD   FAIRSEQ_LANGUAGE_CODESfairseq_tokens_to_idsr.   lenr-   	enumeratelang_code_to_iditemsZid_to_lang_codeupdatefairseq_ids_to_tokenslistkeysextend	_src_langZcur_lang_code_idsuper__init__rF   set_src_lang_special_tokens)r3   r   r=   r>   r@   rA   r?   rB   rC   rD   r   rE   rF   r'   rG   rH   kwargsZfairseq_language_codes	__class__)r;   r3   r4   r]   w   sf    


	

 
zPLBartTokenizer.__init__c                 C   s$   | j  }d |d< | j |d< |S )NrN   sp_model_proto)__dict__copyrN   serialized_model_proto)r3   stater,   r,   r4   __getstate__   s    
zPLBartTokenizer.__getstate__c                 C   s<   || _ t| dsi | _tjf i | j| _| j| j d S )Nr'   )rc   hasattrr'   rL   rM   rN   ZLoadFromSerializedProtorb   )r3   dr,   r,   r4   __setstate__   s
    
zPLBartTokenizer.__setstate__c                 C   sF   | j dkr(t| jt| j | j d S t| jt| j | j S d S )Nr   r*   )rD   rR   rN   rT   r.   r2   r,   r,   r4   
vocab_size   s    
zPLBartTokenizer.vocab_size)returnc                 C   s   | j S N)r[   r2   r,   r,   r4   rE      s    zPLBartTokenizer.src_lang)new_src_langrl   c                 C   s    |  |}|| _| | j d S rm   )rK   r[   r^   )r3   rn   r,   r,   r4   rE      s    
F)token_ids_0token_ids_1already_has_special_tokensrl   c                    sx   |rt  j||ddS dgt| j }dgt| j }|du rT|dgt|  | S |dgt|  dgt|  | 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)ro   rp   rq   r*   Nr   )r\   get_special_tokens_maskrR   r    r!   )r3   ro   rp   rq   Zprefix_onesZsuffix_onesr`   r,   r4   rr      s    z'PLBartTokenizer.get_special_tokens_mask)ro   rp   rl   c                 C   s,   |du r| j | | j S | j | | | j S )ac  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. An PLBART sequence has the following format, where `X` represents the sequence:

        - `input_ids` (for encoder) `X [eos, src_lang_code]`
        - `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]`

        BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a
        separator.

        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)r    r!   )r3   ro   rp   r,   r,   r4    build_inputs_with_special_tokens  s    z0PLBartTokenizer.build_inputs_with_special_tokensc                 C   sP   | j g}| jg}|du r.t|| | dg S t|| | | | | dg S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. PLBart 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   )Zsep_token_idZcls_token_idrR   )r3   ro   rp   sepclsr,   r,   r4   $create_token_type_ids_from_sequences1  s
    z4PLBartTokenizer.create_token_type_ids_from_sequences)return_tensorsrE   rF   c                 K   s^   |du s|du rt d| || _| || _| |fd|d|}| | j}||d< |S )zIUsed by translation pipeline, to prepare inputs for the generate functionNzATranslation requires a `src_lang` and a `tgt_lang` for this modelT)Zadd_special_tokensrw   Zforced_bos_token_id)
ValueErrorrK   rE   rF   Zconvert_tokens_to_ids)r3   Z
raw_inputsrw   rE   rF   extra_kwargsinputsZtgt_lang_idr,   r,   r4   _build_translation_inputsI  s    z)PLBartTokenizer._build_translation_inputsc                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r,   )Zconvert_ids_to_tokens)r/   r0   r2   r,   r4   r5   W  r9   z-PLBartTokenizer.get_vocab.<locals>.<dictcomp>)rangerk   rV   Zadded_tokens_encoder)r3   Zvocabr,   r2   r4   	get_vocabV  s    zPLBartTokenizer.get_vocab)textrl   c                 C   s   | j j|tdS )N)Zout_type)rN   encoderJ   )r3   r~   r,   r,   r4   	_tokenize[  s    zPLBartTokenizer._tokenizec                 C   s4   || j v r| j | S | j|}|r.|| j S | jS )z0Converts a token (str) in an id using the vocab.)rQ   rN   Z	PieceToIdr.   Zunk_token_id)r3   tokenZspm_idr,   r,   r4   _convert_token_to_id^  s    

z$PLBartTokenizer._convert_token_to_idc                 C   s&   || j v r| j | S | j|| j S )z=Converts an index (integer) in a token (str) using the vocab.)rW   rN   Z	IdToPiecer.   )r3   indexr,   r,   r4   _convert_id_to_tokeng  s    

z$PLBartTokenizer._convert_id_to_tokenc                 C   s   d |td }|S )zIConverts a sequence of tokens (strings for sub-words) in a single string.  )joinreplaceSPIECE_UNDERLINEstrip)r3   tokensZ
out_stringr,   r,   r4   convert_tokens_to_stringm  s    z(PLBartTokenizer.convert_tokens_to_string)save_directoryfilename_prefixrl   c                 C   s   t j|s"td| d d S t j||r6|d ndtd  }t j| jt j|krzt j	| jrzt
| j| nLt j	| jst|d$}| j }|| W d    n1 s0    Y  |fS )NzVocabulary path (z) should be a directory-r   r   wb)ospathisdirloggererrorr   VOCAB_FILES_NAMESabspathr   isfiler   openrN   re   write)r3   r   r   Zout_vocab_filefiZcontent_spiece_modelr,   r,   r4   save_vocabularyr  s    (
(zPLBartTokenizer.save_vocabularyr   r   )	src_textsrE   	tgt_textsrF   rl   c                    s.   |  || _|  || _t j||fi |S rm   )rK   rE   rF   r\   prepare_seq2seq_batch)r3   r   rE   r   rF   r_   r`   r,   r4   r     s    z%PLBartTokenizer.prepare_seq2seq_batchc                 C   s   |  | jS rm   )r^   rE   r2   r,   r,   r4   _switch_to_input_mode  s    z%PLBartTokenizer._switch_to_input_modec                 C   s   |  | jS rm   )set_tgt_lang_special_tokensrF   r2   r,   r,   r4   _switch_to_target_mode  s    z&PLBartTokenizer._switch_to_target_modec                 C   sP   |  |}|dur| j| nd| _g | _| jdurB| j| jg| _n
| jg| _dS )z_Reset the special tokens to the source lang setting. No prefix and suffix=[eos, src_lang_code].NrK   rT   Zcur_lang_coder    Zeos_token_idr!   )r3   rE   r,   r,   r4   r^     s    

z+PLBartTokenizer.set_src_lang_special_tokens)langrl   c                 C   sP   |  |}|dur| j| nd| _g | _| jdurB| j| jg| _n
| jg| _dS )zcReset the special tokens to the target language setting. No prefix and suffix=[eos, tgt_lang_code].Nr   r3   r   r,   r,   r4   r     s    

z+PLBartTokenizer.set_tgt_lang_special_tokensc                 C   s   t ||}|S )z;Convert Language Codes to format tokenizer uses if required)FAIRSEQ_LANGUAGE_CODES_MAPgetr   r,   r,   r4   rK     s    z1PLBartTokenizer._convert_lang_code_special_format)r"   r#   r#   r"   r$   r%   r&   r   NNNNNT)NF)N)N)N)r   Nr   )+__name__
__module____qualname____doc__r   Zvocab_files_namesZmodel_input_namesr    rX   int__annotations__r!   r   dictrJ   r   r]   rg   rj   propertyrk   rE   setterboolrr   rs   rv   r{   r}   r   r   r   r   tupler   r   r   r   r   r^   r   rK   __classcell__r,   r,   r`   r4   r   2   s   
=              ^

   	   

r   )r   shutilr   typingr   r   r   rL   Ztokenization_utilsr   r   r   utilsr	   Zutils.import_utilsr
   Z
get_loggerr   r   r   r   rP   r   r   __all__r,   r,   r,   r4   <module>   s4   

    