





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 ,  lowercase ,  lowercase=3 ,  lowercase=32 ,  lowercase=3 ,  lowercase=10 ,  lowercase=[10, 20, 30, 40] ,  lowercase=[1, 1, 2, 1] ,  lowercase=True ,  lowercase=True ,  lowercase="relu" ,  lowercase=3 ,  lowercase=None ,  )      ->						Optional[Any]:







          '''simple docstring'''

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

   def 							__lowercase		( self)      ->						List[str]:







          '''simple docstring'''

          a__						:     Dict			=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          a__						:     int			=    self.get_config()

          return config, pixel_values, labels

   def 							__lowercase		( self)      ->						Tuple:







          '''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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						List[str]:







          '''simple docstring'''

          a__						:     Any			=    TFResNetModel(config=_snake_case)
          a__						:     Tuple			=    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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Optional[Any]			=    self.num_labels
          a__						:     int			=    TFResNetForImageClassification(_snake_case)
          a__						:     Dict			=    model(_snake_case ,  labels=_snake_case)
          self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.num_labels))

   def 							__lowercase		( self)      ->						Optional[int]:







          '''simple docstring'''

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





@require_tf
class 			A__   (							__UpperCAmelCase			,  __UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



   __A       :    List[Any]	  =  (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
   __A       :    str	  =  (
       {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
       if is_tf_available()
       else {}
   )

   __A       :    List[str]	  =  False
   __A       :    Tuple	  =  False
   __A       :    Any	  =  False
   __A       :    Dict	  =  False
   __A       :    Optional[Any]	  =  False

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







          '''simple docstring'''

          a__						:     Optional[int]			=    TFResNetModelTester(self)
          a__						:     str			=    ConfigTester(self ,  config_class=_snake_case ,  has_text_modality=_snake_case)

   def 							__lowercase		( 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 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          return

   @unittest.skip(reason='ResNet does not use inputs_embeds')
   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          pass

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







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          a__			,							a__						:     Tuple			=    self.model_tester.prepare_config_and_inputs_for_common()

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

                 a__						:     List[str]			=    ['pixel_values']
                 self.assertListEqual(arg_names[:1] ,  _snake_case)

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Dict			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_snake_case)

   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

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

                 a__						:     str			=    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 a__						:     Dict			=    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] ,  )

          a__			,							a__						:     Dict			=    self.model_tester.prepare_config_and_inputs_for_common()
          a__						:     Optional[int]			=    ['basic', 'bottleneck']
          for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                        a__						:     str			=    layer_type
                        a__						:     List[str]			=    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"]
                        a__						:     Tuple			=    True

                        check_hidden_states_output(_snake_case ,  _snake_case ,  _snake_case)

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     List[str]			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_snake_case)

   @slow
   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

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



def A_     (		)  ->		Union[str, Any]:
       a__						:     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 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

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

   @slow
   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     Tuple			=    TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

          a__						:     List[str]			=    self.default_image_processor
          a__						:     Optional[int]			=    prepare_img()
          a__						:     str			=    image_processor(images=_snake_case ,  return_tensors='tf')

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

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

          a__						:     Optional[int]			=    tf.constant([-11.10_69, -9.78_77, -8.37_77])

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









from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


lowercase				:	List[str]      						=  {
    """configuration_clip""": [
        """CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """CLIPConfig""",
        """CLIPOnnxConfig""",
        """CLIPTextConfig""",
        """CLIPVisionConfig""",
    ],
    """processing_clip""": ["""CLIPProcessor"""],
    """tokenization_clip""": ["""CLIPTokenizer"""],
}

try:
    if not is_tokenizers_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowercase				:	Tuple      						=  ["""CLIPTokenizerFast"""]

try:
    if not is_vision_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowercase				:	Optional[int]      						=  ["""CLIPFeatureExtractor"""]
    lowercase				:	Union[str, Any]      						=  ["""CLIPImageProcessor"""]

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowercase				:	Dict      						=  [
        """CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """CLIPModel""",
        """CLIPPreTrainedModel""",
        """CLIPTextModel""",
        """CLIPTextModelWithProjection""",
        """CLIPVisionModel""",
        """CLIPVisionModelWithProjection""",
    ]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowercase				:	List[str]      						=  [
        """TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """TFCLIPModel""",
        """TFCLIPPreTrainedModel""",
        """TFCLIPTextModel""",
        """TFCLIPVisionModel""",
    ]

try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowercase				:	Any      						=  [
        """FlaxCLIPModel""",
        """FlaxCLIPPreTrainedModel""",
        """FlaxCLIPTextModel""",
        """FlaxCLIPTextPreTrainedModel""",
        """FlaxCLIPVisionModel""",
        """FlaxCLIPVisionPreTrainedModel""",
    ]


if TYPE_CHECKING:
    from .configuration_clip import (
        CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
        CLIPConfig,
        CLIPOnnxConfig,
        CLIPTextConfig,
        CLIPVisionConfig,
    )
    from .processing_clip import CLIPProcessor
    from .tokenization_clip import CLIPTokenizer

    try:
        if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_clip_fast import CLIPTokenizerFast

    try:
        if not is_vision_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .feature_extraction_clip import CLIPFeatureExtractor
        from .image_processing_clip import CLIPImageProcessor

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_clip import (
            CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
            CLIPModel,
            CLIPPreTrainedModel,
            CLIPTextModel,
            CLIPTextModelWithProjection,
            CLIPVisionModel,
            CLIPVisionModelWithProjection,
        )

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_clip import (
            TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
            TFCLIPModel,
            TFCLIPPreTrainedModel,
            TFCLIPTextModel,
            TFCLIPVisionModel,
        )

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_clip import (
            FlaxCLIPModel,
            FlaxCLIPPreTrainedModel,
            FlaxCLIPTextModel,
            FlaxCLIPTextPreTrainedModel,
            FlaxCLIPVisionModel,
            FlaxCLIPVisionPreTrainedModel,
        )


else:
    import sys

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


