


import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
 from .tokenization_nllb import NllbTokenizer
else:
 SCREAMING_SNAKE_CASE__					:     Tuple       =     None


SCREAMING_SNAKE_CASE__					:     Tuple       =     logging.get_logger(__name__)


SCREAMING_SNAKE_CASE__					:     List[str]       =     {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}

SCREAMING_SNAKE_CASE__					:     int       =     {
    'vocab_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model'
        ),
    },
    'tokenizer_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json'
        ),
    },
}

SCREAMING_SNAKE_CASE__					:     Optional[Any]       =     {
    'facebook/nllb-large-en-ro': 1_024,
    'facebook/nllb-200-distilled-600M': 1_024,
}

# fmt: off
SCREAMING_SNAKE_CASE__					:     int       =     ['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_Latn']


class 		_SCREAMING_SNAKE_CASE     (						A     ):
     __SCREAMING_SNAKE_CASE     					=    VOCAB_FILES_NAMES
     __SCREAMING_SNAKE_CASE     					=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __SCREAMING_SNAKE_CASE     					=    PRETRAINED_VOCAB_FILES_MAP
     __SCREAMING_SNAKE_CASE     					=    ['''input_ids''', '''attention_mask''']
     __SCREAMING_SNAKE_CASE     					=    NllbTokenizer

     __SCREAMING_SNAKE_CASE     					=    []
     __SCREAMING_SNAKE_CASE     					=    []


     def __init__(  self							,					A_=None							,					A_=None							,					A_="<s>"							,					A_="</s>"							,					A_="</s>"							,					A_="<s>"							,					A_="<unk>"							,					A_="<pad>"							,					A_="<mask>"							,					A_=None							,					A_=None							,					A_=None							,					A_=False							,					**A_							,					):
       # Mask token behave like a normal word, i.e. include the space before it
       _UpperCAmelCase		:							Optional[int]							=     AddedToken(A_							,					lstrip=A_							,					rstrip=A_    ) if isinstance(A_							,					A_    ) else mask_token
       _UpperCAmelCase		:							Tuple							=     legacy_behaviour
       super().__init__(
           vocab_file=A_							,					tokenizer_file=A_							,					bos_token=A_							,					eos_token=A_							,					sep_token=A_							,					cls_token=A_							,					unk_token=A_							,					pad_token=A_							,					mask_token=A_							,					src_lang=A_							,					tgt_lang=A_							,					additional_special_tokens=A_							,					legacy_behaviour=A_							,					**A_							,					)

       _UpperCAmelCase		:							List[str]							=     vocab_file
       _UpperCAmelCase		:							Optional[Any]							=     False if not self.vocab_file else True

       _UpperCAmelCase		:							List[str]							=     FAIRSEQ_LANGUAGE_CODES.copy()

       if additional_special_tokens is not None:
         # Only add those special tokens if they are not already there.
         _additional_special_tokens.extend(
             [t for t in additional_special_tokens if t not in _additional_special_tokens]    )

       self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens}    )
       _UpperCAmelCase		:							Optional[Any]							=     {
           lang_code: self.convert_tokens_to_ids(A_    ) for lang_code in FAIRSEQ_LANGUAGE_CODES
       }

       _UpperCAmelCase		:							Optional[int]							=     src_lang if src_lang is not None else """eng_Latn"""
       _UpperCAmelCase		:							Any							=     self.convert_tokens_to_ids(self._src_lang    )
       _UpperCAmelCase		:							List[str]							=     tgt_lang
       self.set_src_lang_special_tokens(self._src_lang    )


     @property
     def        __snake_case(  self    ):
       return self._src_lang


     @src_lang.setter
     def        __snake_case(  self							,					A_    ):
       _UpperCAmelCase		:							Dict							=     new_src_lang
       self.set_src_lang_special_tokens(self._src_lang    )


     def        __snake_case(  self							,					A_							,					A_ = None    ):
       if token_ids_a is None:
         return self.prefix_tokens + token_ids_a + self.suffix_tokens
       # We don't expect to process pairs, but leave the pair logic for API consistency
       return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens


     def        __snake_case(  self							,					A_							,					A_ = None    ):
       _UpperCAmelCase		:							Optional[Any]							=     [self.sep_token_id]
       _UpperCAmelCase		:							Dict							=     [self.cls_token_id]

       if token_ids_a is None:
         return len(cls + token_ids_a + sep    ) * [0]
       return len(cls + token_ids_a + sep + sep + token_ids_a + sep    ) * [0]


     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_							,					**A_    ):
       if src_lang is None or tgt_lang is None:
         raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""    )
       _UpperCAmelCase		:							Tuple							=     src_lang
       _UpperCAmelCase		:							int							=     self(A_							,					add_special_tokens=A_							,					return_tensors=A_							,					**A_    )
       _UpperCAmelCase		:							int							=     self.convert_tokens_to_ids(A_    )
       _UpperCAmelCase		:							Tuple							=     tgt_lang_id
       return inputs


     def        __snake_case(  self							,					A_							,					A_ = "eng_Latn"							,					A_ = None							,					A_ = "fra_Latn"							,					**A_							,					):
       _UpperCAmelCase		:							int							=     src_lang
       _UpperCAmelCase		:							str							=     tgt_lang
       return super().prepare_seqaseq_batch(A_							,					A_							,					**A_    )


     def        __snake_case(  self    ):
       return self.set_src_lang_special_tokens(self.src_lang    )


     def        __snake_case(  self    ):
       return self.set_tgt_lang_special_tokens(self.tgt_lang    )


     def        __snake_case(  self							,					A_    ):
       _UpperCAmelCase		:							Optional[Any]							=     self.convert_tokens_to_ids(A_    )

       if self.legacy_behaviour:
         _UpperCAmelCase		:							Any							=     []
         _UpperCAmelCase		:							Tuple							=     [self.eos_token_id, self.cur_lang_code]
       else:
         _UpperCAmelCase		:							List[str]							=     [self.cur_lang_code]
         _UpperCAmelCase		:							str							=     [self.eos_token_id]

       _UpperCAmelCase		:							List[str]							=     self.convert_ids_to_tokens(self.prefix_tokens    )
       _UpperCAmelCase		:							str							=     self.convert_ids_to_tokens(self.suffix_tokens    )

       _UpperCAmelCase		:							Tuple							=     processors.TemplateProcessing(
           single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str							,					pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str							,					special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str							,					self.prefix_tokens + self.suffix_tokens    )    )							,					)


     def        __snake_case(  self							,					A_    ):
       _UpperCAmelCase		:							List[Any]							=     self.convert_tokens_to_ids(A_    )
       if self.legacy_behaviour:
         _UpperCAmelCase		:							str							=     []
         _UpperCAmelCase		:							Optional[int]							=     [self.eos_token_id, self.cur_lang_code]
       else:
         _UpperCAmelCase		:							int							=     [self.cur_lang_code]
         _UpperCAmelCase		:							str							=     [self.eos_token_id]

       _UpperCAmelCase		:							Optional[int]							=     self.convert_ids_to_tokens(self.prefix_tokens    )
       _UpperCAmelCase		:							List[str]							=     self.convert_ids_to_tokens(self.suffix_tokens    )

       _UpperCAmelCase		:							List[str]							=     processors.TemplateProcessing(
           single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str							,					pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str							,					special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str							,					self.prefix_tokens + self.suffix_tokens    )    )							,					)




     def        __snake_case(  self							,					A_							,					A_ = None    ):
       if not self.can_save_slow_tokenizer:
         raise ValueError(
             """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
             """tokenizer."""    )

       if not os.path.isdir(A_    ):
         logger.error(F'''Vocabulary path ({save_directory}) should be a directory.'''    )
         return
       _UpperCAmelCase		:							List[Any]							=     os.path.join(
           A_							,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]    )

       if os.path.abspath(self.vocab_file    ) != os.path.abspath(A_    ):
         copyfile(self.vocab_file							,					A_    )

       return (out_vocab_file,)









from __future__ import annotations

import unittest

from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available
from transformers.testing_utils import require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel


@require_tf
class 		_SCREAMING_SNAKE_CASE     :
     __SCREAMING_SNAKE_CASE     					=    BlenderbotConfig
     __SCREAMING_SNAKE_CASE     					=    {}
     __SCREAMING_SNAKE_CASE     					=    '''gelu'''


     def __init__(  self							,					A_							,					A_=13							,					A_=7							,					A_=True							,					A_=False							,					A_=99							,					A_=32							,					A_=2							,					A_=4							,					A_=37							,					A_=0.1							,					A_=0.1							,					A_=20							,					A_=2							,					A_=1							,					A_=0							,					):
       _UpperCAmelCase		:							List[str]							=     parent
       _UpperCAmelCase		:							Union[str, Any]							=     batch_size
       _UpperCAmelCase		:							Optional[Any]							=     seq_length
       _UpperCAmelCase		:							List[Any]							=     is_training
       _UpperCAmelCase		:							Union[str, Any]							=     use_labels
       _UpperCAmelCase		:							Tuple							=     vocab_size
       _UpperCAmelCase		:							Optional[int]							=     hidden_size
       _UpperCAmelCase		:							int							=     num_hidden_layers
       _UpperCAmelCase		:							List[Any]							=     num_attention_heads
       _UpperCAmelCase		:							List[Any]							=     intermediate_size

       _UpperCAmelCase		:							Union[str, Any]							=     hidden_dropout_prob
       _UpperCAmelCase		:							str							=     attention_probs_dropout_prob
       _UpperCAmelCase		:							Optional[int]							=     max_position_embeddings
       _UpperCAmelCase		:							Optional[Any]							=     eos_token_id
       _UpperCAmelCase		:							Optional[Any]							=     pad_token_id
       _UpperCAmelCase		:							Tuple							=     bos_token_id


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Optional[Any]							=     ids_tensor([self.batch_size, self.seq_length - 1]							,					self.vocab_size    )
       _UpperCAmelCase		:							Tuple							=     tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size    )							,					1    )
       _UpperCAmelCase		:							List[Any]							=     tf.concat([input_ids, eos_tensor]							,					axis=1    )

       _UpperCAmelCase		:							int							=     ids_tensor([self.batch_size, self.seq_length]							,					self.vocab_size    )

       _UpperCAmelCase		:							List[Any]							=     self.config_cls(
           vocab_size=self.vocab_size							,					d_model=self.hidden_size							,					encoder_layers=self.num_hidden_layers							,					decoder_layers=self.num_hidden_layers							,					encoder_attention_heads=self.num_attention_heads							,					decoder_attention_heads=self.num_attention_heads							,					encoder_ffn_dim=self.intermediate_size							,					decoder_ffn_dim=self.intermediate_size							,					dropout=self.hidden_dropout_prob							,					attention_dropout=self.attention_probs_dropout_prob							,					max_position_embeddings=self.max_position_embeddings							,					eos_token_ids=[2]							,					bos_token_id=self.bos_token_id							,					pad_token_id=self.pad_token_id							,					decoder_start_token_id=self.pad_token_id							,					**self.config_updates							,					)
       _UpperCAmelCase		:							Dict							=     prepare_blenderbot_inputs_dict(A_							,					A_							,					A_    )
       return config, inputs_dict




     def        __snake_case(  self							,					A_							,					A_    ):
       _UpperCAmelCase		:							Union[str, Any]							=     TFBlenderbotModel(config=A_    ).get_decoder()
       _UpperCAmelCase		:							List[Any]							=     inputs_dict["""input_ids"""]

       _UpperCAmelCase		:							Any							=     input_ids[:1, :]
       _UpperCAmelCase		:							List[str]							=     inputs_dict["""attention_mask"""][:1, :]
       _UpperCAmelCase		:							Tuple							=     inputs_dict["""head_mask"""]
       _UpperCAmelCase		:							Union[str, Any]							=     1

       # first forward pass
       _UpperCAmelCase		:							List[str]							=     model(A_							,					attention_mask=A_							,					head_mask=A_							,					use_cache=A_    )

       _UpperCAmelCase,_UpperCAmelCase		:							List[str]							=     outputs.to_tuple()

       # create hypothetical next token and extent to next_input_ids
       _UpperCAmelCase		:							List[Any]							=     ids_tensor((self.batch_size, 3)							,					config.vocab_size    )
       _UpperCAmelCase		:							List[str]							=     tf.cast(ids_tensor((self.batch_size, 3)							,					2    )							,					tf.inta    )

       # append to next input_ids and
       _UpperCAmelCase		:							Dict							=     tf.concat([input_ids, next_tokens]							,					axis=-1    )
       _UpperCAmelCase		:							Optional[Any]							=     tf.concat([attention_mask, next_attn_mask]							,					axis=-1    )

       _UpperCAmelCase		:							Tuple							=     model(A_							,					attention_mask=A_    )[0]
       _UpperCAmelCase		:							int							=     model(A_							,					attention_mask=A_							,					past_key_values=A_    )[0]

       self.parent.assertEqual(next_tokens.shape[1]							,					output_from_past.shape[1]    )

       # select random slice
       _UpperCAmelCase		:							Tuple							=     int(ids_tensor((1,)							,					output_from_past.shape[-1]    )    )
       _UpperCAmelCase		:							str							=     output_from_no_past[:, -3:, random_slice_idx]
       _UpperCAmelCase		:							str							=     output_from_past[:, :, random_slice_idx]

       # test that outputs are equal for slice
       tf.debugging.assert_near(A_							,					A_							,					rtol=1e-3    )




def    a__    (		snake_case__					:							Optional[Any]						,   snake_case__					:							str						,   snake_case__					:							Dict						,   snake_case__					:							str=None						,   snake_case__					:							Optional[int]=None						,   snake_case__					:							str=None						,   snake_case__					:							List[str]=None						,   snake_case__					:							List[str]=None						,   ):
  if attention_mask is None:
    _UpperCAmelCase		:							List[Any]							=     tf.cast(tf.math.not_equal(snake_case__						,   config.pad_token_id     )						,   tf.inta     )
  if decoder_attention_mask is None:
    _UpperCAmelCase		:							str							=     tf.concat(
        [
            tf.ones(decoder_input_ids[:, :1].shape						,   dtype=tf.inta     ),
            tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]						,   config.pad_token_id     )						,   tf.inta     ),
        ]						,   axis=-1						,   )
  if head_mask is None:
    _UpperCAmelCase		:							List[str]							=     tf.ones((config.encoder_layers, config.encoder_attention_heads)     )
  if decoder_head_mask is None:
    _UpperCAmelCase		:							Tuple							=     tf.ones((config.decoder_layers, config.decoder_attention_heads)     )
  if cross_attn_head_mask is None:
    _UpperCAmelCase		:							Dict							=     tf.ones((config.decoder_layers, config.decoder_attention_heads)     )
  return {
      "input_ids": input_ids,
      "decoder_input_ids": decoder_input_ids,
      "attention_mask": attention_mask,
      "decoder_attention_mask": decoder_attention_mask,
      "head_mask": head_mask,
      "decoder_head_mask": decoder_head_mask,
      "cross_attn_head_mask": cross_attn_head_mask,
  }


@require_tf
class 		_SCREAMING_SNAKE_CASE     (						A							,	A							,	unittest.TestCase     ):
     __SCREAMING_SNAKE_CASE     					=    (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else ()
     __SCREAMING_SNAKE_CASE     					=    (TFBlenderbotForConditionalGeneration,) if is_tf_available() else ()
     __SCREAMING_SNAKE_CASE     					=    (
         {
             '''conversational''': TFBlenderbotForConditionalGeneration,
             '''feature-extraction''': TFBlenderbotModel,
             '''summarization''': TFBlenderbotForConditionalGeneration,
             '''text2text-generation''': TFBlenderbotForConditionalGeneration,
             '''translation''': TFBlenderbotForConditionalGeneration,
         }
         if is_tf_available()
         else {}
     )
     __SCREAMING_SNAKE_CASE     					=    True
     __SCREAMING_SNAKE_CASE     					=    False
     __SCREAMING_SNAKE_CASE     					=    False


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Union[str, Any]							=     TFBlenderbotModelTester(self    )
       _UpperCAmelCase		:							Any							=     ConfigTester(self							,					config_class=A_    )


     def        __snake_case(  self    ):
       self.config_tester.run_common_tests()




     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Tuple							=     self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.check_decoder_model_past_large_inputs(*A_    )


@require_tokenizers
@require_tf
class 		_SCREAMING_SNAKE_CASE     (						unittest.TestCase     ):
     __SCREAMING_SNAKE_CASE     					=    ['''My friends are cool but they eat too many carbs.''']
     __SCREAMING_SNAKE_CASE     					=    '''facebook/blenderbot-400M-distill'''


     @cached_property
     def        __snake_case(  self    ):
       return BlenderbotTokenizer.from_pretrained(self.model_name    )


     @cached_property
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[Any]							=     TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name    )
       return model




     @slow
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Any							=     self.tokenizer(self.src_text							,					return_tensors="""tf"""    )
       _UpperCAmelCase		:							List[Any]							=     self.model.generate(
           model_inputs.input_ids							,					)
       _UpperCAmelCase		:							List[str]							=     self.tokenizer.batch_decode(generated_ids.numpy()							,					skip_special_tokens=A_    )[0]
       assert (
           generated_words
           == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?"
       )





