
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
   from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor






class UpperCAmelCase   :





   '''simple docstring'''


   def __init__(					self     :							str			,			lowerCAmelCase_     :							str			,			lowerCAmelCase_     :							List[str]=3			,			lowerCAmelCase_     :							Dict=3_2			,			lowerCAmelCase_     :							List[Any]=3			,			lowerCAmelCase_     :							Tuple=1_0			,			lowerCAmelCase_     :							Union[str, Any]=[1_0, 2_0, 3_0, 4_0]			,			lowerCAmelCase_     :							Union[str, Any]=[1, 1, 2, 1]			,			lowerCAmelCase_     :							Optional[Any]=True			,			lowerCAmelCase_     :							List[str]=True			,			lowerCAmelCase_     :							List[Any]="relu"			,			lowerCAmelCase_     :							Any=3			,			lowerCAmelCase_     :							Optional[int]=None			,			):

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


   def  __magic_name__				(					self     :							Optional[Any]     ):

      """simple docstring"""
      _A:  List[str]					=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

      _A:  Tuple					=       None
      if self.use_labels:
         _A:  List[Any]					=       ids_tensor([self.batch_size]			,			self.num_labels     )

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

      return config, pixel_values, labels


   def  __magic_name__				(					self     :							Dict     ):

      """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  __magic_name__				(					self     :							Tuple			,			lowerCAmelCase_     :							Optional[Any]			,			lowerCAmelCase_     :							Dict			,			lowerCAmelCase_     :							Optional[Any]     ):

      """simple docstring"""
      _A:  List[str]					=       TFResNetModel(config=lowerCAmelCase_     )
      _A:  Optional[int]					=       model(lowerCAmelCase_     )
      # 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  __magic_name__				(					self     :							Optional[Any]			,			lowerCAmelCase_     :							Union[str, Any]			,			lowerCAmelCase_     :							Any			,			lowerCAmelCase_     :							List[Any]     ):

      """simple docstring"""
      _A:  Dict					=       self.num_labels
      _A:  List[str]					=       TFResNetForImageClassification(lowerCAmelCase_     )
      _A:  Any					=       model(lowerCAmelCase_			,			labels=lowerCAmelCase_     )
      self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)     )


   def  __magic_name__				(					self     :							List[Any]     ):

      """simple docstring"""
      _A:  str					=       self.prepare_config_and_inputs()
      _A:  Tuple					=       config_and_inputs
      _A:  Tuple					=       {'pixel_values': pixel_values}
      return config, inputs_dict






@require_tf
class UpperCAmelCase   (						__UpperCamelCase							,							__UpperCamelCase							,							unittest.TestCase   ):





   '''simple docstring'''
   __UpperCamelCase		:    Union[str, Any] 				=    (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
   __UpperCamelCase		:    Union[str, Any] 				=    (
       {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
       if is_tf_available()
       else {}
   )

   __UpperCamelCase		:    int 				=    False
   __UpperCamelCase		:    str 				=    False
   __UpperCamelCase		:    Union[str, Any] 				=    False
   __UpperCamelCase		:    str 				=    False
   __UpperCamelCase		:    Any 				=    False


   def  __magic_name__				(					self     :							Tuple     ):

      """simple docstring"""
      _A:  Optional[Any]					=       TFResNetModelTester(self     )
      _A:  Tuple					=       ConfigTester(self			,			config_class=lowerCAmelCase_			,			has_text_modality=lowerCAmelCase_     )


   def  __magic_name__				(					self     :							int     ):

      """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  __magic_name__				(					self     :							List[Any]     ):

      """simple docstring"""
      return


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

      """simple docstring"""
      pass


   @unittest.skip(reason='''ResNet does not support input and output embeddings'''     )
   def  __magic_name__				(					self     :							List[Any]     ):

      """simple docstring"""
      pass


   def  __magic_name__				(					self     :							List[str]     ):

      """simple docstring"""
      _A:  List[Any]					=       self.model_tester.prepare_config_and_inputs_for_common()

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

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


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

      """simple docstring"""
      _A:  List[str]					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCAmelCase_     )


   def  __magic_name__				(					self     :							str     ):

      """simple docstring"""
      def check_hidden_states_output(lowerCAmelCase_     :							Any			,			lowerCAmelCase_     :							List[Any]			,			lowerCAmelCase_     :							Optional[Any]     ):
         _A:  Union[str, Any]					=       model_class(lowerCAmelCase_     )
         _A:  Dict					=       model(**self._prepare_for_class(lowerCAmelCase_			,			lowerCAmelCase_     )     )

         _A:  List[str]					=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         _A:  str					=       self.model_tester.num_stages
         self.assertEqual(len(lowerCAmelCase_     )			,			expected_num_stages + 1     )

         # ResNet'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]			,			)

      _A:  Tuple					=       self.model_tester.prepare_config_and_inputs_for_common()
      _A:  Optional[Any]					=       ['basic', 'bottleneck']
      for model_class in self.all_model_classes:
         for layer_type in layers_type:
            _A:  int					=       layer_type
            _A:  int					=       True
            check_hidden_states_output(lowerCAmelCase_			,			lowerCAmelCase_			,			lowerCAmelCase_     )

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            _A:  List[str]					=       True

            check_hidden_states_output(lowerCAmelCase_			,			lowerCAmelCase_			,			lowerCAmelCase_     )


   def  __magic_name__				(					self     :							List[str]     ):

      """simple docstring"""
      _A:  Any					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_     )


   @slow
   def  __magic_name__				(					self     :							List[str]     ):

      """simple docstring"""
      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _A:  int					=       TFResNetModel.from_pretrained(lowerCAmelCase_     )
         self.assertIsNotNone(lowerCAmelCase_     )






def   lowerCamelCase__							(					)      ->   Optional[Any]:
   _A:  Optional[Any]					=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
   return image






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





   '''simple docstring'''


   @cached_property
   def  __magic_name__				(					self     :							int     ):

      """simple docstring"""
      return (
          AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
          if is_vision_available()
          else None
      )


   @slow
   def  __magic_name__				(					self     :							List[str]     ):

      """simple docstring"""
      _A:  Union[str, Any]					=       TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )

      _A:  str					=       self.default_image_processor
      _A:  Tuple					=       prepare_img()
      _A:  Optional[int]					=       image_processor(images=lowerCAmelCase_			,			return_tensors='''tf'''     )

      # forward pass
      _A:  Union[str, Any]					=       model(**lowerCAmelCase_     )

      # verify the logits
      _A:  Union[str, Any]					=       tf.TensorShape((1, 1_0_0_0)     )
      self.assertEqual(outputs.logits.shape			,			lowerCAmelCase_     )

      _A:  Any					=       tf.constant([-1_1.1_0_6_9, -9.7877, -8.3777]     )

      self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()			,			lowerCAmelCase_			,			atol=1e-4     )     )










from __future__ import annotations


def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase						,	_UpperCAmelCase )			->     list[tuple[int, int]]:
    lowerCamelCase__ ,							lowerCamelCase__    :      Union[str, Any]					 =		position
    lowerCamelCase__    :      Optional[Any]					 =		[
        (y + 1, x + 2),
        (y - 1, x + 2),
        (y + 1, x - 2),
        (y - 1, x - 2),
        (y + 2, x + 1),
        (y + 2, x - 1),
        (y - 2, x + 1),
        (y - 2, x - 1),
    ]
    lowerCamelCase__    :      Dict					 =		[]

    for position in positions:
        lowerCamelCase__ ,							lowerCamelCase__    :      Optional[int]					 =		position
        if 0 <= y_test < n and 0 <= x_test < n:
            permissible_positions.append(_UpperCAmelCase )

    return permissible_positions


def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase )			->     bool:
    return not any(elem == 0 for row in board for elem in row )


def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase )			->     bool:

    if is_complete(_UpperCAmelCase ):
        return True

    for position in get_valid_pos(_UpperCAmelCase						,	len(_UpperCAmelCase ) ):
        lowerCamelCase__ ,							lowerCamelCase__    :      Optional[int]					 =		position

        if board[y][x] == 0:
            lowerCamelCase__    :      List[Any]					 =		curr + 1
            if open_knight_tour_helper(_UpperCAmelCase						,	_UpperCAmelCase						,	curr + 1 ):
                return True
            lowerCamelCase__    :      Optional[Any]					 =		0

    return False


def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase )			->     list[list[int]]:
    lowerCamelCase__    :      Any					 =		[[0 for i in range(_UpperCAmelCase )] for j in range(_UpperCAmelCase )]

    for i in range(_UpperCAmelCase ):
        for j in range(_UpperCAmelCase ):
            lowerCamelCase__    :      Optional[int]					 =		1
            if open_knight_tour_helper(_UpperCAmelCase						,	(i, j)						,	1 ):
                return board
            lowerCamelCase__    :      Optional[Any]					 =		0

    lowerCamelCase__    :      Any					 =		F"""Open Kight Tour cannot be performed on a board of size {n}"""
    raise ValueError(_UpperCAmelCase )


if __name__ == "__main__":
    import doctest

    doctest.testmod()





