'''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 			__lowercase		:







     """simple docstring"""






     def __init__(		self     ,			_lowerCamelCase     ,			_lowerCamelCase=1_3     ,			_lowerCamelCase=3_0     ,			_lowerCamelCase=2     ,			_lowerCamelCase=3     ,			_lowerCamelCase=True     ,			_lowerCamelCase=True     ,			_lowerCamelCase=3_2     ,			_lowerCamelCase=2     ,			_lowerCamelCase=4     ,			_lowerCamelCase=3_7     ,			_lowerCamelCase="gelu"     ,			_lowerCamelCase=0.1     ,			_lowerCamelCase=0.1     ,			_lowerCamelCase=1_0     ,			_lowerCamelCase=0.0_2     ,			_lowerCamelCase=3     ,			_lowerCamelCase=None     ,			):
         __UpperCamelCase	:	Dict		    =  parent
         __UpperCamelCase	:	int		    =  batch_size
         __UpperCamelCase	:	Optional[int]		    =  image_size
         __UpperCamelCase	:	List[str]		    =  patch_size
         __UpperCamelCase	:	Union[str, Any]		    =  num_channels
         __UpperCamelCase	:	Optional[int]		    =  is_training
         __UpperCamelCase	:	int		    =  use_labels
         __UpperCamelCase	:	List[str]		    =  hidden_size
         __UpperCamelCase	:	Tuple		    =  num_hidden_layers
         __UpperCamelCase	:	Optional[Any]		    =  num_attention_heads
         __UpperCamelCase	:	str		    =  intermediate_size
         __UpperCamelCase	:	List[Any]		    =  hidden_act
         __UpperCamelCase	:	Union[str, Any]		    =  hidden_dropout_prob
         __UpperCamelCase	:	Any		    =  attention_probs_dropout_prob
         __UpperCamelCase	:	int		    =  type_sequence_label_size
         __UpperCamelCase	:	Optional[int]		    =  initializer_range
         __UpperCamelCase	:	Union[str, Any]		    =  scope

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







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

         __UpperCamelCase	:	Union[str, Any]		    =  None
         if self.use_labels:
             __UpperCamelCase	:	List[str]		    =  ids_tensor([self.batch_size]     ,			self.type_sequence_label_size    )

         __UpperCamelCase	:	Tuple		    =  self.get_config()

         return config, pixel_values, labels







     def lowerCAmelCase     (		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=UpperCAmelCase__     ,			initializer_range=self.initializer_range     ,			)







     def lowerCAmelCase     (		self     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	Optional[int]		    =  TFViTModel(config=UpperCAmelCase__    )
         __UpperCamelCase	:	Any		    =  model(UpperCAmelCase__     ,			training=UpperCAmelCase__    )
         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.
         __UpperCamelCase	:	List[str]		    =  self.image_size // 2
         __UpperCamelCase	:	Any		    =  pixel_values[:, :, :image_size, :image_size]
         __UpperCamelCase	:	Dict		    =  model(UpperCAmelCase__     ,			interpolate_pos_encoding=UpperCAmelCase__     ,			training=UpperCAmelCase__    )
         __UpperCamelCase	:	List[str]		    =  (image_size // self.patch_size) ** 2 + 1
         self.parent.assertEqual(result.last_hidden_state.shape     ,			(self.batch_size, seq_length, self.hidden_size)    )







     def lowerCAmelCase     (		self     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	Optional[int]		    =  self.type_sequence_label_size
         __UpperCamelCase	:	Dict		    =  TFViTForImageClassification(UpperCAmelCase__    )
         __UpperCamelCase	:	Optional[int]		    =  model(UpperCAmelCase__     ,			labels=UpperCAmelCase__     ,			training=UpperCAmelCase__    )
         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.
         __UpperCamelCase	:	List[str]		    =  self.image_size // 2
         __UpperCamelCase	:	Dict		    =  pixel_values[:, :, :image_size, :image_size]
         __UpperCamelCase	:	List[Any]		    =  model(UpperCAmelCase__     ,			interpolate_pos_encoding=UpperCAmelCase__     ,			training=UpperCAmelCase__    )
         self.parent.assertEqual(result.logits.shape     ,			(self.batch_size, self.type_sequence_label_size)    )

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







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[Any]		    =  self.prepare_config_and_inputs()
         __UpperCamelCase    ,					__UpperCamelCase    ,					__UpperCamelCase	:	Dict		    =  config_and_inputs
         __UpperCamelCase	:	Any		    =  {'pixel_values': pixel_values}
         return config, inputs_dict






@require_tf
class 			__lowercase		(						_lowerCamelCase			,							_lowerCamelCase			,							unittest.TestCase						):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		   =						(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
     SCREAMING_SNAKE_CASE__		   =						(
         {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification}
         if is_tf_available()
         else {}
     )

     SCREAMING_SNAKE_CASE__		   =						False
     SCREAMING_SNAKE_CASE__		   =						False
     SCREAMING_SNAKE_CASE__		   =						False







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Dict		    =  TFViTModelTester(self    )
         __UpperCamelCase	:	Optional[Any]		    =  ConfigTester(self     ,			config_class=UpperCAmelCase__     ,			has_text_modality=UpperCAmelCase__     ,			hidden_size=3_7    )







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







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







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







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase    ,					__UpperCamelCase	:	List[Any]		    =  self.model_tester.prepare_config_and_inputs_for_common()

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







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase    ,					__UpperCamelCase	:	int		    =  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             __UpperCamelCase	:	Optional[int]		    =  model_class(UpperCAmelCase__    )
             __UpperCamelCase	:	Union[str, Any]		    =  inspect.signature(model.call    )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             __UpperCamelCase	:	Dict		    =  [*signature.parameters.keys()]

             __UpperCamelCase	:	str		    =  ['pixel_values']
             self.assertListEqual(arg_names[:1]     ,			UpperCAmelCase__    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*UpperCAmelCase__    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Tuple		    =  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__    )







     @slow
     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  TFViTModel.from_pretrained('google/vit-base-patch16-224'    )
         self.assertIsNotNone(UpperCAmelCase__    )







def  _UpperCamelCase (     ):




    """simple docstring"""



    __UpperCamelCase	:	Union[str, Any]		    =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
    return image






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







     """simple docstring"""






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







     @slow
     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	List[str]		    =  TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224'    )

         __UpperCamelCase	:	List[Any]		    =  self.default_image_processor
         __UpperCamelCase	:	List[Any]		    =  prepare_img()
         __UpperCamelCase	:	List[str]		    =  image_processor(images=UpperCAmelCase__     ,			return_tensors='tf'    )

         # forward pass
         __UpperCamelCase	:	Optional[int]		    =  model(**UpperCAmelCase__    )

         # verify the logits
         __UpperCamelCase	:	Any		    =  tf.TensorShape((1, 1_0_0_0)    )
         self.assertEqual(outputs.logits.shape     ,			UpperCAmelCase__    )

         __UpperCamelCase	:	List[str]		    =  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]     ,			UpperCAmelCase__     ,			atol=1E-4    )




'''simple docstring'''
import json
import os
import unittest

from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast
from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 			__lowercase		(						_lowerCamelCase			,							unittest.TestCase						):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		   =						OpenAIGPTTokenizer
     SCREAMING_SNAKE_CASE__		   =						OpenAIGPTTokenizerFast
     SCREAMING_SNAKE_CASE__		   =						True
     SCREAMING_SNAKE_CASE__		   =						False







     def lowerCAmelCase     (		self    ):
         super().setUp()

         # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
         __UpperCamelCase	:	List[Any]		    =  [
             'l',
             'o',
             'w',
             'e',
             'r',
             's',
             't',
             'i',
             'd',
             'n',
             'w</w>',
             'r</w>',
             't</w>',
             'lo',
             'low',
             'er</w>',
             'low</w>',
             'lowest</w>',
             'newer</w>',
             'wider</w>',
             '<unk>',
         ]
         __UpperCamelCase	:	List[str]		    =  dict(zip(_lowerCamelCase     ,			range(len(_lowerCamelCase    )    )    )    )
         __UpperCamelCase	:	Union[str, Any]		    =  ['#version: 0.2', 'l o', 'lo w', 'e r</w>', '']

         __UpperCamelCase	:	Optional[int]		    =  os.path.join(self.tmpdirname     ,			VOCAB_FILES_NAMES['vocab_file']    )
         __UpperCamelCase	:	Tuple		    =  os.path.join(self.tmpdirname     ,			VOCAB_FILES_NAMES['merges_file']    )
         with open(self.vocab_file     ,			'w'    ) as fp:
             fp.write(json.dumps(_lowerCamelCase    )    )
         with open(self.merges_file     ,			'w'    ) as fp:
             fp.write('\n'.join(_lowerCamelCase    )    )







     def lowerCAmelCase     (		self     ,			_lowerCamelCase    ):
         return "lower newer", "lower newer"







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Dict		    =  OpenAIGPTTokenizer(self.vocab_file     ,			self.merges_file    )

         __UpperCamelCase	:	List[Any]		    =  'lower'
         __UpperCamelCase	:	Union[str, Any]		    =  ['low', 'er</w>']
         __UpperCamelCase	:	Tuple		    =  tokenizer.tokenize(_lowerCamelCase    )
         self.assertListEqual(_lowerCamelCase     ,			_lowerCamelCase    )

         __UpperCamelCase	:	List[str]		    =  tokens + ['<unk>']
         __UpperCamelCase	:	Optional[Any]		    =  [1_4, 1_5, 2_0]
         self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase    )     ,			_lowerCamelCase    )







     def lowerCAmelCase     (		self     ,			_lowerCamelCase=1_5    ):
         for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
             with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""    ):
                 __UpperCamelCase	:	Dict		    =  self.rust_tokenizer_class.from_pretrained(_lowerCamelCase     ,			**_lowerCamelCase    )

                 # Simple input
                 __UpperCamelCase	:	int		    =  'This is a simple input'
                 __UpperCamelCase	:	Any		    =  ['This is a simple input 1', 'This is a simple input 2']
                 __UpperCamelCase	:	Union[str, Any]		    =  ('This is a simple input', 'This is a pair')
                 __UpperCamelCase	:	Any		    =  [
                     ('This is a simple input 1', 'This is a simple input 2'),
                     ('This is a simple pair 1', 'This is a simple pair 2'),
                 ]

                 # Simple input tests
                 self.assertRaises(_lowerCamelCase     ,			tokenizer_r.encode     ,			_lowerCamelCase     ,			max_length=_lowerCamelCase     ,			padding='max_length'    )

                 # Simple input
                 self.assertRaises(_lowerCamelCase     ,			tokenizer_r.encode_plus     ,			_lowerCamelCase     ,			max_length=_lowerCamelCase     ,			padding='max_length'    )

                 # Simple input
                 self.assertRaises(
                     _lowerCamelCase     ,			tokenizer_r.batch_encode_plus     ,			_lowerCamelCase     ,			max_length=_lowerCamelCase     ,			padding='max_length'     ,			)

                 # Pair input
                 self.assertRaises(_lowerCamelCase     ,			tokenizer_r.encode     ,			_lowerCamelCase     ,			max_length=_lowerCamelCase     ,			padding='max_length'    )

                 # Pair input
                 self.assertRaises(_lowerCamelCase     ,			tokenizer_r.encode_plus     ,			_lowerCamelCase     ,			max_length=_lowerCamelCase     ,			padding='max_length'    )

                 # Pair input
                 self.assertRaises(
                     _lowerCamelCase     ,			tokenizer_r.batch_encode_plus     ,			_lowerCamelCase     ,			max_length=_lowerCamelCase     ,			padding='max_length'     ,			)







     def lowerCAmelCase     (		self    ):
         pass






@require_ftfy
@require_spacy
@require_tokenizers
class 			__lowercase		(						_lowerCamelCase						):







     """simple docstring"""






     pass



