



from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
						from PIL import Image

						from transformers import ConvNextImageProcessor



class     __snake_case						:




							def __init__(	self					:	List[str]    ,    A_					:	Union[str, Any]    ,    A_					:	Tuple=1_3    ,    A_					:	Optional[int]=3_2    ,    A_					:	List[Any]=3    ,    A_					:	Dict=4    ,    A_					:	Union[str, Any]=[1_0, 2_0, 3_0, 4_0]    ,    A_					:	Tuple=[2, 2, 3, 2]    ,    A_					:	Union[str, Any]=True    ,    A_					:	str=True    ,    A_					:	int=3_7    ,    A_					:	Any="gelu"    ,    A_					:	str=1_0    ,    A_					:	Dict=0.02    ,    A_					:	int=3    ,    A_					:	Any=None    ,    ):
									lowerCAmelCase_      :					Any     =			parent
									lowerCAmelCase_      :					str     =			batch_size
									lowerCAmelCase_      :					List[Any]     =			image_size
									lowerCAmelCase_      :					List[Any]     =			num_channels
									lowerCAmelCase_      :					Union[str, Any]     =			num_stages
									lowerCAmelCase_      :					Optional[Any]     =			hidden_sizes
									lowerCAmelCase_      :					Union[str, Any]     =			depths
									lowerCAmelCase_      :					str     =			is_training
									lowerCAmelCase_      :					str     =			use_labels
									lowerCAmelCase_      :					str     =			intermediate_size
									lowerCAmelCase_      :					Optional[int]     =			hidden_act
									lowerCAmelCase_      :					List[str]     =			type_sequence_label_size
									lowerCAmelCase_      :					Dict     =			initializer_range
									lowerCAmelCase_      :					Any     =			scope




							def        UpperCAmelCase__      (	self					:	Union[str, Any]):
									lowerCAmelCase_      :					Tuple     =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

									lowerCAmelCase_      :					int     =			None
									if self.use_labels:
											lowerCAmelCase_      :					Dict     =			ids_tensor([self.batch_size]    ,    self.type_sequence_label_size)

									lowerCAmelCase_      :					List[str]     =			self.get_config()

									return config, pixel_values, labels




							def        UpperCAmelCase__      (	self					:	Optional[Any]):
									return ConvNextConfig(
									    num_channels=self.num_channels    ,    hidden_sizes=self.hidden_sizes    ,    depths=self.depths    ,    num_stages=self.num_stages    ,    hidden_act=self.hidden_act    ,    is_decoder=A_    ,    initializer_range=self.initializer_range    ,    )




							def        UpperCAmelCase__      (	self					:	int    ,    A_					:	Tuple    ,    A_					:	Optional[Any]    ,    A_					:	Tuple):
									lowerCAmelCase_      :					Any     =			TFConvNextModel(config=A_)
									lowerCAmelCase_      :					Optional[int]     =			model(A_    ,    training=A_)
									# expected last hidden states: B, C, H // 32, W // 32
									self.parent.assertEqual(
									    result.last_hidden_state.shape    ,    (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)    ,    )




							def        UpperCAmelCase__      (	self					:	List[Any]    ,    A_					:	Tuple    ,    A_					:	str    ,    A_					:	Tuple):
									lowerCAmelCase_      :					List[Any]     =			self.type_sequence_label_size
									lowerCAmelCase_      :					str     =			TFConvNextForImageClassification(A_)
									lowerCAmelCase_      :					List[str]     =			model(A_    ,    labels=A_    ,    training=A_)
									self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.type_sequence_label_size))







							def        UpperCAmelCase__      (	self					:	Union[str, Any]):
									lowerCAmelCase_      :					int     =			self.prepare_config_and_inputs()
									lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_      :					Tuple     =			config_and_inputs
									lowerCAmelCase_      :					Dict     =			{'''pixel_values''': pixel_values}
									return config, inputs_dict





@require_tf
class     __snake_case						(					UpperCamelCase_						,UpperCamelCase_						,unittest.TestCase						):
							_a      				=			(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
							_a      				=			(
							    {'''feature-extraction''': TFConvNextModel, '''image-classification''': TFConvNextForImageClassification}
							    if is_tf_available()
							    else {}
							)

							_a      				=			False
							_a      				=			False
							_a      				=			False
							_a      				=			False
							_a      				=			False




							def        UpperCAmelCase__      (	self					:	Optional[Any]):
									lowerCAmelCase_      :					Optional[int]     =			TFConvNextModelTester(self)
									lowerCAmelCase_      :					str     =			ConfigTester(
									    self    ,    config_class=A_    ,    has_text_modality=A_    ,    hidden_size=3_7    ,    )




							@unittest.skip(reason='''ConvNext does not use inputs_embeds''')
							def        UpperCAmelCase__      (	self					:	Dict):
									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.'''    ,    )
							@slow
							def        UpperCAmelCase__      (	self					:	Optional[int]):
									super().test_keras_fit()




							@unittest.skip(reason='''ConvNext does not support input and output embeddings''')
							def        UpperCAmelCase__      (	self					:	Tuple):
									pass




							def        UpperCAmelCase__      (	self					:	List[str]):
									lowerCAmelCase_ ,  lowerCAmelCase_      :					Union[str, Any]     =			self.model_tester.prepare_config_and_inputs_for_common()

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

											lowerCAmelCase_      :					Dict     =			['''pixel_values''']
											self.assertListEqual(arg_names[:1]    ,    A_)




							def        UpperCAmelCase__      (	self					:	Optional[int]):
									lowerCAmelCase_      :					Dict     =			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*A_)




							@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        UpperCAmelCase__      (	self					:	int):
									super().test_dataset_conversion()




							def        UpperCAmelCase__      (	self					:	List[Any]):
									def check_hidden_states_output(A_					:	List[str]    ,    A_					:	int    ,    A_					:	List[str]):
											lowerCAmelCase_      :					Optional[Any]     =			model_class(A_)

											lowerCAmelCase_      :					Optional[Any]     =			model(**self._prepare_for_class(A_    ,    A_))
											lowerCAmelCase_      :					str     =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											lowerCAmelCase_      :					int     =			self.model_tester.num_stages
											self.assertEqual(len(A_)    ,    expected_num_stages + 1)

											# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
											self.assertListEqual(
											    list(hidden_states[0].shape[-2:])    ,    [self.model_tester.image_size // 4, self.model_tester.image_size // 4]    ,    )

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

									for model_class in self.all_model_classes:
											lowerCAmelCase_      :					List[str]     =			True
											check_hidden_states_output(A_    ,    A_    ,    A_)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											lowerCAmelCase_      :					int     =			True

											check_hidden_states_output(A_    ,    A_    ,    A_)




							def        UpperCAmelCase__      (	self					:	List[Any]):
									lowerCAmelCase_ ,  lowerCAmelCase_      :					str     =			self.model_tester.prepare_config_and_inputs_for_common()

									def check_equivalence(A_					:	int    ,    A_					:	Dict    ,    A_					:	str    ,    A_					:	List[Any]={}):
											lowerCAmelCase_      :					List[Any]     =			model(A_    ,    return_dict=A_    ,    **A_)
											lowerCAmelCase_      :					Any     =			model(A_    ,    return_dict=A_    ,    **A_).to_tuple()

											def recursive_check(A_					:	Union[str, Any]    ,    A_					:	Optional[int]):
													if isinstance(A_    ,    (List, Tuple)):
															for tuple_iterable_value, dict_iterable_value in zip(A_    ,    A_):
																	recursive_check(A_    ,    A_)
													elif tuple_object is None:
															return
													else:
															self.assertTrue(
															    all(tf.equal(A_    ,    A_))    ,    msg=(
															        '''Tuple and dict output are not equal. Difference:'''
															        F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}"""
															    )    ,    )

													recursive_check(A_    ,    A_)

									for model_class in self.all_model_classes:
											lowerCAmelCase_      :					List[Any]     =			model_class(A_)

											lowerCAmelCase_      :					Optional[int]     =			self._prepare_for_class(A_    ,    A_)
											lowerCAmelCase_      :					str     =			self._prepare_for_class(A_    ,    A_)
											check_equivalence(A_    ,    A_    ,    A_)

											lowerCAmelCase_      :					List[Any]     =			self._prepare_for_class(A_    ,    A_    ,    return_labels=A_)
											lowerCAmelCase_      :					str     =			self._prepare_for_class(A_    ,    A_    ,    return_labels=A_)
											check_equivalence(A_    ,    A_    ,    A_)

											lowerCAmelCase_      :					List[Any]     =			self._prepare_for_class(A_    ,    A_)
											lowerCAmelCase_      :					Tuple     =			self._prepare_for_class(A_    ,    A_)
											check_equivalence(A_    ,    A_    ,    A_    ,    {'''output_hidden_states''': True})

											lowerCAmelCase_      :					List[Any]     =			self._prepare_for_class(A_    ,    A_    ,    return_labels=A_)
											lowerCAmelCase_      :					Optional[Any]     =			self._prepare_for_class(A_    ,    A_    ,    return_labels=A_)
											check_equivalence(A_    ,    A_    ,    A_    ,    {'''output_hidden_states''': True})




							def        UpperCAmelCase__      (	self					:	int):
									lowerCAmelCase_      :					Tuple     =			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*A_)







							@slow
							def        UpperCAmelCase__      (	self					:	str):
									lowerCAmelCase_      :					Tuple     =			TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224''')
									self.assertIsNotNone(A_)





def       UpperCamelCase(  ):
		lowerCAmelCase_      :					List[Any]     =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
		return image





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




							@cached_property
							def        UpperCAmelCase__      (	self					:	str):
									return ConvNextImageProcessor.from_pretrained('''facebook/convnext-tiny-224''') if is_vision_available() else None







							@slow
							def        UpperCAmelCase__      (	self					:	int):
									lowerCAmelCase_      :					int     =			TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224''')

									lowerCAmelCase_      :					Dict     =			self.default_image_processor
									lowerCAmelCase_      :					Optional[Any]     =			prepare_img()
									lowerCAmelCase_      :					Optional[int]     =			image_processor(images=A_    ,    return_tensors='''tf''')

									# forward pass
									lowerCAmelCase_      :					Any     =			model(**A_)

									# verify the logits
									lowerCAmelCase_      :					Optional[int]     =			tf.TensorShape((1, 1_0_0_0))
									self.assertEqual(outputs.logits.shape    ,    A_)

									lowerCAmelCase_      :					Dict     =			tf.constant([-0.0260, -0.4739, 0.1911])

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










from math import radians as angle_to_radians
from math import sin

# Acceleration Constant on Earth (unit m/s^2)
A__  :  Any       = 9.8_0_6_6_5


def       UpperCamelCase(  __UpperCamelCase							:		float					,__UpperCamelCase							:		float			):

		# Ensure valid instance
		if not isinstance(__UpperCamelCase					,(int, float)			):
				raise TypeError('''Invalid velocity. Should be a positive number.'''			)

		if not isinstance(__UpperCamelCase					,(int, float)			):
				raise TypeError('''Invalid angle. Range is 1-90 degrees.'''			)

		# Ensure valid angle
		if angle > 90 or angle < 1:
				raise ValueError('''Invalid angle. Range is 1-90 degrees.'''			)

		# Ensure valid velocity
		if init_velocity < 0:
				raise ValueError('''Invalid velocity. Should be a positive number.'''			)


def       UpperCamelCase(  __UpperCamelCase							:		float					,__UpperCamelCase							:		float			):
		check_args(__UpperCamelCase					,__UpperCamelCase			)
		lowerCAmelCase_      :					Optional[Any]     =			angle_to_radians(2 * angle			)
		return round(init_velocity**2 * sin(__UpperCamelCase			) / g					,2			)


def       UpperCamelCase(  __UpperCamelCase							:		float					,__UpperCamelCase							:		float			):
		check_args(__UpperCamelCase					,__UpperCamelCase			)
		lowerCAmelCase_      :					Any     =			angle_to_radians(__UpperCamelCase			)
		return round(init_velocity**2 * sin(__UpperCamelCase			) ** 2 / (2 * g)					,2			)


def       UpperCamelCase(  __UpperCamelCase							:		float					,__UpperCamelCase							:		float			):
		check_args(__UpperCamelCase					,__UpperCamelCase			)
		lowerCAmelCase_      :					Dict     =			angle_to_radians(__UpperCamelCase			)
		return round(2 * init_velocity * sin(__UpperCamelCase			) / g					,2			)


def       UpperCamelCase(  ):
		lowerCAmelCase_ ,  lowerCAmelCase_      :					Any     =			25, 20
		assert horizontal_distance(__UpperCamelCase					,__UpperCamelCase			) == 4_0.9_7
		assert max_height(__UpperCamelCase					,__UpperCamelCase			) == 3.7_3
		assert total_time(__UpperCamelCase					,__UpperCamelCase			) == 1.7_4


if __name__ == "__main__":
						from doctest import testmod

						testmod()

						# Get input from user
						A__  :  List[Any]       = float(input('''Initial Velocity: ''').strip())

						# Get input from user
						A__  :  Dict       = float(input('''angle: ''').strip())

						# Print results
						print()
						print('''Results: ''')
						print(F'''Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]''')
						print(F'''Maximum Height: {max_height(init_vel, angle)!s} [m]''')
						print(F'''Total Time: {total_time(init_vel, angle)!s} [s]''')





