
import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
					import jax
					import jax.numpy as jnp

					from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor







class 	A__				(	unittest.TestCase      ):






				def __init__(		self   : List[Any]       ,	a   : Optional[Any]       ,	a   : List[str]=3       ,	a   : Union[str, Any]=32       ,	a   : Tuple=3       ,	a   : int=10       ,	a   : int=[10, 20, 30, 40]       ,	a   : List[Any]=[1, 1, 2, 1]       ,	a   : Optional[int]=True       ,	a   : int=True       ,	a   : Any="relu"       ,	a   : Optional[int]=3       ,	a   : List[Any]=None       ,	):






							'''simple docstring'''







							lowerCAmelCase__ : str   =						parent
							lowerCAmelCase__ : Union[str, Any]   =						batch_size
							lowerCAmelCase__ : Any   =						image_size
							lowerCAmelCase__ : Dict   =						num_channels
							lowerCAmelCase__ : List[Any]   =						embeddings_size
							lowerCAmelCase__ : Optional[Any]   =						hidden_sizes
							lowerCAmelCase__ : List[Any]   =						depths
							lowerCAmelCase__ : int   =						is_training
							lowerCAmelCase__ : Any   =						use_labels
							lowerCAmelCase__ : Tuple   =						hidden_act
							lowerCAmelCase__ : Optional[int]   =						num_labels
							lowerCAmelCase__ : Union[str, Any]   =						scope
							lowerCAmelCase__ : str   =						len(lowerCamelCase__  )






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






							'''simple docstring'''







							lowerCAmelCase__ : Dict   =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

							lowerCAmelCase__ : Optional[Any]   =						self.get_config()

							return config, pixel_values






				def 				_lowerCamelCase						(		self   : Optional[Any]  ):






							'''simple docstring'''







							return ResNetConfig(
							    num_channels=self.num_channels       ,	embeddings_size=self.embeddings_size       ,	hidden_sizes=self.hidden_sizes       ,	depths=self.depths       ,	hidden_act=self.hidden_act       ,	num_labels=self.num_labels       ,	image_size=self.image_size       ,	)






				def 				_lowerCamelCase						(		self   : Optional[int]       ,	a   : Tuple       ,	a   : Optional[int]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Optional[Any]   =						FlaxResNetModel(config=lowerCamelCase__  )
							lowerCAmelCase__ : Dict   =						model(lowerCamelCase__  )

							# Output shape (b, c, h, w)
							self.parent.assertEqual(
							    result.last_hidden_state.shape       ,	(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,	)






				def 				_lowerCamelCase						(		self   : Any       ,	a   : int       ,	a   : int  ):






							'''simple docstring'''







							lowerCAmelCase__ : List[Any]   =						self.num_labels
							lowerCAmelCase__ : Optional[int]   =						FlaxResNetForImageClassification(config=lowerCamelCase__  )
							lowerCAmelCase__ : int   =						model(lowerCamelCase__  )
							self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_labels)  )






				def 				_lowerCamelCase						(		self   : Optional[int]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Any   =						self.prepare_config_and_inputs()
							lowerCAmelCase__ ,							lowerCAmelCase__ : Optional[int]   =						config_and_inputs
							lowerCAmelCase__ : Optional[Any]   =						{'pixel_values': pixel_values}
							return config, inputs_dict







@require_flax
class 	A__				(	lowerCAmelCase_		,  unittest.TestCase      ):
				lowercase            =    (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

				lowercase            =    False
				lowercase            =    False
				lowercase            =    False






				def 				_lowerCamelCase						(		self   : List[str]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Tuple   =						FlaxResNetModelTester(self  )
							lowerCAmelCase__ : Tuple   =						ConfigTester(self       ,	config_class=lowerCamelCase__       ,	has_text_modality=lowerCamelCase__  )






				def 				_lowerCamelCase						(		self   : Any  ):






							'''simple docstring'''







							self.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()






				def 				_lowerCamelCase						(		self   : Tuple  ):






							'''simple docstring'''







							return






				def 				_lowerCamelCase						(		self   : Optional[Any]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Tuple   =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__  )






				def 				_lowerCamelCase						(		self   : List[Any]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Tuple   =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__  )






				@unittest.skip(reason='ResNet does not use inputs_embeds'  )
				def 				_lowerCamelCase						(		self   : Optional[Any]  ):






							'''simple docstring'''







							pass






				@unittest.skip(reason='ResNet does not support input and output embeddings'  )
				def 				_lowerCamelCase						(		self   : Union[str, Any]  ):






							'''simple docstring'''







							pass






				def 				_lowerCamelCase						(		self   : Optional[Any]  ):






							'''simple docstring'''







							lowerCAmelCase__ ,							lowerCAmelCase__ : Union[str, Any]   =						self.model_tester.prepare_config_and_inputs_for_common()

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

										lowerCAmelCase__ : Any   =						['pixel_values']
										self.assertListEqual(arg_names[:1]       ,	lowerCamelCase__  )






				def 				_lowerCamelCase						(		self   : int  ):






							'''simple docstring'''







							def check_hidden_states_output(a   : List[str]       ,	a   : Optional[Any]       ,	a   : str  ):
										lowerCAmelCase__ : Tuple   =						model_class(lowerCamelCase__  )

										lowerCAmelCase__ : int   =						model(**self._prepare_for_class(lowerCamelCase__       ,	lowerCamelCase__  )  )

										lowerCAmelCase__ : Optional[int]   =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										lowerCAmelCase__ : List[Any]   =						self.model_tester.num_stages
										self.assertEqual(len(lowerCamelCase__  )       ,	expected_num_stages + 1  )






				@unittest.skip(reason='ResNet does not use feedforward chunking'  )
				def 				_lowerCamelCase						(		self   : int  ):






							'''simple docstring'''







							pass






				def 				_lowerCamelCase						(		self   : str  ):






							'''simple docstring'''







							lowerCAmelCase__ ,							lowerCAmelCase__ : Dict   =						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										with self.subTest(model_class.__name__  ):
													lowerCAmelCase__ : List[str]   =						self._prepare_for_class(lowerCamelCase__       ,	lowerCamelCase__  )
													lowerCAmelCase__ : str   =						model_class(lowerCamelCase__  )

													@jax.jit
													def model_jitted(a   : List[str]       ,	**a   : List[str]  ):
																return model(pixel_values=lowerCamelCase__       ,	**lowerCamelCase__  )

													with self.subTest('JIT Enabled'  ):
																lowerCAmelCase__ : List[str]   =						model_jitted(**lowerCamelCase__  ).to_tuple()

													with self.subTest('JIT Disabled'  ):
																with jax.disable_jit():
																			lowerCAmelCase__ : Dict   =						model_jitted(**lowerCamelCase__  ).to_tuple()

													self.assertEqual(len(lowerCamelCase__  )       ,	len(lowerCamelCase__  )  )
													for jitted_output, output in zip(lowerCamelCase__       ,	lowerCamelCase__  ):
																self.assertEqual(jitted_output.shape       ,	output.shape  )






def 					lowerCAmelCase__     (    )							->						List[str]:
			lowerCAmelCase__ : Optional[int]   =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
			return image







@require_flax
class 	A__				(	unittest.TestCase      ):






				@cached_property
				def 				_lowerCamelCase						(		self   : Optional[Any]  ):






							'''simple docstring'''







							return AutoImageProcessor.from_pretrained('microsoft/resnet-50'  ) if is_vision_available() else None






				@slow
				def 				_lowerCamelCase						(		self   : List[Any]  ):






							'''simple docstring'''







							lowerCAmelCase__ : Optional[Any]   =						FlaxResNetForImageClassification.from_pretrained('microsoft/resnet-50'  )

							lowerCAmelCase__ : str   =						self.default_image_processor
							lowerCAmelCase__ : Optional[Any]   =						prepare_img()
							lowerCAmelCase__ : Dict   =						image_processor(images=lowerCamelCase__       ,	return_tensors='np'  )

							lowerCAmelCase__ : Tuple   =						model(**lowerCamelCase__  )

							# verify the logits
							lowerCAmelCase__ : Dict   =						(1, 1_000)
							self.assertEqual(outputs.logits.shape       ,	lowerCamelCase__  )

							lowerCAmelCase__ : Optional[int]   =						jnp.array([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]  )

							self.assertTrue(jnp.allclose(outputs.logits[0, :3]       ,	lowerCamelCase__       ,	atol=1E-4  )  )






from __future__ import annotations

from collections.abc import Iterable

class 						UpperCamelCase__					:



     '''simple docstring'''

     def __init__(				self		:       Optional[Any]		,lowerCamelCase__		:       Optional[int]		,lowerCamelCase__		:       List[Any]			)	->						int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,   SCREAMING_SNAKE_CASE						=		float(lowerCamelCase__			), float(lowerCamelCase__			)






     def __eq__(				self		:       int		,lowerCamelCase__		:       Union[str, Any]			)	->						List[str]:




           '''simple docstring'''


           return self.x == other.x and self.y == other.y






     def __ne__(				self		:       Optional[int]		,lowerCamelCase__		:       int			)	->						Dict:




           '''simple docstring'''


           return not self == other






     def __gt__(				self		:       Optional[Any]		,lowerCamelCase__		:       Optional[Any]			)	->						List[Any]:




           '''simple docstring'''


           if self.x > other.x:
                 return True
           elif self.x == other.x:
                 return self.y > other.y
           return False






     def __lt__(				self		:       Union[str, Any]		,lowerCamelCase__		:       Optional[Any]			)	->						Optional[Any]:




           '''simple docstring'''


           return not self > other






     def __ge__(				self		:       Optional[Any]		,lowerCamelCase__		:       Tuple			)	->						Optional[Any]:




           '''simple docstring'''


           if self.x > other.x:
                 return True
           elif self.x == other.x:
                 return self.y >= other.y
           return False






     def __le__(				self		:       Tuple		,lowerCamelCase__		:       int			)	->						Dict:




           '''simple docstring'''


           if self.x < other.x:
                 return True
           elif self.x == other.x:
                 return self.y <= other.y
           return False






     def __repr__(				self		:       Dict			)	->						Any:




           '''simple docstring'''


           return F"""({self.x}, {self.y})"""






     def __hash__(				self		:       List[Any]			)	->						List[Any]:




           '''simple docstring'''


           return hash(self.x			)



def   __lowercase  ( _SCREAMING_SNAKE_CASE					,		)					->  list[Point]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE						=		[]
      if list_of_tuples:
            for p in list_of_tuples:
                  if isinstance(_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      ):
                        points.append(_SCREAMING_SNAKE_CASE      )
                  else:
                        try:
                              points.append(Point(p[0]					,		p[1]      )      )
                        except (IndexError, TypeError):
                              print(
                                  F"""Ignoring deformed point {p}. All points"""
                                  """ must have at least 2 coordinates."""      )
      return points



def   __lowercase  ( _SCREAMING_SNAKE_CASE      )					->  list[Point]:


      '''simple docstring'''


      if not hasattr(_SCREAMING_SNAKE_CASE					,		"""__iter__"""      ):
            SCREAMING_SNAKE_CASE						=		F"""Expecting an iterable object but got an non-iterable type {points}"""
            raise ValueError(_SCREAMING_SNAKE_CASE      )

      if not points:
            SCREAMING_SNAKE_CASE						=		F"""Expecting a list of points but got {points}"""
            raise ValueError(_SCREAMING_SNAKE_CASE      )

      return _construct_points(_SCREAMING_SNAKE_CASE      )



def   __lowercase  ( _SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      )					->  float:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE						=		(a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
      return det



def   __lowercase  ( _SCREAMING_SNAKE_CASE      )					->  list[Point]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE						=		sorted(_validate_input(_SCREAMING_SNAKE_CASE      )      )
      SCREAMING_SNAKE_CASE						=		len(_SCREAMING_SNAKE_CASE      )
      SCREAMING_SNAKE_CASE						=		set()

      for i in range(n - 1      ):
            for j in range(i + 1					,		_SCREAMING_SNAKE_CASE      ):
                  SCREAMING_SNAKE_CASE						=		SCREAMING_SNAKE_CASE						=		False
                  SCREAMING_SNAKE_CASE						=		True
                  for k in range(_SCREAMING_SNAKE_CASE      ):
                        if k != i and k != j:
                              SCREAMING_SNAKE_CASE						=		_det(points[i]					,		points[j]					,		points[k]      )

                              if det_k > 0:
                                    SCREAMING_SNAKE_CASE						=		True
                              elif det_k < 0:
                                    SCREAMING_SNAKE_CASE						=		True
                              else:
                                    # point[i], point[j], point[k] all lie on a straight line
                                    # if point[k] is to the left of point[i] or it's to the
                                    # right of point[j], then point[i], point[j] cannot be
                                    # part of the convex hull of A
                                    if points[k] < points[i] or points[k] > points[j]:
                                          SCREAMING_SNAKE_CASE						=		False
                                          break

                        if points_left_of_ij and points_right_of_ij:
                              SCREAMING_SNAKE_CASE						=		False
                              break

                  if ij_part_of_convex_hull:
                        convex_set.update([points[i], points[j]]      )

      return sorted(_SCREAMING_SNAKE_CASE      )



def   __lowercase  ( _SCREAMING_SNAKE_CASE      )					->  list[Point]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE						=		sorted(_validate_input(_SCREAMING_SNAKE_CASE      )      )
      SCREAMING_SNAKE_CASE						=		len(_SCREAMING_SNAKE_CASE      )

      # divide all the points into an upper hull and a lower hull
      # the left most point and the right most point are definitely
      # members of the convex hull by definition.
      # use these two anchors to divide all the points into two hulls,
      # an upper hull and a lower hull.

      # all points to the left (above) the line joining the extreme points belong to the
      # upper hull
      # all points to the right (below) the line joining the extreme points below to the
      # lower hull
      # ignore all points on the line joining the extreme points since they cannot be
      # part of the convex hull

      SCREAMING_SNAKE_CASE						=		points[0]
      SCREAMING_SNAKE_CASE						=		points[n - 1]

      SCREAMING_SNAKE_CASE						=		{left_most_point, right_most_point}
      SCREAMING_SNAKE_CASE						=		[]
      SCREAMING_SNAKE_CASE						=		[]

      for i in range(1					,		n - 1      ):
            SCREAMING_SNAKE_CASE						=		_det(_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		points[i]      )

            if det > 0:
                  upper_hull.append(points[i]      )
            elif det < 0:
                  lower_hull.append(points[i]      )

      _construct_hull(_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      )
      _construct_hull(_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      )

      return sorted(_SCREAMING_SNAKE_CASE      )



def   __lowercase  ( _SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      )					->  None:


      '''simple docstring'''


      if points:
            SCREAMING_SNAKE_CASE						=		None
            SCREAMING_SNAKE_CASE						=		float("""-inf"""      )
            SCREAMING_SNAKE_CASE						=		[]

            for p in points:
                  SCREAMING_SNAKE_CASE						=		_det(_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      )

                  if det > 0:
                        candidate_points.append(_SCREAMING_SNAKE_CASE      )

                        if det > extreme_point_distance:
                              SCREAMING_SNAKE_CASE						=		det
                              SCREAMING_SNAKE_CASE						=		p

            if extreme_point:
                  _construct_hull(_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      )
                  convex_set.add(_SCREAMING_SNAKE_CASE      )
                  _construct_hull(_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      )



def   __lowercase  ( _SCREAMING_SNAKE_CASE      )					->  list[Point]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE						=		sorted(_validate_input(_SCREAMING_SNAKE_CASE      )      )
      SCREAMING_SNAKE_CASE						=		len(_SCREAMING_SNAKE_CASE      )

      SCREAMING_SNAKE_CASE						=		points[:2]
      for i in range(2					,		_SCREAMING_SNAKE_CASE      ):
            SCREAMING_SNAKE_CASE						=		_det(convex_hull[1]					,		convex_hull[0]					,		points[i]      )
            if det > 0:
                  convex_hull.insert(0					,		points[i]      )
                  break
            elif det < 0:
                  convex_hull.append(points[i]      )
                  break
            else:
                  SCREAMING_SNAKE_CASE						=		points[i]
      i += 1

      for j in range(_SCREAMING_SNAKE_CASE					,		_SCREAMING_SNAKE_CASE      ):
            if (
                _det(convex_hull[0]					,		convex_hull[-1]					,		points[j]      ) > 0
                and _det(convex_hull[-1]					,		convex_hull[0]					,		points[1]      ) < 0
            ):
                  # The point lies within the convex hull
                  continue

            convex_hull.insert(0					,		points[j]      )
            convex_hull.append(points[j]      )
            while _det(convex_hull[0]					,		convex_hull[1]					,		convex_hull[2]      ) >= 0:
                  del convex_hull[1]
            while _det(convex_hull[-1]					,		convex_hull[-2]					,		convex_hull[-3]      ) <= 0:
                  del convex_hull[-2]

    # `convex_hull` is contains the convex hull in circular order
      return sorted(convex_hull[1:] if len(_SCREAMING_SNAKE_CASE      ) > 3 else convex_hull      )



def   __lowercase  ( )					->  Any:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE						=		[
          (0, 3),
          (2, 2),
          (1, 1),
          (2, 1),
          (3, 0),
          (0, 0),
          (3, 3),
          (2, -1),
          (2, -4),
          (1, -3),
      ]
      # the convex set of points is
      # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
      SCREAMING_SNAKE_CASE						=		convex_hull_bf(_SCREAMING_SNAKE_CASE      )

      SCREAMING_SNAKE_CASE						=		convex_hull_recursive(_SCREAMING_SNAKE_CASE      )
      assert results_bf == results_recursive

      SCREAMING_SNAKE_CASE						=		convex_hull_melkman(_SCREAMING_SNAKE_CASE      )
      assert results_bf == results_melkman

      print(_SCREAMING_SNAKE_CASE      )


if __name__ == "__main__":
      main()


