
    gyJ                         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j        e          ZdZdd	iZg d
Z G d de          ZdS )    N)copyfile)AnyDictListOptionalTuple   )
AddedTokenBatchEncodingPreTrainedTokenizer)loggingu   ▁
vocab_filezsentencepiece.bpe.model)ace_Arabace_Latnacm_Arabacq_Arabaeb_Arabafr_Latnajp_Arabaka_Latnamh_Ethiapc_Arabarb_Arabars_Arabary_Arabarz_Arabasm_Bengast_Latnawa_Devaayr_Latnazb_Arabazj_Latnbak_Cyrlbam_Latnban_Latnbel_Cyrlbem_Latnben_Bengbho_Devabjn_Arabbjn_Latnbod_Tibtbos_Latnbug_Latnbul_Cyrlcat_Latnceb_Latnces_Latncjk_Latnckb_Arabcrh_Latncym_Latndan_Latndeu_Latndik_Latndyu_Latndzo_Tibtell_Grekeng_Latnepo_Latnest_Latneus_Latnewe_Latnfao_Latnpes_Arabfij_Latnfin_Latnfon_Latnfra_Latnfur_Latnfuv_Latngla_Latngle_Latnglg_Latngrn_Latnguj_Gujrhat_Latnhau_Latnheb_Hebrhin_Devahne_Devahrv_Latnhun_Latnhye_Armnibo_Latnilo_Latnind_Latnisl_Latnita_Latnjav_Latnjpn_Jpankab_Latnkac_Latnkam_Latnkan_Kndakas_Arabkas_Devakat_Georknc_Arabknc_Latnkaz_Cyrlkbp_Latnkea_Latnkhm_Khmrkik_Latnkin_Latnkir_Cyrlkmb_Latnkon_Latnkor_Hangkmr_Latnlao_Laoolvs_Latnlij_Latnlim_Latnlin_Latnlit_Latnlmo_Latnltg_Latnltz_Latnlua_Latnlug_Latnluo_Latnlus_Latnmag_Devamai_Devamal_Mlymmar_Devamin_Latnmkd_Cyrlplt_Latnmlt_Latnmni_Bengkhk_Cyrlmos_Latnmri_Latnzsm_Latnmya_Mymrnld_Latnnno_Latnnob_Latnnpi_Devanso_Latnnus_Latnnya_Latnoci_Latngaz_Latnory_Oryapag_Latnpan_Gurupap_Latnpol_Latnpor_Latnprs_Arabpbt_Arabquy_Latnron_Latnrun_Latnrus_Cyrlsag_Latnsan_Devasat_Bengscn_Latnshn_Mymrsin_Sinhslk_Latnslv_Latnsmo_Latnsna_Latnsnd_Arabsom_Latnsot_Latnspa_Latnals_Latnsrd_Latnsrp_Cyrlssw_Latnsun_Latnswe_Latnswh_Latnszl_Latntam_Tamltat_Cyrltel_Telutgk_Cyrltgl_Latntha_Thaitir_Ethitaq_Latntaq_Tfngtpi_Latntsn_Latntso_Latntuk_Latntum_Latntur_Latntwi_Latntzm_Tfnguig_Arabukr_Cyrlumb_Latnurd_Arabuzn_Latnvec_Latnvie_Latnwar_Latnwol_Latnxho_Latnydd_Hebryor_Latnyue_Hantzho_Hanszho_Hantzul_Latnc                       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<   	 	 	 	 	 	 	 	 	 	 	 	 	 d3deeeef                  f fdZd Zd Zed             Zedefd            Zej        deddfd            Z	 d4dee	         deee	                  dedee	         f fdZ	 d5dee	         deee	                  dee	         fdZ	 d5dee	         deee	                  dee	         fdZdedee         dee         fdZd  Zd!edee         fd"Zd# Zd$ Zd% Z d5d&ed'ee         de!e         fd(Z"	 	 	 d6d+ee         ded,eee                  dede#f
 fd-Z$d. Z%d/ Z&d7d0Z'd1eddfd2Z( xZ)S )8NllbTokenizeraN  
    Construct an NLLB 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.

    Examples:

    ```python
    >>> from transformers import NllbTokenizer

    >>> tokenizer = NllbTokenizer.from_pretrained(
    ...     "facebook/nllb-200-distilled-600M", src_lang="eng_Latn", tgt_lang="fra_Latn"
    ... )
    >>> example_english_phrase = " UN Chief Says There Is No Military Solution in Syria"
    >>> expected_translation_french = "Le chef de l'ONU affirme qu'il n'y a pas de solution militaire en Syrie."
    >>> inputs = tokenizer(example_english_phrase, text_target=expected_translation_french, return_tensors="pt")
    ```

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the end of sequence.
            The token used is the `sep_token`.

            </Tip>

        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.
        tokenizer_file (`str`, *optional*):
            The path to a tokenizer file to use instead of the vocab file.
        src_lang (`str`, *optional*):
            The language to use as source language for translation.
        tgt_lang (`str`, *optional*):
            The language to use as target language for translation.
        sp_model_kwargs (`Dict[str, str]`):
            Additional keyword arguments to pass to the model initialization.
    	input_idsattention_maskprefix_tokenssuffix_tokens<s></s><unk><pad><mask>NFsp_model_kwargsc                    |t           }t          |t                    rt          |dd          n|}t          |t                    rt          |dd          n|}t          |t                    rt          |dd          n|}t          |t                    rt          |dd          n|}t          |t                    rt          |ddd          n|}|i n|| _        || _        t          j        d	i | j        | _        | j        	                    t          |                     || _
        ||||d| _        d| _        t          | j                  | _         t                      j        d	||||||||	|
||| j        |d| |
|
nd| _        |                     | j                  | _        || _        |                     | j                   d S )
NFT)
normalizedspecial)r   lstripr   )r         r	   r   )	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokentokenizer_filesrc_langtgt_langadditional_special_tokensr   legacy_behaviourr=    )FAIRSEQ_LANGUAGE_CODES
isinstancestrr
   r   r   spmSentencePieceProcessorsp_modelLoadr   _added_tokens_decoderfairseq_offsetlensp_model_sizesuper__init__	_src_langconvert_tokens_to_idscur_lang_code_idr   set_src_lang_special_tokens)selfr   r   r   r   r   r   r   r   r   r   r   r   r   r   kwargs	__class__s                   f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/nllb/tokenization_nllb.pyr  zNllbTokenizer.__init__q   s   $ %,(>%MWXacfMgMgvJyUDIIIImv	MWXacfMgMgvJyUDIIIImv	MWXacfMgMgvJyUDIIIImv	MWXacfMgMgvJyUDIIIImv	 *c**Jzd4NNNN 	 &5%<rr/ 02JJT5IJJ3z??+++$ *3yYS\%]%]" // 	
!)&? 0-	
 	
 	
 	
 	
" &.%9z $ : :4> J J ((88888    c                 z    | j                                         }d |d<   | j                                        |d<   |S )Nr   sp_model_proto)__dict__copyr   serialized_model_proto)r	  states     r  __getstate__zNllbTokenizer.__getstate__   s=    ""$$ j"&-"F"F"H"Hr  c                     || _         t          | d          si | _        t          j        di | j        | _        | j                            | j                   d S )Nr   r   )r  hasattrr   r   r   r   LoadFromSerializedProtor  )r	  ds     r  __setstate__zNllbTokenizer.__setstate__   s`     t.// 	&#%D 2JJT5IJJ--d.ABBBBBr  c                 :    t          | j                  | j        z   S N)r  r   r   r	  s    r  
vocab_sizezNllbTokenizer.vocab_size   s    4=!!D$777r  returnc                     | j         S r  )r  r  s    r  r   zNllbTokenizer.src_lang   s
    ~r  new_src_langc                 H    || _         |                     | j                    d S r  )r  r  )r	  r   s     r  r   zNllbTokenizer.src_lang   s%    %((88888r  token_ids_0token_ids_1already_has_special_tokensc                 @   |r$t                                          ||d          S dgt          | j                  z  }dgt          | j                  z  }||dgt          |          z  z   |z   S |dgt          |          z  z   dgt          |          z  z   |z   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$  r   Nr   )r  get_special_tokens_maskr  r   r   )r	  r"  r#  r$  prefix_onessuffix_onesr  s         r  r&  z%NllbTokenizer.get_special_tokens_mask   s    & & 	7722'[]a 3    cC 2333cC 23331#K(8(8"89KGGqcC$4$445!s;?O?O9OPS^^^r  c                 T    || j         |z   | j        z   S | j         |z   |z   | j        z   S )aa  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. An NLLB 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.
        )r   r   )r	  r"  r#  s      r   build_inputs_with_special_tokensz.NllbTokenizer.build_inputs_with_special_tokens   s;    , %3d6HHH!K/+=@RRRr  c                     | j         g}| j        g}|t          ||z   |z             dgz  S t          ||z   |z   |z   |z   |z             dgz  S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. nllb 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_idr  )r	  r"  r#  sepclss        r  $create_token_type_ids_from_sequencesz2NllbTokenizer.create_token_type_ids_from_sequences  sm    $  ! !s[(3.//1#553$s*S0;>DEEKKr  return_tensorsr   r   c                     ||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)add_special_tokensr1  forced_bos_token_id)
ValueErrorr   r  )r	  
raw_inputsr1  r   r   extra_kwargsinputstgt_lang_ids           r  _build_translation_inputsz'NllbTokenizer._build_translation_inputs'  sg     x/`aaa jiT.ii\hii00::(3$%r  c                 |      fdt           j                  D             }|                     j                   |S )Nc                 <    i | ]}                     |          |S r   )convert_ids_to_tokens).0ir	  s     r  
<dictcomp>z+NllbTokenizer.get_vocab.<locals>.<dictcomp>4  s)    RRRa++A..RRRr  )ranger  updateadded_tokens_encoder)r	  vocabs   ` r  	get_vocabzNllbTokenizer.get_vocab3  s@    RRRR5;Q;QRRRT.///r  textc                 D    | j                             |t                    S )N)out_type)r   encoder   )r	  rF  s     r  	_tokenizezNllbTokenizer._tokenize8  s    }##D3#777r  c                 \    | j                             |          }|r
|| j        z   n| j        S )z0Converts a token (str) in an id using the vocab.)r   	PieceToIdr   unk_token_id)r	  tokenspm_ids      r  _convert_token_to_idz"NllbTokenizer._convert_token_to_id;  s2    ((///5Lv+++4;LLr  c                 F    | j                             || j        z
            S )z=Converts an index (integer) in a token (str) using the vocab.)r   	IdToPiecer   )r	  indexs     r  _convert_id_to_tokenz"NllbTokenizer._convert_id_to_tokenA  s     }&&ut/B'BCCCr  c                     d                     |                              t          d                                          }|S )zIConverts a sequence of tokens (strings for sub-words) in a single string.  )joinreplaceSPIECE_UNDERLINEstrip)r	  tokens
out_strings      r  convert_tokens_to_stringz&NllbTokenizer.convert_tokens_to_stringE  s4    WWV__,,-=sCCIIKK
r  save_directoryfilename_prefixc                    t           j                            |          s t                              d| d           d S t           j                            ||r|dz   ndt          d         z             }t           j                            | j                  t           j                            |          k    r:t           j        	                    | j                  rt          | j        |           nzt           j        	                    | j                  sVt          |d          5 }| j                                        }|                    |           d d d            n# 1 swxY w Y   |fS )NzVocabulary path (z) should be a directory-rV  r   wb)ospathisdirloggererrorrX  VOCAB_FILES_NAMESabspathr   isfiler   openr   r  write)r	  r_  r`  out_vocab_fileficontent_spiece_models         r  save_vocabularyzNllbTokenizer.save_vocabularyJ  sw   w}}^,, 	LLT^TTTUUUFoM_s222QbcoQpp
 
 7??4?++rw~/N/NNNSUSZSaSabfbqSrSrNT_n555500 	/nd++ /r'+}'K'K'M'M$-.../ / / / / / / / / / / / / / /   s   (/E##E'*E'r=   rG   	src_texts	tgt_textsc                 V    || _         || _         t                      j        ||fi |S r  )r   r   r  prepare_seq2seq_batch)r	  rr  r   rs  r   r
  r  s         r  ru  z#NllbTokenizer.prepare_seq2seq_batch[  s4     ! ,uww,Y	LLVLLLr  c                 6    |                      | j                  S r  )r  r   r  s    r  _switch_to_input_modez#NllbTokenizer._switch_to_input_modeg      //>>>r  c                 6    |                      | j                  S r  )set_tgt_lang_special_tokensr   r  s    r  _switch_to_target_modez$NllbTokenizer._switch_to_target_modej  rx  r  c                     |                      |          | _        | j        rg | _        | j        | j        g| _        dS | j        g| _        | j        g| _        dS )zReset the special tokens to the source lang setting.
        - In legacy mode: No prefix and suffix=[eos, src_lang_code].
        - In default mode: Prefix=[src_lang_code], suffix = [eos]
        Nr  cur_lang_coder   r   eos_token_idr   )r	  r   s     r  r  z)NllbTokenizer.set_src_lang_special_tokensm  sh    
 "77AA  	5!#D"&"3T5G!HD"&"4!5D"&"3!4Dr  langc                     |                      |          | _        | j        rg | _        | j        | j        g| _        dS | j        g| _        | j        g| _        dS )zReset the special tokens to the target lang setting.
        - In legacy mode: No prefix and suffix=[eos, tgt_lang_code].
        - In default mode: Prefix=[tgt_lang_code], suffix = [eos]
        Nr}  )r	  r  s     r  rz  z)NllbTokenizer.set_tgt_lang_special_tokensz  sh    
 "77==  	5!#D"&"3T5G!HD"&"4!5D"&"3!4Dr  )r   r   r   r   r   r   r   NNNNNF)NFr  )r=   NrG   )r  N)*__name__
__module____qualname____doc__ri  vocab_files_namesmodel_input_namesr   r   int__annotations__r   r   r   r   r   r  r  r  propertyr  r   setterboolr&  r*  r0  r:  rE  rJ  rP  rT  r^  r   rq  r   ru  rw  r{  r  rz  __classcell__)r  s   @r  r   r   $   s        D DL *$&67!M49!!!!M49!!!
 48"&E9 E9 "$sCx.1E9 E9 E9 E9 E9 E9N  C C C 8 8 X8 #    X _9S 9T 9 9 9 _9
 sx_ _9_3;DI3F_ko_	c_ _ _ _ _ _> JNS S9S3;DI3FS	cS S S S8 JNL L9L3;DI3FL	cL L L L2
*-
9A#
RZ[^R_
 
 
 
  
8c 8d3i 8 8 8 8M M MD D D  
! !c !HSM !]bcf]g ! ! ! !( #)-"
M 
M9
M 
M DI&	
M
 
M 

M 
M 
M 
M 
M 
M? ? ?? ? ?5 5 5 55 5 5 5 5 5 5 5 5 5r  r   )rd  shutilr   typingr   r   r   r   r   sentencepiecer   tokenization_utilsr
   r   r   utilsr   
get_loggerr  rg  rZ  ri  r   r   r   r  r  <module>r     s    
			       3 3 3 3 3 3 3 3 3 3 3 3 3 3     P P P P P P P P P P       
	H	%	% !#<=  R&  R&  R& a5 a5 a5 a5 a5' a5 a5 a5 a5 a5r  