U
    9%eA                  4   @   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	iZdd
diiZd
diZdddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@g4ZG dAdB dBeZdS )C    N)copyfile)AnyDictListOptionalTuple   )
AddedTokenBatchEncodingPreTrainedTokenizer)loggingu   ▁
vocab_filezsentencepiece.bpe.modelz'facebook/mbart-large-50-one-to-many-mmtzchttps://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.modeli   Zar_ARcs_CZde_DEen_XXZes_XXet_EEfi_FIZfr_XXgu_INhi_INit_ITZja_XXkk_KZko_KRlt_LTlv_LVZmy_MMne_NPZnl_XXro_ROru_RUsi_LKtr_TRvi_VNzh_CNaf_ZAaz_AZbn_INfa_IRhe_ILhr_HRid_IDka_GEZkm_KHmk_MKml_INmn_MNmr_INpl_PLps_AFZpt_XXsv_SEsw_KEta_INte_INth_THZtl_XXuk_UAur_PKxh_ZAgl_ESsl_SIc                	       s  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< dDeeeef  dd fddZeedddZeedddZejeddddZedddZeddddZedddZeee dddZeed d!d"Zeed#d$d%Zd&d' ZdEeee e e d(d)d*Z!dFee eee  e"ee d, fd-d.Z#dGee eee  ee d/d0d1Z$eee ee d2d3d4Z%dHee eeee  ee&d7 fd8d9Z'd:d; Z(d<d= Z)edd>d?d@Z*eddAdBdCZ+  Z,S )IMBart50Tokenizeru  
    Construct a MBart50 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).

    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.
        src_lang (`str`, *optional*):
            A string representing the source language.
        tgt_lang (`str`, *optional*):
            A string representing the target language.
        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 classifier token which is used when doing sequence classification (classification of the whole sequence
            instead of per-token classification). It is the first token of the sequence when built with special tokens.
        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 masked language
            modeling. This is the token which the model will try to predict.
        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 MBart50Tokenizer

    >>> tokenizer = MBart50Tokenizer.from_pretrained("facebook/mbart-large-50", src_lang="en_XX", tgt_lang="ro_RO")
    >>> src_text = " UN Chief Says There Is No Military Solution in Syria"
    >>> tgt_text = "Şeful ONU declară că nu există o soluţie militară în Siria"
    >>> model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt")
    >>> # model(**model_inputs) should work
    ```Z	input_idsZattention_maskprefix_tokenssuffix_tokensN</s><s><unk><pad><mask>)sp_model_kwargsreturnc                    sv  t |	trt|	dddn|	}	|
d kr(i n|
_ dg  d<  d   fddtD 7  < tjf j_j	t| |_
ddd	d
d_d_tj_fddttD _dd j D _tjtj j jd< jj dd j D _t jf ||||||||	jd	  |d k	rL|nd_jj _|_j d S )NTF)lstriprstripadditional_special_tokensc                    s   g | ]}| d  kr|qS )rE    ).0code)kwargsrF   o/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/mbart50/tokenization_mbart50.py
<listcomp>   s     z-MBart50Tokenizer.__init__.<locals>.<listcomp>r         r   )r=   r?   r<   r>   c                    s"   i | ]\}}| j |  j qS rF   )sp_model_sizefairseq_offset)rG   irH   selfrF   rJ   
<dictcomp>   s     z-MBart50Tokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS rF   rF   rG   kvrF   rF   rJ   rS      s      r@   c                 S   s   i | ]\}}||qS rF   rF   rT   rF   rF   rJ   rS      s      )	src_langtgt_lang	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokenrA   r   )
isinstancestrr	   rA   getFAIRSEQ_LANGUAGE_CODESspmSentencePieceProcessorsp_modelLoadr   fairseq_tokens_to_idsrO   lenrN   	enumeratelang_code_to_iditemsZid_to_lang_codeupdatefairseq_ids_to_tokenssuper__init__	_src_langcur_lang_code_idrX   set_src_lang_special_tokens)rR   r   rW   rX   rY   r[   r\   rZ   r]   r^   rA   rI   	__class__)rI   rR   rJ   ro   t   sH    
	
 
zMBart50Tokenizer.__init__)rB   c                 C   s   t | jt | j | j d S )NrL   )rh   re   rj   rO   rQ   rF   rF   rJ   
vocab_size   s    zMBart50Tokenizer.vocab_sizec                 C   s   | j S N)rp   rQ   rF   rF   rJ   rW      s    zMBart50Tokenizer.src_lang)new_src_langrB   c                 C   s   || _ | | j  d S rv   )rp   rr   )rR   rw   rF   rF   rJ   rW      s    c                 C   s   | j  }d |d< |S )Nre   )__dict__copy)rR   staterF   rF   rJ   __getstate__   s    
zMBart50Tokenizer.__getstate__)drB   c                 C   s8   || _ t| dsi | _tjf | j| _| j| j d S )NrA   )rx   hasattrrA   rc   rd   re   rf   r   )rR   r|   rF   rF   rJ   __setstate__   s
    
zMBart50Tokenizer.__setstate__c                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS rF   )Zconvert_ids_to_tokens)rG   rP   rQ   rF   rJ   rS      s      z.MBart50Tokenizer.get_vocab.<locals>.<dictcomp>)rangeru   rl   Zadded_tokens_encoder)rR   ZvocabrF   rQ   rJ   	get_vocab   s    zMBart50Tokenizer.get_vocab)textrB   c                 C   s   | j j|tdS )N)Zout_type)re   encoder`   )rR   r   rF   rF   rJ   	_tokenize   s    zMBart50Tokenizer._tokenize)tokenrB   c                 C   s4   || j kr| j | S | j|}|r.|| j S | jS )z0Converts a token (str) in an id using the vocab.)rg   re   Z	PieceToIdrO   Zunk_token_id)rR   r   Zspm_idrF   rF   rJ   _convert_token_to_id   s    

z%MBart50Tokenizer._convert_token_to_id)indexrB   c                 C   s&   || j kr| j | S | j|| j S )z=Converts an index (integer) in a token (str) using the vocab.)rm   re   Z	IdToPiecerO   )rR   r   rF   rF   rJ   _convert_id_to_token   s    

z%MBart50Tokenizer._convert_id_to_tokenc                 C   sp   g }d}d}|D ]F}|| j krH|s*|d7 }|| j|| 7 }d}g }q|| d}q|| j|7 }| S )z:Converts a sequence of tokens (string) in a single string. F T)Zall_special_tokensre   decodeappendstrip)rR   tokensZcurrent_sub_tokensZ
out_stringZprev_is_specialr   rF   rF   rJ   convert_tokens_to_string   s    

z)MBart50Tokenizer.convert_tokens_to_string)save_directoryfilename_prefixrB   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| n8t j	| jst|d}| j }|| W 5 Q R X |fS )NzVocabulary path (z) should be a directory-r   r   wb)ospathisdirloggererrorjoinVOCAB_FILES_NAMESabspathr   isfiler   openre   Zserialized_model_protowrite)rR   r   r   Zout_vocab_filefiZcontent_spiece_modelrF   rF   rJ   save_vocabulary   s     (
z MBart50Tokenizer.save_vocabularyF)token_ids_0token_ids_1already_has_special_tokensrB   c                    sx   |rt  j||ddS dgt| j }dgt| j }|dk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)r   r   r   rL   Nr   )rn   get_special_tokens_maskrh   r:   r;   )rR   r   r   r   Zprefix_onesZsuffix_onesrs   rF   rJ   r     s      z(MBart50Tokenizer.get_special_tokens_mask)r   r   rB   c                 C   s,   |dkr| j | | j S | j | | | j S )a\  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. An MBART-50 sequence has the following format, where `X` represents the sequence:

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

        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;   )rR   r   r   rF   rF   rJ    build_inputs_with_special_tokens-  s    z1MBart50Tokenizer.build_inputs_with_special_tokens)return_tensorsrW   rX   c                 K   sJ   |dks|dkrt d|| _| |fd|d|}| |}||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)
ValueErrorrW   Zconvert_tokens_to_ids)rR   Z
raw_inputsr   rW   rX   extra_kwargsinputsZtgt_lang_idrF   rF   rJ   _build_translation_inputsH  s    
z*MBart50Tokenizer._build_translation_inputsr   r   )	src_textsrW   	tgt_textsrX   rB   c                    s   || _ || _t j||f|S rv   )rW   rX   rn   prepare_seq2seq_batch)rR   r   rW   r   rX   rI   rs   rF   rJ   r   T  s    z&MBart50Tokenizer.prepare_seq2seq_batchc                 C   s   |  | jS rv   )rr   rW   rQ   rF   rF   rJ   _switch_to_input_mode`  s    z&MBart50Tokenizer._switch_to_input_modec                 C   s   |  | jS rv   )set_tgt_lang_special_tokensrX   rQ   rF   rF   rJ   _switch_to_target_modec  s    z'MBart50Tokenizer._switch_to_target_mode)rW   rB   c                 C   s$   | j | | _| jg| _| jg| _dS )z]Reset the special tokens to the source lang setting. prefix=[src_lang_code] and suffix=[eos].Nrj   rq   r:   Zeos_token_idr;   )rR   rW   rF   rF   rJ   rr   f  s    
z,MBart50Tokenizer.set_src_lang_special_tokens)rX   rB   c                 C   s$   | j | | _| jg| _| jg| _dS )zaReset the special tokens to the target language setting. prefix=[tgt_lang_code] and suffix=[eos].Nr   )rR   rX   rF   rF   rJ   r   l  s    
z,MBart50Tokenizer.set_tgt_lang_special_tokens)	NNr<   r<   r=   r>   r?   r@   N)N)NF)N)r   Nr   )-__name__
__module____qualname____doc__r   Zvocab_files_names&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_mapZmodel_input_namesr:   r   int__annotations__r;   r   r   r`   r   ro   propertyru   rW   setterr{   r~   r   r   r   r   r   r   r   boolr   r   r   r
   r   r   r   rr   r   __classcell__rF   rF   rs   rJ   r9   1   s   
:         D
	    
   
     
r9   )r   shutilr   typingr   r   r   r   r   Zsentencepiecerc   Ztokenization_utilsr	   r
   r   utilsr   Z
get_loggerr   r   ZSPIECE_UNDERLINEr   r   r   rb   r9   rF   rF   rF   rJ   <module>   s$   
	 l