


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      :
 def __init__(       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__=3    ,			lowerCAmelCase__=32    ,			lowerCAmelCase__=3    ,			lowerCAmelCase__=10    ,			lowerCAmelCase__=[10, 20, 30, 40]    ,			lowerCAmelCase__=[1, 1, 2, 1]    ,			lowerCAmelCase__=True    ,			lowerCAmelCase__=True    ,			lowerCAmelCase__="relu"    ,			lowerCAmelCase__=3    ,			lowerCAmelCase__=None    ,			) ->    List[str]:




        '''simple docstring'''
        lowercase__:       List[Any]        =       parent
        lowercase__:       Dict        =       batch_size
        lowercase__:       Dict        =       image_size
        lowercase__:       Optional[Any]        =       num_channels
        lowercase__:       List[Any]        =       embeddings_size
        lowercase__:       Any        =       hidden_sizes
        lowercase__:       Any        =       depths
        lowercase__:       int        =       is_training
        lowercase__:       Union[str, Any]        =       use_labels
        lowercase__:       Dict        =       hidden_act
        lowercase__:       Optional[Any]        =       num_labels
        lowercase__:       Optional[Any]        =       scope
        lowercase__:       int        =       len(lowerCAmelCase__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Any:




        '''simple docstring'''
        lowercase__:       Optional[Any]        =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

        lowercase__:       Optional[int]        =       None
        if self.use_labels:
               lowercase__:       Optional[Any]        =       ids_tensor([self.batch_size]    ,			self.num_labels			)

        lowercase__:       str        =       self.get_config()

        return config, pixel_values, labels
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Optional[int]:




        '''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 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__			) ->    List[Any]:




        '''simple docstring'''
        lowercase__:       Dict        =       TFResNetModel(config=lowerCAmelCase__			)
        lowercase__:       Optional[Any]        =       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 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__			) ->    List[Any]:




        '''simple docstring'''
        lowercase__:       int        =       self.num_labels
        lowercase__:       Dict        =       TFResNetForImageClassification(lowerCAmelCase__			)
        lowercase__:       Tuple        =       model(lowerCAmelCase__    ,			labels=lowerCAmelCase__			)
        self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels)			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Union[str, Any]:




        '''simple docstring'''
        lowercase__:       Tuple        =       self.prepare_config_and_inputs()
        lowercase__      ,						lowercase__      ,						lowercase__:       Optional[Any]        =       config_and_inputs
        lowercase__:       Optional[Any]        =       {'pixel_values': pixel_values}
        return config, inputs_dict





@require_tf
class   __a      (   __UpperCamelCase	,	__UpperCamelCase	,	unittest.TestCase				):
 __lowercase			:							Dict       					=			(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 __lowercase			:							Optional[Any]       					=			(
     {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 __lowercase			:							Any       					=			False
 __lowercase			:							Optional[Any]       					=			False
 __lowercase			:							Optional[Any]       					=			False
 __lowercase			:							Tuple       					=			False
 __lowercase			:							Optional[int]       					=			False
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Optional[int]:




        '''simple docstring'''
        lowercase__:       int        =       TFResNetModelTester(self			)
        lowercase__:       Optional[int]        =       ConfigTester(self    ,			config_class=lowerCAmelCase__    ,			has_text_modality=lowerCAmelCase__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Dict:




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




        '''simple docstring'''
        return
 @unittest.skip(reason='ResNet does not use inputs_embeds'			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Optional[Any]:




        '''simple docstring'''
        pass
 @unittest.skip(reason='ResNet does not support input and output embeddings'			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Dict:




        '''simple docstring'''
        pass
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Dict:




        '''simple docstring'''
        lowercase__      ,						lowercase__:       Dict        =       self.model_tester.prepare_config_and_inputs_for_common()

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

               lowercase__:       Optional[Any]        =       ['pixel_values']
               self.assertListEqual(arg_names[:1]    ,			lowerCAmelCase__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[Any]:




        '''simple docstring'''
        lowercase__:       List[Any]        =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Dict:




        '''simple docstring'''
        def check_hidden_states_output(lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__			):
               lowercase__:       Dict        =       model_class(lowerCAmelCase__			)
               lowercase__:       Optional[int]        =       model(**self._prepare_for_class(lowerCAmelCase__    ,			lowerCAmelCase__			)			)

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

               lowercase__:       Union[str, Any]        =       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]    ,			)

        lowercase__      ,						lowercase__:       int        =       self.model_tester.prepare_config_and_inputs_for_common()
        lowercase__:       List[Any]        =       ['basic', 'bottleneck']
        for model_class in self.all_model_classes:
               for layer_type in layers_type:
                      lowercase__:       Optional[Any]        =       layer_type
                      lowercase__:       Dict        =       True
                      check_hidden_states_output(lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__			)

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

                      check_hidden_states_output(lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Any:




        '''simple docstring'''
        lowercase__:       Tuple        =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__			)
 @slow
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[Any]:




        '''simple docstring'''
        for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowercase__:       Any        =       TFResNetModel.from_pretrained(lowerCAmelCase__			)
               self.assertIsNotNone(lowerCAmelCase__			)





def        snake_case_					(  )  ->    List[Any]:
       lowercase__:       List[Any]        =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
       return image





@require_tf
@require_vision
class   __a      (   unittest.TestCase				):
 @cached_property
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    int:




        '''simple docstring'''
        return (
            AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)
            if is_vision_available()
            else None
        )
 @slow
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[str]:




        '''simple docstring'''
        lowercase__:       int        =       TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)

        lowercase__:       int        =       self.default_image_processor
        lowercase__:       Any        =       prepare_img()
        lowercase__:       List[str]        =       image_processor(images=lowerCAmelCase__    ,			return_tensors='tf'			)

        # forward pass
        lowercase__:       List[Any]        =       model(**lowerCAmelCase__			)

        # verify the logits
        lowercase__:       Optional[int]        =       tf.TensorShape((1, 1_000)			)
        self.assertEqual(outputs.logits.shape    ,			lowerCAmelCase__			)

        lowercase__:       str        =       tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]			)

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






def        snake_case_					(  snake_case					)  ->    list[int]:
       lowercase__:       Dict        =       [0 for i in range(len(snake_case					)					)]

       # initialize interval's left pointer and right pointer
       lowercase__      ,						lowercase__:       Union[str, Any]        =       0, 0

       for i in range(1      ,							len(snake_case					)					):
              # case when current index is inside the interval
              if i <= right_pointer:
                     lowercase__:       List[Any]        =       min(right_pointer - i + 1      ,							z_result[i - left_pointer]					)
                     lowercase__:       List[str]        =       min_edge

              while go_next(snake_case      ,							snake_case      ,							snake_case					):
                     z_result[i] += 1

              # if new index's result gives us more right interval,
              # we've to update left_pointer and right_pointer
              if i + z_result[i] - 1 > right_pointer:
                     lowercase__      ,						lowercase__:       List[Any]        =       i, i + z_result[i] - 1

       return z_result




def        snake_case_					(  snake_case      ,							snake_case      ,							snake_case					)  ->    bool:
       return i + z_result[i] < len(snake_case					) and s[z_result[i]] == s[i + z_result[i]]




def        snake_case_					(  snake_case      ,							snake_case					)  ->    int:
       lowercase__:       Tuple        =       0
       # concatenate 'pattern' and 'input_str' and call z_function
       # with concatenated string
       lowercase__:       Any        =       z_function(pattern + input_str					)

       for val in z_result:
              # if value is greater then length of the pattern string
              # that means this index is starting position of substring
              # which is equal to pattern string
              if val >= len(snake_case					):
                     answer += 1

       return answer


if __name__ == "__main__":
 import doctest

 doctest.testmod()


