o
    ZhJ                     @   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 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DictListOptionalTuple   )
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                       s2  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< 								
							dKd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	dLdee	 deee	  dedee	 f fd d!Z	dMdee	 deee	  dee	 fd"d#Z	dMd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d0d1 Zd2d3 Zd4d5 Z dMd6ed7ee de!e fd8d9Z"	:		;dNd<ee d'ed=eee  d(ede#f
 fd>d?Z$d@dA Z%dBdC Z&dOdDdEZ'dFeddfdGdHZ(dFedefdIdJZ)  Z*S )P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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/   ]/var/www/auris/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/   r2   kvr/   r/   r7   r8          r   r)   c                 S   r9   r/   r/   r:   r/   r/   r7   r8      r=   c                    s   g | ]}| vr|qS r/   r/   )r2   t)_additional_special_tokensr/   r7   
<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*   clean_up_tokenization_spacesr/   )
isinstancestrr	   r*   !_convert_lang_code_special_formatspmSentencePieceProcessorsp_modelLoadr   rI   FAIRSEQ_LANGUAGE_CODESfairseq_tokens_to_idsr1   lenr0   	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__rK   set_src_lang_special_tokens)r6   r   rB   rC   rE   rF   rD   rG   rH   rI   r   rJ   rK   r*   rL   rM   kwargsZfairseq_language_codes	__class__)r?   r6   r7   rb   w   sf   


	

 
zPLBartTokenizer.__init__c                 C   s$   | j  }d |d< | j |d< |S )NrS   sp_model_proto)__dict__copyrS   serialized_model_proto)r6   stater/   r/   r7   __getstate__   s   
zPLBartTokenizer.__getstate__c                 C   s<   || _ t| dsi | _tjdi | j| _| j| j d S )Nr*   r/   )rh   hasattrr*   rQ   rR   rS   ZLoadFromSerializedProtorg   )r6   dr/   r/   r7   __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-   )rI   rW   rS   rY   r1   r5   r/   r/   r7   
vocab_size   s   
zPLBartTokenizer.vocab_sizereturnc                 C   s   | j S N)r`   r5   r/   r/   r7   rJ      s   zPLBartTokenizer.src_langnew_src_langc                 C   s    |  |}|| _| | j d S rr   )rP   r`   rc   )r6   rs   r/   r/   r7   rJ      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)rt   ru   rv   r-   Nr   )ra   get_special_tokens_maskrW   r#   r$   )r6   rt   ru   rv   Zprefix_onesZsuffix_onesre   r/   r7   rw      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$   )r6   rt   ru   r/   r/   r7    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_idrW   )r6   rt   ru   sepclsr/   r/   r7   $create_token_type_ids_from_sequences1  s
   "z4PLBartTokenizer.create_token_type_ids_from_sequencesreturn_tensorsrJ   rK   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_tokensr|   Zforced_bos_token_id)
ValueErrorrP   rJ   rK   Zconvert_tokens_to_ids)r6   Z
raw_inputsr|   rJ   rK   extra_kwargsZinputsZtgt_lang_idr/   r/   r7   _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)r2   r3   r5   r/   r7   r8   W  rA   z-PLBartTokenizer.get_vocab.<locals>.<dictcomp>)rangerp   r[   Zadded_tokens_encoder)r6   Zvocabr/   r5   r7   	get_vocabV  s   zPLBartTokenizer.get_vocabtextc                 C   s   | j j|tdS )N)Zout_type)rS   encoderO   )r6   r   r/   r/   r7   	_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.)rV   rS   Z	PieceToIdr1   Zunk_token_id)r6   tokenZspm_idr/   r/   r7   _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\   rS   Z	IdToPiecer1   )r6   indexr/   r/   r7   _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)r6   tokensZ
out_stringr/   r/   r7   convert_tokens_to_stringm  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   openrS   rj   write)r6   r   r   Zout_vocab_filefiZcontent_spiece_modelr/   r/   r7   save_vocabularyr  s"   (

zPLBartTokenizer.save_vocabularyr   r   	src_texts	tgt_textsc                    s.   |  || _|  || _t j||fi |S rr   )rP   rJ   rK   ra   prepare_seq2seq_batch)r6   r   rJ   r   rK   rd   re   r/   r7   r     s   z%PLBartTokenizer.prepare_seq2seq_batchc                 C      |  | jS rr   )rc   rJ   r5   r/   r/   r7   _switch_to_input_mode     z%PLBartTokenizer._switch_to_input_modec                 C   r   rr   )set_tgt_lang_special_tokensrK   r5   r/   r/   r7   _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rP   rY   Zcur_lang_coder#   Zeos_token_idr$   )r6   rJ   r/   r/   r7   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   r6   r   r/   r/   r7   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/   r7   rP     s   z1PLBartTokenizer._convert_lang_code_special_format)r%   r&   r&   r%   r'   r(   r)   r   NNNNNT)NFrr   )r   Nr   )rq   N)+__name__
__module____qualname____doc__r   Zvocab_files_namesZmodel_input_namesr#   r   int__annotations__r$   r   r   rO   r   rb   rl   ro   propertyrp   rJ   setterboolrw   rx   r{   r   r   r   r   r   r   r   r   r
   r   r   r   rc   r   rP   __classcell__r/   r/   re   r7   r"   2   s   
 =^







	 


r"   )r   shutilr   typingr   r   r   r   r   r    rQ   Ztokenization_utilsr	   r
   r   utilsr   Zutils.import_utilsr   Z
get_loggerr   r   r   r   rU   r   r"   __all__r/   r/   r/   r7   <module>   s4   

  
