





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        snake_case_    :






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






   '''simple docstring'''

   __lowerCAmelCase					:	List[str]      =       parent
   __lowerCAmelCase					:	Any      =       batch_size
   __lowerCAmelCase					:	str      =       image_size
   __lowerCAmelCase					:	int      =       num_channels
   __lowerCAmelCase					:	Tuple      =       embeddings_size
   __lowerCAmelCase					:	Optional[Any]      =       hidden_sizes
   __lowerCAmelCase					:	List[Any]      =       depths
   __lowerCAmelCase					:	List[Any]      =       is_training
   __lowerCAmelCase					:	List[str]      =       use_labels
   __lowerCAmelCase					:	int      =       hidden_act
   __lowerCAmelCase					:	Tuple      =       num_labels
   __lowerCAmelCase					:	Optional[Any]      =       scope
   __lowerCAmelCase					:	Optional[int]      =       len(_snake_case      )






  def 				UpperCAmelCase__						(							self			:					List[Any]      )->int:






   '''simple docstring'''

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

   __lowerCAmelCase					:	Dict      =       None
   if self.use_labels:
    __lowerCAmelCase					:	str      =       ids_tensor([self.batch_size]       ,  self.num_labels      )

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

   return config, pixel_values, labels






  def 				UpperCAmelCase__						(							self			:					Optional[Any]      )->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 				UpperCAmelCase__						(							self			:					Union[str, Any]       ,  _snake_case			:					str       ,  _snake_case			:					Optional[Any]       ,  _snake_case			:					Any      )->int:






   '''simple docstring'''

   __lowerCAmelCase					:	int      =       TFResNetModel(config=_snake_case      )
   __lowerCAmelCase					:	List[Any]      =       model(_snake_case      )
   # 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 // 32, self.image_size // 32)       ,  )






  def 				UpperCAmelCase__						(							self			:					Any       ,  _snake_case			:					Optional[int]       ,  _snake_case			:					Optional[int]       ,  _snake_case			:					int      )->Union[str, Any]:






   '''simple docstring'''

   __lowerCAmelCase					:	int      =       self.num_labels
   __lowerCAmelCase					:	List[str]      =       TFResNetForImageClassification(_snake_case      )
   __lowerCAmelCase					:	int      =       model(_snake_case       ,  labels=_snake_case      )
   self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)      )






  def 				UpperCAmelCase__						(							self			:					Any      )->Any:






   '''simple docstring'''

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






@require_tf
class        snake_case_    (		__lowercase					,__lowercase					,unittest.TestCase						):
  A_      							=   (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
  A_      							=   (
      {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
      if is_tf_available()
      else {}
  )

  A_      							=   False
  A_      							=   False
  A_      							=   False
  A_      							=   False
  A_      							=   False






  def 				UpperCAmelCase__						(							self			:					str      )->int:






   '''simple docstring'''

   __lowerCAmelCase					:	List[str]      =       TFResNetModelTester(self      )
   __lowerCAmelCase					:	Optional[Any]      =       ConfigTester(self       ,  config_class=_snake_case       ,  has_text_modality=_snake_case      )






  def 				UpperCAmelCase__						(							self			:					str      )->Optional[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 				UpperCAmelCase__						(							self			:					Dict      )->List[Any]:






   '''simple docstring'''

   return






  @unittest.skip(reason="""ResNet does not use inputs_embeds"""      )
  def 				UpperCAmelCase__						(							self			:					Any      )->Dict:






   '''simple docstring'''

   pass






  @unittest.skip(reason="""ResNet does not support input and output embeddings"""      )
  def 				UpperCAmelCase__						(							self			:					Tuple      )->Optional[int]:






   '''simple docstring'''

   pass






  def 				UpperCAmelCase__						(							self			:					Optional[Any]      )->List[Any]:






   '''simple docstring'''

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

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

    __lowerCAmelCase					:	Optional[int]      =       ["""pixel_values"""]
    self.assertListEqual(arg_names[:1]       ,  _snake_case      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	Any      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*_snake_case      )






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






   '''simple docstring'''

   def check_hidden_states_output(_snake_case			:					str       ,  _snake_case			:					Any       ,  _snake_case			:					Any      ):
    __lowerCAmelCase					:	Any      =       model_class(_snake_case      )
    __lowerCAmelCase					:	Optional[Any]      =       model(**self._prepare_for_class(_snake_case       ,  _snake_case      )      )

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

    __lowerCAmelCase					:	Union[str, Any]      =       self.model_tester.num_stages
    self.assertEqual(len(_snake_case      )       ,  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]       ,  )

   __lowerCAmelCase ,					__lowerCAmelCase					:	Any      =       self.model_tester.prepare_config_and_inputs_for_common()
   __lowerCAmelCase					:	Dict      =       ["""basic""", """bottleneck"""]
   for model_class in self.all_model_classes:
    for layer_type in layers_type:
     __lowerCAmelCase					:	Optional[Any]      =       layer_type
     __lowerCAmelCase					:	Dict      =       True
     check_hidden_states_output(_snake_case       ,  _snake_case       ,  _snake_case      )

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

     check_hidden_states_output(_snake_case       ,  _snake_case       ,  _snake_case      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	List[Any]      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*_snake_case      )






  @slow
  def 				UpperCAmelCase__						(							self			:					Tuple      )->List[str]:






   '''simple docstring'''

   for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __lowerCAmelCase					:	Any      =       TFResNetModel.from_pretrained(_snake_case      )
    self.assertIsNotNone(_snake_case      )






def 	_SCREAMING_SNAKE_CASE		(      )      ->   Optional[Any]:
 __lowerCAmelCase					:	str      =       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			:					Union[str, Any]      )->Tuple:






   '''simple docstring'''

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






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






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

   __lowerCAmelCase					:	Optional[Any]      =       self.default_image_processor
   __lowerCAmelCase					:	str      =       prepare_img()
   __lowerCAmelCase					:	List[str]      =       image_processor(images=_snake_case       ,  return_tensors="""tf"""      )

   # forward pass
   __lowerCAmelCase					:	List[str]      =       model(**_snake_case      )

   # verify the logits
   __lowerCAmelCase					:	Dict      =       tf.TensorShape((1, 1000)      )
   self.assertEqual(outputs.logits.shape       ,  _snake_case      )

   __lowerCAmelCase					:	Dict      =       tf.constant([-11.1_069, -9.7_877, -8.3_777]      )

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






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:list   )      ->   Dict:
 _enforce_args(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 if n == 0:
  return 0
 __lowerCAmelCase					:	Union[str, Any]      =       float("""-inf"""   )
 for i in range(1   ,   n + 1   ):
  __lowerCAmelCase					:	Union[str, Any]      =       max(
      SCREAMING_SNAKE_CASE   ,   prices[i - 1] + naive_cut_rod_recursive(n - i   ,   SCREAMING_SNAKE_CASE   )   )

 return max_revue






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:list   )      ->   List[str]:
 _enforce_args(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase					:	List[str]      =       [float("""-inf"""   ) for _ in range(n + 1   )]
 return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:list   ,   SCREAMING_SNAKE_CASE		:list   )      ->   List[str]:
 if max_rev[n] >= 0:
  return max_rev[n]
 elif n == 0:
  return 0
 else:
  __lowerCAmelCase					:	str      =       float("""-inf"""   )
  for i in range(1   ,   n + 1   ):
   __lowerCAmelCase					:	List[Any]      =       max(
       SCREAMING_SNAKE_CASE   ,   prices[i - 1] + _top_down_cut_rod_recursive(n - i   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )   ,   )

  __lowerCAmelCase					:	List[str]      =       max_revenue

 return max_rev[n]






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:list   )      ->   Union[str, Any]:
 _enforce_args(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

 # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
 # length 0.
 __lowerCAmelCase					:	Optional[int]      =       [float("""-inf"""   ) for _ in range(n + 1   )]
 __lowerCAmelCase					:	List[str]      =       0

 for i in range(1   ,   n + 1   ):
  __lowerCAmelCase					:	Optional[Any]      =       max_rev[i]
  for j in range(1   ,   i + 1   ):
   __lowerCAmelCase					:	Optional[int]      =       max(SCREAMING_SNAKE_CASE   ,   prices[j - 1] + max_rev[i - j]   )

  __lowerCAmelCase					:	Optional[int]      =       max_revenue_i

 return max_rev[n]






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:list   )      ->   List[Any]:
 if n < 0:
  __lowerCAmelCase					:	Any      =       F'''n must be greater than or equal to 0. Got n = {n}'''
  raise ValueError(SCREAMING_SNAKE_CASE   )

 if n > len(SCREAMING_SNAKE_CASE   ):
  __lowerCAmelCase					:	Any      =       (
      """Each integral piece of rod must have a corresponding price. """
      F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE   )}'''
  )
  raise ValueError(SCREAMING_SNAKE_CASE   )






def 	_SCREAMING_SNAKE_CASE		(      )      ->   Optional[int]:
 __lowerCAmelCase					:	Tuple      =       [6, 10, 12, 15, 20, 23]
 __lowerCAmelCase					:	List[str]      =       len(SCREAMING_SNAKE_CASE   )

 # the best revenue comes from cutting the rod into 6 pieces, each
 # of length 1 resulting in a revenue of 6 * 6 = 36.
 __lowerCAmelCase					:	Union[str, Any]      =       36

 __lowerCAmelCase					:	Optional[int]      =       top_down_cut_rod(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase					:	List[str]      =       bottom_up_cut_rod(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase					:	int      =       naive_cut_rod_recursive(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

 assert expected_max_revenue == max_rev_top_down
 assert max_rev_top_down == max_rev_bottom_up
 assert max_rev_bottom_up == max_rev_naive


if __name__ == "__main__":
      main()