"""simple docstring"""




from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
     import tensorflow as tf

     from transformers import TFViTForImageClassification, TFViTModel


if is_vision_available():
     from PIL import Image

     from transformers import ViTImageProcessor
class 						__A							:






     def __init__(		self    ,					a__    ,					a__=13    ,					a__=30    ,					a__=2    ,					a__=3    ,					a__=True    ,					a__=True    ,					a__=32    ,					a__=2    ,					a__=4    ,					a__=37    ,					a__="gelu"    ,					a__=0.1    ,					a__=0.1    ,					a__=10    ,					a__=0.0_2    ,					a__=3    ,					a__=None    ,					):
       _lowerCAmelCase						:	Optional[int]        =					parent
       _lowerCAmelCase						:	Optional[int]        =					batch_size
       _lowerCAmelCase						:	Any        =					image_size
       _lowerCAmelCase						:	str        =					patch_size
       _lowerCAmelCase						:	Tuple        =					num_channels
       _lowerCAmelCase						:	Any        =					is_training
       _lowerCAmelCase						:	List[Any]        =					use_labels
       _lowerCAmelCase						:	List[Any]        =					hidden_size
       _lowerCAmelCase						:	Any        =					num_hidden_layers
       _lowerCAmelCase						:	Union[str, Any]        =					num_attention_heads
       _lowerCAmelCase						:	Optional[Any]        =					intermediate_size
       _lowerCAmelCase						:	List[str]        =					hidden_act
       _lowerCAmelCase						:	Tuple        =					hidden_dropout_prob
       _lowerCAmelCase						:	List[str]        =					attention_probs_dropout_prob
       _lowerCAmelCase						:	Dict        =					type_sequence_label_size
       _lowerCAmelCase						:	str        =					initializer_range
       _lowerCAmelCase						:	Union[str, Any]        =					scope

       # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
       _lowerCAmelCase						:	Tuple        =					(image_size // patch_size) ** 2
       _lowerCAmelCase						:	int        =					num_patches + 1






     def    __A  (		self  ):
       _lowerCAmelCase						:	Dict        =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

       _lowerCAmelCase						:	Optional[Any]        =					None
       if self.use_labels:
         _lowerCAmelCase						:	int        =					ids_tensor([self.batch_size]    ,					self.type_sequence_label_size  )

       _lowerCAmelCase						:	Any        =					self.get_config()

       return config, pixel_values, labels






     def    __A  (		self  ):
       return ViTConfig(
           image_size=self.image_size    ,					patch_size=self.patch_size    ,					num_channels=self.num_channels    ,					hidden_size=self.hidden_size    ,					num_hidden_layers=self.num_hidden_layers    ,					num_attention_heads=self.num_attention_heads    ,					intermediate_size=self.intermediate_size    ,					hidden_act=self.hidden_act    ,					hidden_dropout_prob=self.hidden_dropout_prob    ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,					is_decoder=a__    ,					initializer_range=self.initializer_range    ,					)






     def    __A  (		self    ,					a__    ,					a__    ,					a__  ):
       _lowerCAmelCase						:	Optional[Any]        =					TFViTModel(config=a__  )
       _lowerCAmelCase						:	Optional[int]        =					model(a__    ,					training=a__  )
       self.parent.assertEqual(result.last_hidden_state.shape    ,					(self.batch_size, self.seq_length, self.hidden_size)  )

       # Test with an image with different size than the one specified in config.
       _lowerCAmelCase						:	Dict        =					self.image_size // 2
       _lowerCAmelCase						:	Optional[int]        =					pixel_values[:, :, :image_size, :image_size]
       _lowerCAmelCase						:	Tuple        =					model(a__    ,					interpolate_pos_encoding=a__    ,					training=a__  )
       _lowerCAmelCase						:	Union[str, Any]        =					(image_size // self.patch_size) ** 2 + 1
       self.parent.assertEqual(result.last_hidden_state.shape    ,					(self.batch_size, seq_length, self.hidden_size)  )






     def    __A  (		self    ,					a__    ,					a__    ,					a__  ):
       _lowerCAmelCase						:	List[str]        =					self.type_sequence_label_size
       _lowerCAmelCase						:	Tuple        =					TFViTForImageClassification(a__  )
       _lowerCAmelCase						:	List[Any]        =					model(a__    ,					labels=a__    ,					training=a__  )
       self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.type_sequence_label_size)  )

       # Test with an image with different size than the one specified in config.
       _lowerCAmelCase						:	List[Any]        =					self.image_size // 2
       _lowerCAmelCase						:	Dict        =					pixel_values[:, :, :image_size, :image_size]
       _lowerCAmelCase						:	Optional[Any]        =					model(a__    ,					interpolate_pos_encoding=a__    ,					training=a__  )
       self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.type_sequence_label_size)  )

       # test greyscale images
       _lowerCAmelCase						:	List[str]        =					1
       _lowerCAmelCase						:	List[str]        =					TFViTForImageClassification(a__  )
       _lowerCAmelCase						:	Optional[Any]        =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
       _lowerCAmelCase						:	List[str]        =					model(a__  )
       self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.type_sequence_label_size)  )






     def    __A  (		self  ):
       _lowerCAmelCase						:	Dict        =					self.prepare_config_and_inputs()
       _lowerCAmelCase      ,     _lowerCAmelCase      ,     _lowerCAmelCase						:	Optional[int]        =					config_and_inputs
       _lowerCAmelCase						:	List[Any]        =					{"""pixel_values""": pixel_values}
       return config, inputs_dict







@require_tf
class 						__A							(			SCREAMING_SNAKE_CASE_   ,     SCREAMING_SNAKE_CASE_   ,     unittest.TestCase		):
     _UpperCamelCase							:      Union[str, Any]		 =		(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
     _UpperCamelCase							:      Dict		 =		(
         {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification}
         if is_tf_available()
         else {}
     )

     _UpperCamelCase							:      Dict		 =		False
     _UpperCamelCase							:      Any		 =		False
     _UpperCamelCase							:      Union[str, Any]		 =		False






     def    __A  (		self  ):
       _lowerCAmelCase						:	Optional[int]        =					TFViTModelTester(self  )
       _lowerCAmelCase						:	Optional[Any]        =					ConfigTester(self    ,					config_class=a__    ,					has_text_modality=a__    ,					hidden_size=37  )






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






     @unittest.skip(reason="""ViT does not use inputs_embeds"""  )
     def    __A  (		self  ):
       pass






     @unittest.skip(reason="""ViT does not use inputs_embeds"""  )
     def    __A  (		self  ):
       pass






     def    __A  (		self  ):
       _lowerCAmelCase      ,     _lowerCAmelCase						:	List[Any]        =					self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         _lowerCAmelCase						:	Dict        =					model_class(a__  )
         self.assertIsInstance(model.get_input_embeddings()    ,					(tf.keras.layers.Layer)  )
         _lowerCAmelCase						:	List[str]        =					model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(a__    ,					tf.keras.layers.Layer  )  )






     def    __A  (		self  ):
       _lowerCAmelCase      ,     _lowerCAmelCase						:	List[str]        =					self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         _lowerCAmelCase						:	Dict        =					model_class(a__  )
         _lowerCAmelCase						:	Any        =					inspect.signature(model.call  )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         _lowerCAmelCase						:	List[Any]        =					[*signature.parameters.keys()]

         _lowerCAmelCase						:	Dict        =					["""pixel_values"""]
         self.assertListEqual(arg_names[:1]    ,					a__  )






     def    __A  (		self  ):
       _lowerCAmelCase						:	List[Any]        =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a__  )






     def    __A  (		self  ):
       _lowerCAmelCase						:	List[Any]        =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*a__  )






     @slow
     def    __A  (		self  ):
       _lowerCAmelCase						:	Any        =					TFViTModel.from_pretrained("""google/vit-base-patch16-224"""  )
       self.assertIsNotNone(a__  )







def 							SCREAMING_SNAKE_CASE					(      )	->				Optional[Any]:
  _lowerCAmelCase						:	int        =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
  return image






@require_tf
@require_vision
class 						__A							(			unittest.TestCase		):






     @cached_property
     def    __A  (		self  ):
       return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""  ) if is_vision_available() else None






     @slow
     def    __A  (		self  ):
       _lowerCAmelCase						:	List[str]        =					TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""  )

       _lowerCAmelCase						:	Optional[int]        =					self.default_image_processor
       _lowerCAmelCase						:	Optional[int]        =					prepare_img()
       _lowerCAmelCase						:	Optional[Any]        =					image_processor(images=a__    ,					return_tensors="""tf"""  )

       # forward pass
       _lowerCAmelCase						:	Tuple        =					model(**a__  )

       # verify the logits
       _lowerCAmelCase						:	Union[str, Any]        =					tf.TensorShape((1, 1000)  )
       self.assertEqual(outputs.logits.shape    ,					a__  )

       _lowerCAmelCase						:	Optional[Any]        =					tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]  )

       tf.debugging.assert_near(outputs.logits[0, :3]    ,					a__    ,					atol=1e-4  )





"""simple docstring"""




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:
     _a				:		Tuple	   =       None


_a				:		str	   =       logging.get_logger(__name__)


_a				:		str	   =       {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}

_a				:		Tuple	   =       {
    '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'
        ),
    },
}

_a				:		int	   =       {
    'facebook/nllb-large-en-ro': 1_024,
    'facebook/nllb-200-distilled-600M': 1_024,
}

# fmt: off
_a				:		Union[str, Any]	   =       ['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 						__A							(			SCREAMING_SNAKE_CASE_		):
     _UpperCamelCase							:      Union[str, Any]		 =		VOCAB_FILES_NAMES
     _UpperCamelCase							:      Union[str, Any]		 =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     _UpperCamelCase							:      Dict		 =		PRETRAINED_VOCAB_FILES_MAP
     _UpperCamelCase							:      str		 =		["input_ids", "attention_mask"]
     _UpperCamelCase							:      Tuple		 =		NllbTokenizer

     _UpperCamelCase							:      List[int]		 =		[]
     _UpperCamelCase							:      List[int]		 =		[]






     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
       _lowerCAmelCase						:	Optional[int]        =					AddedToken(a__    ,					lstrip=a__    ,					rstrip=a__  ) if isinstance(a__    ,					a__  ) else mask_token
       _lowerCAmelCase						:	int        =					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__    ,					)

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

       _lowerCAmelCase						:	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}  )
       _lowerCAmelCase						:	Tuple        =					{
           lang_code: self.convert_tokens_to_ids(a__  ) for lang_code in FAIRSEQ_LANGUAGE_CODES
       }

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






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






     @src_lang.setter
     def    __A  (		self    ,					a__  ):
       _lowerCAmelCase						:	List[Any]        =					new_src_lang
       self.set_src_lang_special_tokens(self._src_lang  )






     def    __A  (		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    __A  (		self    ,					a__    ,					a__ = None  ):
       _lowerCAmelCase						:	Tuple        =					[self.sep_token_id]
       _lowerCAmelCase						:	int        =					[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    __A  (		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"""  )
       _lowerCAmelCase						:	str        =					src_lang
       _lowerCAmelCase						:	List[Any]        =					self(a__    ,					add_special_tokens=a__    ,					return_tensors=a__    ,					**a__  )
       _lowerCAmelCase						:	Dict        =					self.convert_tokens_to_ids(a__  )
       _lowerCAmelCase						:	Dict        =					tgt_lang_id
       return inputs






     def    __A  (		self    ,					a__    ,					a__ = "eng_Latn"    ,					a__ = None    ,					a__ = "fra_Latn"    ,					**a__    ,					):
       _lowerCAmelCase						:	List[Any]        =					src_lang
       _lowerCAmelCase						:	Optional[int]        =					tgt_lang
       return super().prepare_seqaseq_batch(a__    ,					a__    ,					**a__  )






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






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






     def    __A  (		self    ,					a__  ):
       _lowerCAmelCase						:	Optional[Any]        =					self.convert_tokens_to_ids(a__  )

       if self.legacy_behaviour:
         _lowerCAmelCase						:	Optional[int]        =					[]
         _lowerCAmelCase						:	Union[str, Any]        =					[self.eos_token_id, self.cur_lang_code]
       else:
         _lowerCAmelCase						:	str        =					[self.cur_lang_code]
         _lowerCAmelCase						:	List[Any]        =					[self.eos_token_id]

       _lowerCAmelCase						:	List[Any]        =					self.convert_ids_to_tokens(self.prefix_tokens  )
       _lowerCAmelCase						:	Any        =					self.convert_ids_to_tokens(self.suffix_tokens  )

       _lowerCAmelCase						:	Optional[Any]        =					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    __A  (		self    ,					a__  ):
       _lowerCAmelCase						:	Any        =					self.convert_tokens_to_ids(a__  )
       if self.legacy_behaviour:
         _lowerCAmelCase						:	Optional[int]        =					[]
         _lowerCAmelCase						:	str        =					[self.eos_token_id, self.cur_lang_code]
       else:
         _lowerCAmelCase						:	int        =					[self.cur_lang_code]
         _lowerCAmelCase						:	Optional[int]        =					[self.eos_token_id]

       _lowerCAmelCase						:	Union[str, Any]        =					self.convert_ids_to_tokens(self.prefix_tokens  )
       _lowerCAmelCase						:	int        =					self.convert_ids_to_tokens(self.suffix_tokens  )

       _lowerCAmelCase						:	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    __A  (		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
       _lowerCAmelCase						:	Optional[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,)




