



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    lowerCamelCase__  :
     """simple docstring"""



     def __init__(self				,			__a				,			__a=3				,			__a=32				,			__a=3				,			__a=10				,			__a=[10, 20, 30, 40]				,			__a=[1, 1, 2, 1]				,			__a=True				,			__a=True				,			__a="relu"				,			__a=3				,			__a=None				,			):






           '''simple docstring'''



           lowerCamelCase								=		parent
           lowerCamelCase								=		batch_size
           lowerCamelCase								=		image_size
           lowerCamelCase								=		num_channels
           lowerCamelCase								=		embeddings_size
           lowerCamelCase								=		hidden_sizes
           lowerCamelCase								=		depths
           lowerCamelCase								=		is_training
           lowerCamelCase								=		use_labels
           lowerCamelCase								=		hidden_act
           lowerCamelCase								=		num_labels
           lowerCamelCase								=		scope
           lowerCamelCase								=		len(__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

           lowerCamelCase								=		None
           if self.use_labels:
                 lowerCamelCase								=		ids_tensor([self.batch_size]				,			self.num_labels    )

           lowerCamelCase								=		self.get_config()

           return config, pixel_values, labels







     def 						_a      (self    ):






           '''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 						_a      (self				,			__a				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		TFResNetModel(config=__a    )
           lowerCamelCase								=		model(__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 // 32, self.image_size // 32)				,			)







     def 						_a      (self				,			__a				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		self.num_labels
           lowerCamelCase								=		TFResNetForImageClassification(__a    )
           lowerCamelCase								=		model(__a				,			labels=__a    )
           self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.num_labels)    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.prepare_config_and_inputs()
           lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase								=		config_and_inputs
           lowerCamelCase								=		{"pixel_values": pixel_values}
           return config, inputs_dict





@require_tf
class    lowerCamelCase__  (						UpperCAmelCase_       ,    UpperCAmelCase_       ,    unittest.TestCase):
     """simple docstring"""



     _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 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		TFResNetModelTester(self    )
           lowerCamelCase								=		ConfigTester(self				,			config_class=__a				,			has_text_modality=__a    )







     def 						_a      (self    ):






           '''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 						_a      (self    ):






           '''simple docstring'''



           return







     @unittest.skip(reason="ResNet does not use inputs_embeds"    )
     def 						_a      (self    ):






           '''simple docstring'''



           pass







     @unittest.skip(reason="ResNet does not support input and output embeddings"    )
     def 						_a      (self    ):






           '''simple docstring'''



           pass







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase			,							lowerCamelCase								=		self.model_tester.prepare_config_and_inputs_for_common()

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

                 lowerCamelCase								=		["pixel_values"]
                 self.assertListEqual(arg_names[:1]				,			__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           def check_hidden_states_output(__a				,			__a				,			__a    ):
                 lowerCamelCase								=		model_class(__a    )
                 lowerCamelCase								=		model(**self._prepare_for_class(__a				,			__a    )    )

                 lowerCamelCase								=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 lowerCamelCase								=		self.model_tester.num_stages
                 self.assertEqual(len(__a    )				,			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								=		self.model_tester.prepare_config_and_inputs_for_common()
           lowerCamelCase								=		["basic", "bottleneck"]
           for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                       lowerCamelCase								=		layer_type
                       lowerCamelCase								=		True
                       check_hidden_states_output(__a				,			__a				,			__a    )

                       # check that output_hidden_states also work using config
                       del inputs_dict["output_hidden_states"]
                       lowerCamelCase								=		True

                       check_hidden_states_output(__a				,			__a				,			__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__a    )







     @slow
     def 						_a      (self    ):






           '''simple docstring'''



           for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase								=		TFResNetModel.from_pretrained(__a    )
                 self.assertIsNotNone(__a    )



def     __lowercase(	):


      """simple docstring"""



      lowerCamelCase								=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
      return image






@require_tf
@require_vision
class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     @cached_property
     def 						_a      (self    ):






           '''simple docstring'''



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







     @slow
     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

           lowerCamelCase								=		self.default_image_processor
           lowerCamelCase								=		prepare_img()
           lowerCamelCase								=		image_processor(images=__a				,			return_tensors="tf"    )

           # forward pass
           lowerCamelCase								=		model(**__a    )

           # verify the logits
           lowerCamelCase								=		tf.TensorShape((1, 10_00)    )
           self.assertEqual(outputs.logits.shape				,			__a    )

           lowerCamelCase								=		tf.constant([-11.1069, -9.7877, -8.3777]    )

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




import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate

def     __lowercase(	UpperCAmelCase__ ):


      """simple docstring"""



      return x + 2






class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"x = 3"
           lowerCamelCase								=		{}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           assert result == 3
           self.assertDictEqual(__a				,			{"x": 3}    )

           lowerCamelCase								=		"x = y"
           lowerCamelCase								=		{"y": 5}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 5, "y": 5}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"y = add_two(x)"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 3, "y": 5}    )

           # Won't work without the tool
           with CaptureStdout() as out:
                 lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           assert result is None
           assert "tried to execute add_two" in out.out







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"x = 3"
           lowerCamelCase								=		{}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           assert result == 3
           self.assertDictEqual(__a				,			{"x": 3}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"test_dict = {'x': x, 'y': add_two(x)}"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           self.assertDictEqual(__a				,			{"x": 3, "y": 5}    )
           self.assertDictEqual(__a				,			{"x": 3, "test_dict": {"x": 3, "y": 5}}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"x = 3\ny = 5"
           lowerCamelCase								=		{}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 3, "y": 5}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"text = f'This is x: {x}.'"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == "This is x: 3."
           self.assertDictEqual(__a				,			{"x": 3, "text": "This is x: 3."}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"if x <= 3:\n    y = 2\nelse:\n    y = 5"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == 2
           self.assertDictEqual(__a				,			{"x": 3, "y": 2}    )

           lowerCamelCase								=		{"x": 8}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           # evaluate returns the value of the last assignment.
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 8, "y": 5}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"test_list = [x, add_two(x)]"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           self.assertListEqual(__a				,			[3, 5]    )
           self.assertDictEqual(__a				,			{"x": 3, "test_list": [3, 5]}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"y = x"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{}				,			state=__a    )
           assert result == 3
           self.assertDictEqual(__a				,			{"x": 3, "y": 3}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"test_list = [x, add_two(x)]\ntest_list[1]"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 3, "test_list": [3, 5]}    )

           lowerCamelCase								=		"test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
           lowerCamelCase								=		{"x": 3}
           lowerCamelCase								=		evaluate(__a				,			{"add_two": add_two}				,			state=__a    )
           assert result == 5
           self.assertDictEqual(__a				,			{"x": 3, "test_dict": {"x": 3, "y": 5}}    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"x = 0\nfor i in range(3):\n    x = i"
           lowerCamelCase								=		{}
           lowerCamelCase								=		evaluate(__a				,			{"range": range}				,			state=__a    )
           assert result == 2
           self.assertDictEqual(__a				,			{"x": 2, "i": 2}    )