o
    hT                     @   s   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mZ ddlmZ eeZdZdd	d
ZddddddddddddddddiZdddddddddddddddZg dg ddZdd d!d"d#d$d%d&ZG d'd( d(eZdS ))    N)copyfile)AnyDictListOptionalTuple   )
AddedTokenBatchEncodingPreTrainedTokenizer)loggingu   ▁zsentencepiece.bpe.modelztokenizer.json)
vocab_filetokenizer_filer   zOhttps://huggingface.co/uclanlp/plbart-base/resolve/main/sentencepiece.bpe.modelzahttps://huggingface.co/uclanlp/plbart-c-cpp-defect-detection/resolve/main/sentencepiece.bpe.modelzRhttps://huggingface.co/uclanlp/plbart-cs-java/resolve/main/sentencepiece.bpe.modelzUhttps://huggingface.co/uclanlp/plbart-en_XX-java/resolve/main/sentencepiece.bpe.modelzShttps://huggingface.co/uclanlp/plbart-go-en_XX/resolve/main/sentencepiece.bpe.modelz_https://huggingface.co/uclanlp/plbart-java-clone-detection/resolve/main/sentencepiece.bpe.modelzRhttps://huggingface.co/uclanlp/plbart-java-cs/resolve/main/sentencepiece.bpe.modelzUhttps://huggingface.co/uclanlp/plbart-java-en_XX/resolve/main/sentencepiece.bpe.modelz[https://huggingface.co/uclanlp/plbart-javascript-en_XX/resolve/main/sentencepiece.bpe.modelzThttps://huggingface.co/uclanlp/plbart-php-en_XX/resolve/main/sentencepiece.bpe.modelzWhttps://huggingface.co/uclanlp/plbart-python-en_XX/resolve/main/sentencepiece.bpe.modelz]https://huggingface.co/uclanlp/plbart-refine-java-medium/resolve/main/sentencepiece.bpe.modelz\https://huggingface.co/uclanlp/plbart-refine-java-small/resolve/main/sentencepiece.bpe.modelzUhttps://huggingface.co/uclanlp/plbart-ruby-en_XX/resolve/main/sentencepiece.bpe.model)zuclanlp/plbart-basez%uclanlp/plbart-c-cpp-defect-detectionzuclanlp/plbart-cs-javazuclanlp/plbart-en_XX-javazuclanlp/plbart-go-en_XXz#uclanlp/plbart-java-clone-detectionzuclanlp/plbart-java-cszuclanlp/plbart-java-en_XXzuclanlp/plbart-javascript-en_XXzuclanlp/plbart-php-en_XXzuclanlp/plbart-python-en_XXz!uclanlp/plbart-refine-java-mediumz uclanlp/plbart-refine-java-smallzuclanlp/plbart-ruby-en_XXi   )__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goc                       s8  e Zd ZU dZeZeZeZ	ddgZ
g Zee ed< g Zee ed< 								
						dJdeeeef  f fddZdd Zdd Zedd ZedefddZejdeddfddZ	dKdee deee  dedee f fdd Z	dLdee deee  dee fd!d"Z	dLdee deee  dee fd#d$Zd%ed&ee d'ee fd(d)Zd*d+ Z d,edee fd-d.Z!d/d0 Z"d1d2 Z#d3d4 Z$dLd5ed6ee de%e fd7d8Z&	9		:dMd;ee d&ed<eee  d'ede'f
 fd=d>Z(d?d@ Z)dAdB Z*dNdCdDZ+dEeddfdFdGZ,dEedefdHdIZ-  Z.S )O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")
    ```	input_idsattention_maskprefix_tokenssuffix_tokens<s></s><unk><pad><mask>r   Nsp_model_kwargsc                    s  t |trt|dddn|}|d u ri n|_|}|}tjd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r{tjtj j jd< jj dd
 j D _tj  |d ur  fdd|D  j
dkr|_jd urjj nj_n|d ur|nd_jj _t jd||||||||	|
|| 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.   d/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/plbart/tokenization_plbart.py
<dictcomp>   s    z,PLBartTokenizer.__init__.<locals>.<dictcomp>c                 S      i | ]\}}||qS r.   r.   r1   kvr.   r.   r6   r7          r   r(   c                 S   r8   r.   r.   r9   r.   r.   r6   r7      r<   c                    s   g | ]}| vr|qS r.   r.   )r1   t)_additional_special_tokensr.   r6   
<listcomp>       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)   r.   )
isinstancestrr	   r)   !_convert_lang_code_special_formatspmSentencePieceProcessorsp_modelLoadr   rH   FAIRSEQ_LANGUAGE_CODESfairseq_tokens_to_idsr0   lenr/   	enumeratelang_code_to_iditemsid_to_lang_codeupdatefairseq_ids_to_tokenslistkeysextend	_src_langcur_lang_code_idsuper__init__rJ   set_src_lang_special_tokens)r5   r   rA   rB   rD   rE   rC   rF   rG   rH   r   rI   rJ   r)   rK   kwargsfairseq_language_codes	__class__)r>   r5   r6   rb      sd   


	

 
zPLBartTokenizer.__init__c                 C   s$   | j  }d |d< | j |d< |S )NrQ   sp_model_proto)__dict__copyrQ   serialized_model_proto)r5   stater.   r.   r6   __getstate__  s   
zPLBartTokenizer.__getstate__c                 C   s<   || _ t| dsi | _tjdi | j| _| j| j d S )Nr)   r.   )ri   hasattrr)   rO   rP   rQ   LoadFromSerializedProtorh   )r5   dr.   r.   r6   __setstate__  s
   
zPLBartTokenizer.__setstate__c                 C   sB   | j dkrt| jt| j | j d S t| jt| j | j S )Nr   r,   )rH   rU   rQ   rW   r0   r4   r.   r.   r6   
vocab_size  s   
zPLBartTokenizer.vocab_sizereturnc                 C   s   | j S N)r_   r4   r.   r.   r6   rI   %  s   zPLBartTokenizer.src_langnew_src_langc                 C   s    |  |}|| _| | j d S rt   )rN   r_   rc   )r5   ru   r.   r.   r6   rI   )  s   
Ftoken_ids_0token_ids_1already_has_special_tokensc                    sx   |rt  j||ddS dgt| j }dgt| j }|du r*|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)rv   rw   rx   r,   Nr   )ra   get_special_tokens_maskrU   r"   r#   )r5   rv   rw   rx   prefix_onessuffix_onesrf   r.   r6   ry   /  s   $z'PLBartTokenizer.get_special_tokens_maskc                 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#   )r5   rv   rw   r.   r.   r6    build_inputs_with_special_tokensM  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   )sep_token_idcls_token_idrU   )r5   rv   rw   sepclsr.   r.   r6   $create_token_type_ids_from_sequencesh  s
   "z4PLBartTokenizer.create_token_type_ids_from_sequencesreturn_tensorsrI   rJ   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)add_special_tokensr   forced_bos_token_id)
ValueErrorrN   rI   rJ   convert_tokens_to_ids)r5   
raw_inputsr   rI   rJ   extra_kwargsinputstgt_lang_idr.   r.   r6   _build_translation_inputs  s   z)PLBartTokenizer._build_translation_inputsc                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r.   )convert_ids_to_tokens)r1   r2   r4   r.   r6   r7     r@   z-PLBartTokenizer.get_vocab.<locals>.<dictcomp>)rangerr   rZ   added_tokens_encoder)r5   vocabr.   r4   r6   	get_vocab  s   zPLBartTokenizer.get_vocabtextc                 C   s   | j j|tdS )N)out_type)rQ   encoderM   )r5   r   r.   r.   r6   	_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.)rT   rQ   	PieceToIdr0   unk_token_id)r5   tokenspm_idr.   r.   r6   _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.)r[   rQ   	IdToPiecer0   )r5   indexr.   r.   r6   _convert_id_to_token  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)r5   tokens
out_stringr.   r.   r6   convert_tokens_to_string  s   z(PLBartTokenizer.convert_tokens_to_stringsave_directoryfilename_prefixc                 C   s   t j|std| d d S t j||r|d ndtd  }t j| jt j|kr?t j	| jr?t
| j| |fS t j	| jsgt|d}| j }|| W d    |fS 1 sbw   Y  |fS )NzVocabulary path (z) should be a directory-r   r   wb)ospathisdirloggererrorr   VOCAB_FILES_NAMESabspathr   isfiler   openrQ   rk   write)r5   r   r   out_vocab_fileficontent_spiece_modelr.   r.   r6   save_vocabulary  s"   (

zPLBartTokenizer.save_vocabularyr   r   	src_texts	tgt_textsc                    s.   |  || _|  || _t j||fi |S rt   )rN   rI   rJ   ra   prepare_seq2seq_batch)r5   r   rI   r   rJ   rd   rf   r.   r6   r     s   z%PLBartTokenizer.prepare_seq2seq_batchc                 C      |  | jS rt   )rc   rI   r4   r.   r.   r6   _switch_to_input_mode     z%PLBartTokenizer._switch_to_input_modec                 C   r   rt   )set_tgt_lang_special_tokensrJ   r4   r.   r.   r6   _switch_to_target_mode  r   z&PLBartTokenizer._switch_to_target_modec                 C   R   |  |}|dur| j| nd| _g | _| jdur"| j| jg| _dS | jg| _dS )z_Reset the special tokens to the source lang setting. No prefix and suffix=[eos, src_lang_code].NrN   rW   cur_lang_coder"   eos_token_idr#   )r5   rI   r.   r.   r6   rc     s   

z+PLBartTokenizer.set_src_lang_special_tokenslangc                 C   r   )zcReset the special tokens to the target language setting. No prefix and suffix=[eos, tgt_lang_code].Nr   r5   r   r.   r.   r6   r     s   

z+PLBartTokenizer.set_tgt_lang_special_tokensc                 C   s    |t  v rt | }|S |}|S )z;Convert Language Codes to format tokenizer uses if required)FAIRSEQ_LANGUAGE_CODES_MAPr]   r   r.   r.   r6   rN     s   z1PLBartTokenizer._convert_lang_code_special_format)r$   r%   r%   r$   r&   r'   r(   r   NNNNN)NFrt   )r   Nr   )rs   N)/__name__
__module____qualname____doc__r   vocab_files_names&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESmax_model_input_sizesPRETRAINED_VOCAB_FILES_MAPpretrained_vocab_files_mapmodel_input_namesr"   r   int__annotations__r#   r   r   rM   r   rb   rm   rq   propertyrr   rI   setterboolry   r|   r   r   r   r   r   r   r   r   r   r
   r   r   r   rc   r   rN   __classcell__r.   r.   rf   r6   r   j   s   
 =\







	 


r   )r   shutilr   typingr   r   r   r   r   sentencepiecerO   tokenization_utilsr	   r
   r   utilsr   
get_loggerr   r   r   r   r   r   rS   r   r   r.   r.   r.   r6   <module>   sj   

*