



from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
							from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor







class     __lowerCAmelCase					(    A		):



			def 					_lowerCamelCase (		self     :						Optional[Any])     ->					Optional[int]:



						"""simple docstring"""






						_UpperCAmelCase	 =     self.config_class(**self.inputs_dict)
						self.parent.assertTrue(hasattr(A				,	'embed_dim'))
						self.parent.assertTrue(hasattr(A				,	'num_heads'))







class     __lowerCAmelCase					:



			def __init__(		self     :						Optional[int]				,	A     :						int				,	A     :						int=13				,	A     :						Optional[Any]=64				,	A     :						Union[str, Any]=3				,	A     :						Tuple=[16, 48, 96]				,	A     :						int=[1, 3, 6]				,	A     :						Any=[1, 2, 10]				,	A     :						Any=[7, 3, 3]				,	A     :						List[str]=[4, 2, 2]				,	A     :						Dict=[2, 1, 1]				,	A     :						str=[2, 2, 2]				,	A     :						Union[str, Any]=[False, False, True]				,	A     :						int=[0.0, 0.0, 0.0]				,	A     :						int=0.0_2				,	A     :						Optional[int]=1E-12				,	A     :						Optional[int]=True				,	A     :						Tuple=True				,	A     :						Dict=2				,	)     ->					int:



						"""simple docstring"""






						_UpperCAmelCase	 =     parent
						_UpperCAmelCase	 =     batch_size
						_UpperCAmelCase	 =     image_size
						_UpperCAmelCase	 =     patch_sizes
						_UpperCAmelCase	 =     patch_stride
						_UpperCAmelCase	 =     patch_padding
						_UpperCAmelCase	 =     is_training
						_UpperCAmelCase	 =     use_labels
						_UpperCAmelCase	 =     num_labels
						_UpperCAmelCase	 =     num_channels
						_UpperCAmelCase	 =     embed_dim
						_UpperCAmelCase	 =     num_heads
						_UpperCAmelCase	 =     stride_kv
						_UpperCAmelCase	 =     depth
						_UpperCAmelCase	 =     cls_token
						_UpperCAmelCase	 =     attention_drop_rate
						_UpperCAmelCase	 =     initializer_range
						_UpperCAmelCase	 =     layer_norm_eps



			def 					_lowerCamelCase (		self     :						List[str])     ->					Union[str, Any]:



						"""simple docstring"""






						_UpperCAmelCase	 =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

						_UpperCAmelCase	 =     None
						if self.use_labels:
									# create a random int32 tensor of given shape
									_UpperCAmelCase	 =     ids_tensor([self.batch_size]				,	self.num_labels)

						_UpperCAmelCase	 =     self.get_config()
						return config, pixel_values, labels



			def 					_lowerCamelCase (		self     :						List[str])     ->					Union[str, Any]:



						"""simple docstring"""






						return CvtConfig(
						    image_size=self.image_size				,	num_labels=self.num_labels				,	num_channels=self.num_channels				,	embed_dim=self.embed_dim				,	num_heads=self.num_heads				,	patch_sizes=self.patch_sizes				,	patch_padding=self.patch_padding				,	patch_stride=self.patch_stride				,	stride_kv=self.stride_kv				,	depth=self.depth				,	cls_token=self.cls_token				,	attention_drop_rate=self.attention_drop_rate				,	initializer_range=self.initializer_range				,	)



			def 					_lowerCamelCase (		self     :						List[Any]				,	A     :						str				,	A     :						List[str]				,	A     :						Tuple)     ->					Tuple:



						"""simple docstring"""






						_UpperCAmelCase	 =     TFCvtModel(config=A)
						_UpperCAmelCase	 =     model(A				,	training=A)
						_UpperCAmelCase	 =     (self.image_size, self.image_size)
						_UpperCAmelCase ,  _UpperCAmelCase	 =     image_size[0], image_size[1]
						for i in range(len(self.depth)):
									_UpperCAmelCase	 =     floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
									_UpperCAmelCase	 =     floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
						self.parent.assertEqual(result.last_hidden_state.shape				,	(self.batch_size, self.embed_dim[-1], height, width))



			def 					_lowerCamelCase (		self     :						Tuple				,	A     :						Optional[int]				,	A     :						int				,	A     :						int)     ->					Dict:



						"""simple docstring"""






						_UpperCAmelCase	 =     self.num_labels
						_UpperCAmelCase	 =     TFCvtForImageClassification(A)
						_UpperCAmelCase	 =     model(A				,	labels=A				,	training=A)
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.num_labels))



			def 					_lowerCamelCase (		self     :						int)     ->					Any:



						"""simple docstring"""






						_UpperCAmelCase	 =     self.prepare_config_and_inputs()
						_UpperCAmelCase ,  _UpperCAmelCase ,  _UpperCAmelCase	 =     config_and_inputs
						_UpperCAmelCase	 =     {'pixel_values': pixel_values}
						return config, inputs_dict







@require_tf
class     __lowerCAmelCase					(    A       ,		A       ,		unittest.TestCase		):
			UpperCamelCase           =  (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
			UpperCamelCase           =  (
			    {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
			    if is_tf_available()
			    else {}
			)
			UpperCamelCase           =  False
			UpperCamelCase           =  False
			UpperCamelCase           =  False
			UpperCamelCase           =  False
			UpperCamelCase           =  False



			def 					_lowerCamelCase (		self     :						Optional[int])     ->					List[str]:



						"""simple docstring"""






						_UpperCAmelCase	 =     TFCvtModelTester(self)
						_UpperCAmelCase	 =     TFCvtConfigTester(self				,	config_class=A				,	has_text_modality=A				,	hidden_size=37)



			def 					_lowerCamelCase (		self     :						Optional[int])     ->					Any:



						"""simple docstring"""






						self.config_tester.create_and_test_config_common_properties()
						self.config_tester.create_and_test_config_to_json_string()
						self.config_tester.create_and_test_config_to_json_file()
						self.config_tester.create_and_test_config_from_and_save_pretrained()
						self.config_tester.create_and_test_config_with_num_labels()
						self.config_tester.check_config_can_be_init_without_params()
						self.config_tester.check_config_arguments_init()



			@unittest.skip(reason='Cvt does not output attentions')
			def 					_lowerCamelCase (		self     :						Optional[int])     ->					int:



						"""simple docstring"""






						pass



			@unittest.skip(reason='Cvt does not use inputs_embeds')
			def 					_lowerCamelCase (		self     :						Any)     ->					int:



						"""simple docstring"""






						pass



			@unittest.skip(reason='Cvt does not support input and output embeddings')
			def 					_lowerCamelCase (		self     :						Optional[Any])     ->					Dict:



						"""simple docstring"""






						pass



			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('GPU')) == 0				,	reason='TF does not support backprop for grouped convolutions on CPU.'				,	)
			def 					_lowerCamelCase (		self     :						Union[str, Any])     ->					Tuple:



						"""simple docstring"""






						super().test_dataset_conversion()



			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('GPU')) == 0				,	reason='TF does not support backprop for grouped convolutions on CPU.'				,	)
			@slow
			def 					_lowerCamelCase (		self     :						Tuple)     ->					Optional[int]:



						"""simple docstring"""






						super().test_keras_fit()



			@unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8')
			def 					_lowerCamelCase (		self     :						Optional[int])     ->					List[str]:



						"""simple docstring"""






						_UpperCAmelCase	 =     tf.keras.mixed_precision.Policy('mixed_float16')
						tf.keras.mixed_precision.set_global_policy(A)
						super().test_keras_fit()
						tf.keras.mixed_precision.set_global_policy('float32')



			def 					_lowerCamelCase (		self     :						Optional[int])     ->					Tuple:



						"""simple docstring"""






						_UpperCAmelCase ,  _UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs_for_common()

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

									_UpperCAmelCase	 =     ['pixel_values']
									self.assertListEqual(arg_names[:1]				,	A)



			def 					_lowerCamelCase (		self     :						Union[str, Any])     ->					Any:



						"""simple docstring"""






						def check_hidden_states_output(A     :						int				,	A     :						Optional[int]				,	A     :						List[str]):
									_UpperCAmelCase	 =     model_class(A)

									_UpperCAmelCase	 =     model(**self._prepare_for_class(A				,	A))
									_UpperCAmelCase	 =     outputs.hidden_states

									_UpperCAmelCase	 =     len(self.model_tester.depth)
									self.assertEqual(len(A)				,	A)

									# verify the first hidden states (first block)
									self.assertListEqual(
									    list(hidden_states[0].shape[-3:])				,	[
									        self.model_tester.embed_dim[0],
									        self.model_tester.image_size // 4,
									        self.model_tester.image_size // 4,
									    ]				,	)

						_UpperCAmelCase ,  _UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									_UpperCAmelCase	 =     True
									check_hidden_states_output(A				,	A				,	A)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									_UpperCAmelCase	 =     True

									check_hidden_states_output(A				,	A				,	A)



			def 					_lowerCamelCase (		self     :						str)     ->					str:



						"""simple docstring"""






						_UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*A)



			def 					_lowerCamelCase (		self     :						Dict)     ->					Dict:



						"""simple docstring"""






						_UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*A)



			@slow
			def 					_lowerCamelCase (		self     :						int)     ->					int:



						"""simple docstring"""






						for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									_UpperCAmelCase	 =     TFCvtModel.from_pretrained(A)
									self.assertIsNotNone(A)





def 							A			(  )       ->				Optional[Any]:







			'''simple docstring'''
			_UpperCAmelCase	 =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
			return image







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



			@cached_property
			def 					_lowerCamelCase (		self     :						int)     ->					Optional[int]:



						"""simple docstring"""






						return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])



			@slow
			def 					_lowerCamelCase (		self     :						Union[str, Any])     ->					Dict:



						"""simple docstring"""






						_UpperCAmelCase	 =     TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])

						_UpperCAmelCase	 =     self.default_image_processor
						_UpperCAmelCase	 =     prepare_img()
						_UpperCAmelCase	 =     image_processor(images=A				,	return_tensors='tf')

						# forward pass
						_UpperCAmelCase	 =     model(**A)

						# verify the logits
						_UpperCAmelCase	 =     tf.TensorShape((1, 10_00))
						self.assertEqual(outputs.logits.shape				,	A)

						_UpperCAmelCase	 =     tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0])
						self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()				,	A				,	atol=1E-4))





from sympy import diff, lambdify, symbols
from sympy.functions import *  # noqa: F403





def 							A			(  _UpperCAmelCase       :     str							,     _UpperCAmelCase       :     complex							,     _UpperCAmelCase       :     str = "x"							,     _UpperCAmelCase       :     float = 10**-10							,     _UpperCAmelCase       :     int = 1							,     )       ->				complex:







			'''simple docstring'''
			_UpperCAmelCase	 =     symbols(_UpperCAmelCase					)
			_UpperCAmelCase	 =     lambdify(_UpperCAmelCase							,     _UpperCAmelCase					)
			_UpperCAmelCase	 =     lambdify(_UpperCAmelCase							,     diff(_UpperCAmelCase							,     _UpperCAmelCase					)					)

			_UpperCAmelCase	 =     starting_point

			while True:
						if diff_function(_UpperCAmelCase					) != 0:
									_UpperCAmelCase	 =     prev_guess - multiplicity * func(_UpperCAmelCase					) / diff_function(
									    _UpperCAmelCase					)
						else:
									raise ZeroDivisionError('Could not find root'					) from None

						# Precision is checked by comparing the difference of consecutive guesses
						if abs(next_guess - prev_guess					) < precision:
									return next_guess

						_UpperCAmelCase	 =     next_guess


# Let's Execute
if __name__ == "__main__":
							# Find root of trigonometric function
							# Find value of pi
							print(f"""The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}""")

							# Find root of polynomial
							# Find fourth Root of 5
							print(f"""The root of x**4 - 5 = 0 is {newton_raphson("x**4 -5", 0.4 +5J)}""")

							# Find value of e
							print(
							    "The root of log(y) - 1 = 0 is ",
							    f"""{newton_raphson("log(y) - 1", 2, variable="y")}""",
							)

							# Exponential Roots
							print(
							    "The root of exp(x) - 1 = 0 is",
							    f"""{newton_raphson("exp(x) - 1", 10, precision=0.005)}""",
							)

							# Find root of cos(x)
							print(f"""The root of cos(x) = 0 is {newton_raphson("cos(x)", 0)}""")
