


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:
       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, )			->  int:




           """simple docstring"""

           _lowercase			:				Dict 						=						parent
           _lowercase			:				Union[str, Any] 						=						batch_size
           _lowercase			:				Union[str, Any] 						=						image_size
           _lowercase			:				int 						=						num_channels
           _lowercase			:				Tuple 						=						embeddings_size
           _lowercase			:				List[str] 						=						hidden_sizes
           _lowercase			:				Union[str, Any] 						=						depths
           _lowercase			:				List[Any] 						=						is_training
           _lowercase			:				Optional[Any] 						=						use_labels
           _lowercase			:				int 						=						hidden_act
           _lowercase			:				Optional[Any] 						=						num_labels
           _lowercase			:				str 						=						scope
           _lowercase			:				str 						=						len(__lowerCamelCase)
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

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

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

           _lowercase			:				Dict 						=						self.get_config()

           return config, pixel_values, labels
       def      UpperCamelCase	(   self)			->  List[str]:




           """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, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Tuple:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						TFResNetModel(config=__lowerCamelCase)
           _lowercase			:				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 // 32, self.image_size // 32), )
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						self.num_labels
           _lowercase			:				List[Any] 						=						TFResNetForImageClassification(__lowerCamelCase)
           _lowercase			:				Optional[int] 						=						model(__lowerCamelCase, labels=__lowerCamelCase)
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))




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




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.prepare_config_and_inputs()
           _lowercase						,							_lowercase						,							_lowercase			:				List[Any] 						=						config_and_inputs
           _lowercase			:				str 						=						{'pixel_values': pixel_values}
           return config, inputs_dict






@require_tf
class _lowerCamelCase(		__snake_case,					__snake_case,					unittest.TestCase  ):
       lowercase_					:      Any       					=     (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[int]       					=     False
       lowercase_					:      List[Any]       					=     False
       lowercase_					:      Tuple       					=     False
       lowercase_					:      Any       					=     False
       def      UpperCamelCase	(   self)			->  Dict:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						TFResNetModelTester(self)
           _lowercase			:				str 						=						ConfigTester(self, config_class=__lowerCamelCase, has_text_modality=__lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Optional[Any]:




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




           """simple docstring"""

           return
       @unittest.skip(reason='ResNet does not use inputs_embeds')
       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           pass
       @unittest.skip(reason='ResNet does not support input and output embeddings')
       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           pass
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase						,							_lowercase			:				int 						=						self.model_tester.prepare_config_and_inputs_for_common()

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

               _lowercase			:				str 						=						['pixel_values']
               self.assertListEqual(arg_names[:1], __lowerCamelCase)
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           def check_hidden_states_output(lowerCamelCase, lowerCamelCase, lowerCamelCase):
               _lowercase			:				List[Any] 						=						model_class(__lowerCamelCase)
               _lowercase			:				Optional[int] 						=						model(**self._prepare_for_class(__lowerCamelCase, __lowerCamelCase))

               _lowercase			:				List[Any] 						=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               _lowercase			:				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], )

           _lowercase						,							_lowercase			:				Optional[int] 						=						self.model_tester.prepare_config_and_inputs_for_common()
           _lowercase			:				Union[str, Any] 						=						['basic', 'bottleneck']
           for model_class in self.all_model_classes:
               for layer_type in layers_type:
                   _lowercase			:				Any 						=						layer_type
                   _lowercase			:				Any 						=						True
                   check_hidden_states_output(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase)

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

                   check_hidden_states_output(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase)




       @slow
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase			:				Tuple 						=						TFResNetModel.from_pretrained(__lowerCamelCase)
               self.assertIsNotNone(__lowerCamelCase)



def 							UpperCamelCase_( )       ->		Optional[int]:
    _lowercase			:				Tuple 						=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
    return image






@require_tf
@require_vision
class _lowerCamelCase(		unittest.TestCase  ):
       @cached_property
       def      UpperCamelCase	(   self)			->  List[Any]:




           """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]:




           """simple docstring"""

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

           _lowercase			:				Dict 						=						self.default_image_processor
           _lowercase			:				Optional[Any] 						=						prepare_img()
           _lowercase			:				List[str] 						=						image_processor(images=__lowerCamelCase, return_tensors='tf')

           # forward pass
           _lowercase			:				Union[str, Any] 						=						model(**__lowerCamelCase)

           # verify the logits
           _lowercase			:				Tuple 						=						tf.TensorShape((1, 10_00))
           self.assertEqual(outputs.logits.shape, __lowerCamelCase)

           _lowercase			:				Dict 						=						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))





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__A			:					Dict						=			{
    'configuration_bigbird_pegasus': [
        'BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'BigBirdPegasusConfig',
        'BigBirdPegasusOnnxConfig',
    ],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __A			:					int						=			[
        'BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST',
        'BigBirdPegasusForCausalLM',
        'BigBirdPegasusForConditionalGeneration',
        'BigBirdPegasusForQuestionAnswering',
        'BigBirdPegasusForSequenceClassification',
        'BigBirdPegasusModel',
        'BigBirdPegasusPreTrainedModel',
    ]


if TYPE_CHECKING:
    from .configuration_bigbird_pegasus import (
        BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP,
        BigBirdPegasusConfig,
        BigBirdPegasusOnnxConfig,
    )

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_bigbird_pegasus import (
            BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST,
            BigBirdPegasusForCausalLM,
            BigBirdPegasusForConditionalGeneration,
            BigBirdPegasusForQuestionAnswering,
            BigBirdPegasusForSequenceClassification,
            BigBirdPegasusModel,
            BigBirdPegasusPreTrainedModel,
        )


else:
    import sys

    __A			:					List[Any]						=			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)