

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 _UpperCamelCase				:
			'''simple docstring'''







			def __init__(      self				:			Optional[int]   ,   a				:			Any   ,   a				:			str=13   ,   a				:			Optional[int]=30   ,   a				:			int=2   ,   a				:			str=3   ,   a				:			Optional[Any]=True   ,   a				:			List[Any]=True   ,   a				:			Any=32   ,   a				:			Any=2   ,   a				:			Optional[int]=4   ,   a				:			Dict=37   ,   a				:			List[Any]="gelu"   ,   a				:			int=0.1   ,   a				:			List[str]=0.1   ,   a				:			Dict=10   ,   a				:			Optional[int]=0.02   ,   a				:			Tuple=3   ,   a				:			Union[str, Any]=None   ,   )				->							Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   List[str]					  =							parent
				SCREAMING_SNAKE_CASE :   Tuple					  =							batch_size
				SCREAMING_SNAKE_CASE :   List[str]					  =							image_size
				SCREAMING_SNAKE_CASE :   Tuple					  =							patch_size
				SCREAMING_SNAKE_CASE :   Tuple					  =							num_channels
				SCREAMING_SNAKE_CASE :   Tuple					  =							is_training
				SCREAMING_SNAKE_CASE :   List[Any]					  =							use_labels
				SCREAMING_SNAKE_CASE :   Optional[int]					  =							hidden_size
				SCREAMING_SNAKE_CASE :   Any					  =							num_hidden_layers
				SCREAMING_SNAKE_CASE :   List[Any]					  =							num_attention_heads
				SCREAMING_SNAKE_CASE :   Any					  =							intermediate_size
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							hidden_act
				SCREAMING_SNAKE_CASE :   Tuple					  =							hidden_dropout_prob
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							attention_probs_dropout_prob
				SCREAMING_SNAKE_CASE :   Optional[int]					  =							type_sequence_label_size
				SCREAMING_SNAKE_CASE :   Dict					  =							initializer_range
				SCREAMING_SNAKE_CASE :   List[str]					  =							scope

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

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   int					  =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							self.get_config()

				return config, pixel_values, labels
			def 				__UpperCamelCase			(      self				:			List[Any]						)				->							Any:

				"""simple docstring"""

				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 				__UpperCamelCase			(      self				:			List[Any]   ,   a				:			Any   ,   a				:			Union[str, Any]   ,   a				:			Union[str, Any]						)				->							Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Any					  =							TFViTModel(config=a						)
				SCREAMING_SNAKE_CASE :   Optional[Any]					  =							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.
				SCREAMING_SNAKE_CASE :   Tuple					  =							self.image_size // 2
				SCREAMING_SNAKE_CASE :   List[Any]					  =							pixel_values[:, :, :image_size, :image_size]
				SCREAMING_SNAKE_CASE :   int					  =							model(a   ,   interpolate_pos_encoding=a   ,   training=a						)
				SCREAMING_SNAKE_CASE :   List[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 				__UpperCamelCase			(      self				:			List[str]   ,   a				:			List[str]   ,   a				:			Tuple   ,   a				:			Tuple						)				->							List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							self.type_sequence_label_size
				SCREAMING_SNAKE_CASE :   Tuple					  =							TFViTForImageClassification(a						)
				SCREAMING_SNAKE_CASE :   str					  =							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.
				SCREAMING_SNAKE_CASE :   Tuple					  =							self.image_size // 2
				SCREAMING_SNAKE_CASE :   int					  =							pixel_values[:, :, :image_size, :image_size]
				SCREAMING_SNAKE_CASE :   Tuple					  =							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
				SCREAMING_SNAKE_CASE :   Dict					  =							1
				SCREAMING_SNAKE_CASE :   List[str]					  =							TFViTForImageClassification(a						)
				SCREAMING_SNAKE_CASE :   List[Any]					  =							floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
				SCREAMING_SNAKE_CASE :   List[str]					  =							model(a						)
				self.parent.assertEqual(result.logits.shape   ,   (self.batch_size, self.type_sequence_label_size)						)






			def 				__UpperCamelCase			(      self				:			str						)				->							Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   List[str]					  =							self.prepare_config_and_inputs()
				SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE :   List[Any]					  =							config_and_inputs
				SCREAMING_SNAKE_CASE :   int					  =							{"pixel_values": pixel_values}
				return config, inputs_dict






@require_tf
class _UpperCamelCase				(				__A				,						__A				,						unittest.TestCase ):
			'''simple docstring'''







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

			lowerCamelCase__							     =False
			lowerCamelCase__							     =False
			lowerCamelCase__							     =False
			def 				__UpperCamelCase			(      self				:			List[Any]						)				->							Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   str					  =							TFViTModelTester(self						)
				SCREAMING_SNAKE_CASE :   Any					  =							ConfigTester(self   ,   config_class=a   ,   has_text_modality=a   ,   hidden_size=37						)
			def 				__UpperCamelCase			(      self				:			int						)				->							List[Any]:

				"""simple docstring"""

				self.config_tester.run_common_tests()
			@unittest.skip(reason="ViT does not use inputs_embeds"						)
			def 				__UpperCamelCase			(      self				:			List[Any]						)				->							Any:

				"""simple docstring"""

				pass
			@unittest.skip(reason="ViT does not use inputs_embeds"						)
			def 				__UpperCamelCase			(      self				:			int						)				->							Union[str, Any]:

				"""simple docstring"""

				pass
			def 				__UpperCamelCase			(      self				:			Union[str, Any]						)				->							Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE :   Optional[int]					  =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE :   List[str]					  =							model_class(a						)
					self.assertIsInstance(model.get_input_embeddings()   ,   (tf.keras.layers.Layer)						)
					SCREAMING_SNAKE_CASE :   str					  =							model.get_output_embeddings()
					self.assertTrue(x is None or isinstance(a   ,   tf.keras.layers.Layer						)						)
			def 				__UpperCamelCase			(      self				:			Optional[Any]						)				->							Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE :   Any					  =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE :   int					  =							model_class(a						)
					SCREAMING_SNAKE_CASE :   str					  =							inspect.signature(model.call						)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					SCREAMING_SNAKE_CASE :   int					  =							[*signature.parameters.keys()]

					SCREAMING_SNAKE_CASE :   Optional[int]					  =							["pixel_values"]
					self.assertListEqual(arg_names[:1]   ,   a						)
			def 				__UpperCamelCase			(      self				:			Any						)				->							Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*a						)
			def 				__UpperCamelCase			(      self				:			Optional[int]						)				->							List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*a						)






			@slow
			def 				__UpperCamelCase			(      self				:			List[Any]						)				->							List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   List[Any]					  =							TFViTModel.from_pretrained("google/vit-base-patch16-224"						)
				self.assertIsNotNone(a						)

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






@require_tf
@require_vision
class _UpperCamelCase				(				unittest.TestCase ):
			'''simple docstring'''







			@cached_property
			def 				__UpperCamelCase			(      self				:			Union[str, Any]						)				->							List[Any]:

				"""simple docstring"""

				return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"						) if is_vision_available() else None






			@slow
			def 				__UpperCamelCase			(      self				:			int						)				->							List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"						)

				SCREAMING_SNAKE_CASE :   List[str]					  =							self.default_image_processor
				SCREAMING_SNAKE_CASE :   Optional[int]					  =							prepare_img()
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							image_processor(images=a   ,   return_tensors="tf"						)

				# forward pass
				SCREAMING_SNAKE_CASE :   Dict					  =							model(**a						)

				# verify the logits
				SCREAMING_SNAKE_CASE :   Tuple					  =							tf.TensorShape((1, 1000)						)
				self.assertEqual(outputs.logits.shape   ,   a						)

				SCREAMING_SNAKE_CASE :   Dict					  =							tf.constant([-0.2744, 0.8215, -0.0836]						)

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

"""simple docstring"""




from collections.abc import Callable




def 			_lowerCAmelCase		(		_UpperCamelCase			,					_UpperCamelCase			,					_UpperCamelCase    ):






  """simple docstring"""



  _lowercase:      float   			=  a
  _lowercase:      float   			=  b
  if function(_UpperCamelCase    ) == 0:  # one of the a or b is a root for the function
    return a
  elif function(_UpperCamelCase    ) == 0:
    return b
  elif (
      function(_UpperCamelCase    ) * function(_UpperCamelCase    ) > 0
  ):  # if none of these are root and they are both positive or negative,
    # then this algorithm can't find the root
    raise ValueError('''could not find root in given interval.'''    )
  else:
    _lowercase:      float   			=  start + (end - start) / 2.0
    while abs(start - mid    ) > 10**-7:  # until precisely equals to 10^-7
      if function(_UpperCamelCase    ) == 0:
        return mid
      elif function(_UpperCamelCase    ) * function(_UpperCamelCase    ) < 0:
        _lowercase:      Union[str, Any]   			=  mid
      else:
        _lowercase:      Any   			=  mid
      _lowercase:      List[Any]   			=  start + (end - start) / 2.0
    return mid




def 			_lowerCAmelCase		(		_UpperCamelCase    ):






  """simple docstring"""



  return x**3 - 2 * x - 5


if __name__ == "__main__":
  print(bisection(f, 1, 1_0_0_0))

  import doctest

  doctest.testmod()
