


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




      '''simple docstring'''


      def __init__(    self:	Optional[int]						,				a:	Tuple						,				a:	Optional[Any]=3						,				a:	Tuple=32						,				a:	Any=3						,				a:	Optional[int]=10						,				a:	Any=[10, 20, 30, 40]						,				a:	Union[str, Any]=[1, 1, 2, 1]						,				a:	Tuple=True						,				a:	str=True						,				a:	Union[str, Any]="relu"						,				a:	Optional[int]=3						,				a:	Optional[int]=None						,				):
       __lowerCamelCase		:							List[Any]		 =						parent
       __lowerCamelCase		:							Optional[int]		 =						batch_size
       __lowerCamelCase		:							Optional[int]		 =						image_size
       __lowerCamelCase		:							List[str]		 =						num_channels
       __lowerCamelCase		:							Dict		 =						embeddings_size
       __lowerCamelCase		:							Optional[int]		 =						hidden_sizes
       __lowerCamelCase		:							Optional[Any]		 =						depths
       __lowerCamelCase		:							Tuple		 =						is_training
       __lowerCamelCase		:							Union[str, Any]		 =						use_labels
       __lowerCamelCase		:							int		 =						hidden_act
       __lowerCamelCase		:							Dict		 =						num_labels
       __lowerCamelCase		:							Optional[Any]		 =						scope
       __lowerCamelCase		:							Optional[Any]		 =						len(lowerCamelCase_    )




      def 					_snake_case     (    self:	str    ):
       __lowerCamelCase		:							Optional[int]		 =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

       __lowerCamelCase		:							Union[str, Any]		 =						None
       if self.use_labels:
        __lowerCamelCase		:							Tuple		 =						ids_tensor([self.batch_size]						,				self.num_labels    )

       __lowerCamelCase		:							Union[str, Any]		 =						self.get_config()

       return config, pixel_values, labels




      def 					_snake_case     (    self:	Tuple    ):
       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 					_snake_case     (    self:	Optional[int]						,				a:	Optional[int]						,				a:	Dict						,				a:	Optional[int]    ):
       __lowerCamelCase		:							Any		 =						TFResNetModel(config=lowerCamelCase_    )
       __lowerCamelCase		:							Tuple		 =						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 // 32, self.image_size // 32)						,				)




      def 					_snake_case     (    self:	List[str]						,				a:	Any						,				a:	List[Any]						,				a:	Any    ):
       __lowerCamelCase		:							Optional[int]		 =						self.num_labels
       __lowerCamelCase		:							Dict		 =						TFResNetForImageClassification(lowerCamelCase_    )
       __lowerCamelCase		:							int		 =						model(lowerCamelCase_						,				labels=lowerCamelCase_    )
       self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_labels)    )




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


@require_tf
class 	A_ (	__snake_case ,				__snake_case ,				unittest.TestCase   ):




      '''simple docstring'''


      __snake_case 	=       (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
      __snake_case 	=       (
          {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
          if is_tf_available()
          else {}
      )

      __snake_case 	=       False
      __snake_case 	=       False
      __snake_case 	=       False
      __snake_case 	=       False
      __snake_case 	=       False




      def 					_snake_case     (    self:	int    ):
       __lowerCamelCase		:							int		 =						TFResNetModelTester(self    )
       __lowerCamelCase		:							Dict		 =						ConfigTester(self						,				config_class=lowerCamelCase_						,				has_text_modality=lowerCamelCase_    )




      def 					_snake_case     (    self:	List[Any]    ):
       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 					_snake_case     (    self:	Any    ):
       return




      @unittest.skip(reason='ResNet does not use inputs_embeds'    )
      def 					_snake_case     (    self:	Any    ):
       pass




      @unittest.skip(reason='ResNet does not support input and output embeddings'    )
      def 					_snake_case     (    self:	Optional[int]    ):
       pass




      def 					_snake_case     (    self:	List[Any]    ):
       __lowerCamelCase		:							Tuple		 =						self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCamelCase		:							Any		 =						["""pixel_values"""]
        self.assertListEqual(arg_names[:1]						,				lowerCamelCase_    )




      def 					_snake_case     (    self:	List[Any]    ):
       __lowerCamelCase		:							str		 =						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase_    )




      def 					_snake_case     (    self:	str    ):
       def check_hidden_states_output(a:	Dict						,				a:	Tuple						,				a:	Any    ):
        __lowerCamelCase		:							Any		 =						model_class(lowerCamelCase_    )
        __lowerCamelCase		:							List[Any]		 =						model(**self._prepare_for_class(lowerCamelCase_						,				lowerCamelCase_    )    )

        __lowerCamelCase		:							Any		 =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        __lowerCamelCase		:							Optional[int]		 =						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]						,				)

       __lowerCamelCase		:							Dict		 =						self.model_tester.prepare_config_and_inputs_for_common()
       __lowerCamelCase		:							Any		 =						["""basic""", """bottleneck"""]
       for model_class in self.all_model_classes:
        for layer_type in layers_type:
         __lowerCamelCase		:							Tuple		 =						layer_type
         __lowerCamelCase		:							List[str]		 =						True
         check_hidden_states_output(lowerCamelCase_						,				lowerCamelCase_						,				lowerCamelCase_    )

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

         check_hidden_states_output(lowerCamelCase_						,				lowerCamelCase_						,				lowerCamelCase_    )




      def 					_snake_case     (    self:	str    ):
       __lowerCamelCase		:							Tuple		 =						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_    )




      @slow
      def 					_snake_case     (    self:	Union[str, Any]    ):
       for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCamelCase		:							Dict		 =						TFResNetModel.from_pretrained(lowerCamelCase_    )
        self.assertIsNotNone(lowerCamelCase_    )
def 				UpperCamelCase__					(  ):
 __lowerCamelCase		:							Dict		 =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
 return image



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




      '''simple docstring'''


      @cached_property
      def 					_snake_case     (    self:	int    ):
       return (
           AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )
           if is_vision_available()
           else None
       )




      @slow
      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase		:							Optional[Any]		 =						TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

       __lowerCamelCase		:							Tuple		 =						self.default_image_processor
       __lowerCamelCase		:							List[str]		 =						prepare_img()
       __lowerCamelCase		:							Union[str, Any]		 =						image_processor(images=lowerCamelCase_						,				return_tensors='tf'    )

       # forward pass
       __lowerCamelCase		:							Dict		 =						model(**lowerCamelCase_    )

       # verify the logits
       __lowerCamelCase		:							str		 =						tf.TensorShape((1, 1000)    )
       self.assertEqual(outputs.logits.shape						,				lowerCamelCase_    )

       __lowerCamelCase		:							Union[str, Any]		 =						tf.constant([-11.1069, -9.7_8_7_7, -8.3_7_7_7]    )

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





from math import pow
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	):
 if current_sum == needed_sum:
  # If the sum of the powers is equal to needed_sum, then we have a solution.
  solutions_count += 1
  return current_sum, solutions_count

 __lowerCamelCase		:							Optional[Any]		 =						int(pow(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						)						)
 if current_sum + i_to_n <= needed_sum:
  # If the sum of the powers is less than needed_sum, then continue adding powers.
  current_sum += i_to_n
  __lowerCamelCase ,					__lowerCamelCase		:							Optional[Any]		 =						backtrack(
      SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	current_number + 1      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						)
  current_sum -= i_to_n
 if i_to_n < needed_sum:
  # If the power of i is less than needed_sum, then try with the next power.
  __lowerCamelCase ,					__lowerCamelCase		:							Dict		 =						backtrack(
      SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	current_number + 1      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						)
 return current_sum, solutions_count
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						):
 if not (1 <= needed_sum <= 1_000 and 2 <= power <= 10):
  raise ValueError(
      'Invalid input\n'
      'needed_sum must be between 1 and 1000, power between 2 and 10.'						)

 return backtrack(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	1      ,	0      ,	0						)[1]  # Return the solutions_count


if __name__ == "__main__":
       import doctest

       doctest.testmod()

