


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[Any]				,				lowerCamelCase__			:  Dict				,				lowerCamelCase__			:  str=3				,				lowerCamelCase__			:  Dict=32				,				lowerCamelCase__			:  Dict=3				,				lowerCamelCase__			:  str=10				,				lowerCamelCase__			:  Tuple=[10, 20, 30, 40]				,				lowerCamelCase__			:  Tuple=[1, 1, 2, 1]				,				lowerCamelCase__			:  str=True				,				lowerCamelCase__			:  List[str]=True				,				lowerCamelCase__			:  Tuple="relu"				,				lowerCamelCase__			:  List[str]=3				,				lowerCamelCase__			:  int=None				,				):
        a__	:  Optional[Any]     =   parent
        a__	:  Optional[int]     =   batch_size
        a__	:  Union[str, Any]     =   image_size
        a__	:  Dict     =   num_channels
        a__	:  Any     =   embeddings_size
        a__	:  int     =   hidden_sizes
        a__	:  Optional[int]     =   depths
        a__	:  List[str]     =   is_training
        a__	:  Dict     =   use_labels
        a__	:  int     =   hidden_act
        a__	:  Tuple     =   num_labels
        a__	:  Tuple     =   scope
        a__	:  str     =   len(lowerCamelCase__       )

  def    _UpperCamelCase( self			:  int       ):
        a__	:  Union[str, Any]     =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

        a__	:  Any     =   self.get_config()

        return config, pixel_values, labels

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        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			:  Any				,				lowerCamelCase__			:  Any				,				lowerCamelCase__			:  Union[str, Any]				,				lowerCamelCase__			:  Any       ):
        a__	:  str     =   TFResNetModel(config=lowerCamelCase__       )
        a__	:  Union[str, 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    _UpperCamelCase( self			:  int				,				lowerCamelCase__			:  Union[str, Any]				,				lowerCamelCase__			:  Optional[Any]				,				lowerCamelCase__			:  Optional[int]       ):
        a__	:  List[str]     =   self.num_labels
        a__	:  Any     =   TFResNetForImageClassification(lowerCamelCase__       )
        a__	:  Dict     =   model(lowerCamelCase__				,				labels=lowerCamelCase__       )
        self.parent.assertEqual(result.logits.shape				,				(self.batch_size, self.num_labels)       )

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        a__	:  Any     =   self.prepare_config_and_inputs()
        a__,	a__,	a__	:  Union[str, Any]     =   config_and_inputs
        a__	:  int     =   {"pixel_values": pixel_values}
        return config, inputs_dict




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



  """simple docstring"""



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

  _lowercase									=		False
  _lowercase									=		False
  _lowercase									=		False
  _lowercase									=		False
  _lowercase									=		False

  def    _UpperCamelCase( self			:  Any       ):
        a__	:  Tuple     =   TFResNetModelTester(self       )
        a__	:  Any     =   ConfigTester(self				,				config_class=lowerCamelCase__				,				has_text_modality=lowerCamelCase__       )

  def    _UpperCamelCase( self			:  int       ):
        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			:  Any       ):
        return

  @unittest.skip(reason="ResNet does not use inputs_embeds"       )
  def    _UpperCamelCase( self			:  Optional[Any]       ):
        pass

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

  def    _UpperCamelCase( self			:  Union[str, Any]       ):
        a__,	a__	:  List[str]     =   self.model_tester.prepare_config_and_inputs_for_common()

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

              a__	:  str     =   ["pixel_values"]
              self.assertListEqual(arg_names[:1]				,				lowerCamelCase__       )

  def    _UpperCamelCase( self			:  List[Any]       ):
        a__	:  Dict     =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase__       )

  def    _UpperCamelCase( self			:  int       ):
        def check_hidden_states_output(lowerCamelCase__			:  Any				,				lowerCamelCase__			:  Any				,				lowerCamelCase__			:  str       ):
              a__	:  Optional[int]     =   model_class(lowerCamelCase__       )
              a__	:  Optional[int]     =   model(**self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__       )       )

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

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

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

                    check_hidden_states_output(lowerCamelCase__				,				lowerCamelCase__				,				lowerCamelCase__       )

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        a__	:  List[Any]     =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__       )

  @slow
  def    _UpperCamelCase( self			:  Dict       ):
        for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              a__	:  List[str]     =   TFResNetModel.from_pretrained(lowerCamelCase__       )
              self.assertIsNotNone(lowerCamelCase__       )




def UpperCamelCase_				(				)	->   Tuple:
      a__	:  Any     =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
      return image



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



  """simple docstring"""



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

  @slow
  def    _UpperCamelCase( self			:  Dict       ):
        a__	:  List[str]     =   TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

        a__	:  Union[str, Any]     =   self.default_image_processor
        a__	:  Optional[Any]     =   prepare_img()
        a__	:  Dict     =   image_processor(images=lowerCamelCase__				,				return_tensors="tf"       )

        # forward pass
        a__	:  Optional[int]     =   model(**lowerCamelCase__       )

        # verify the logits
        a__	:  Union[str, Any]     =   tf.TensorShape((1, 1_000)       )
        self.assertEqual(outputs.logits.shape				,				lowerCamelCase__       )

        a__	:  Union[str, Any]     =   tf.constant([-11.1069, -9.7877, -8.3777]       )

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








from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
    import PIL


_UpperCAmelCase							:			Any        =							logging.get_logger(__name__)

class   lowerCAmelCase				(   __UpperCamelCase     ):
 UpperCAmelCase__						=						["""pixel_values"""]
 def __init__( self    : Any     ,	UpperCAmelCase    : bool = True     ,	UpperCAmelCase    : Dict[str, int] = None     ,	UpperCAmelCase    : int = 0.9     ,	UpperCAmelCase    : PILImageResampling = PILImageResampling.BICUBIC     ,	UpperCAmelCase    : bool = True     ,	UpperCAmelCase    : Dict[str, int] = None     ,	UpperCAmelCase    : Union[int, float] = 1 / 255     ,	UpperCAmelCase    : bool = True     ,	UpperCAmelCase    : bool = True     ,	UpperCAmelCase    : Optional[Union[float, List[float]]] = None     ,	UpperCAmelCase    : Optional[Union[float, List[float]]] = None     ,	**UpperCAmelCase    : str     ,	)     ->      None:
     super().__init__(**UpperCAmelCase      )
     lowerCamelCase__       : int   					=						size if size is not None else {'shortest_edge': 224}
     lowerCamelCase__       : Tuple   					=						get_size_dict(UpperCAmelCase     ,	default_to_square=UpperCAmelCase      )
     lowerCamelCase__       : Any   					=						crop_size if crop_size is not None else {'height': 224, 'width': 224}
     lowerCamelCase__       : str   					=						get_size_dict(UpperCAmelCase     ,	param_name='crop_size'      )

     lowerCamelCase__       : Tuple   					=						do_resize
     lowerCamelCase__       : str   					=						size
     lowerCamelCase__       : List[str]   					=						crop_pct
     lowerCamelCase__       : Any   					=						resample
     lowerCamelCase__       : Tuple   					=						do_center_crop
     lowerCamelCase__       : Any   					=						crop_size
     lowerCamelCase__       : Optional[int]   					=						do_rescale
     lowerCamelCase__       : Optional[Any]   					=						rescale_factor
     lowerCamelCase__       : Union[str, Any]   					=						do_normalize
     lowerCamelCase__       : Any   					=						image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
     lowerCamelCase__       : Optional[Any]   					=						image_std if image_std is not None else IMAGENET_DEFAULT_STD
 def 	A_      ( self    : Optional[Any]     ,	UpperCAmelCase    : np.ndarray     ,	UpperCAmelCase    : Dict[str, int]     ,	UpperCAmelCase    : Optional[float] = None     ,	UpperCAmelCase    : PILImageResampling = PILImageResampling.BICUBIC     ,	UpperCAmelCase    : Optional[Union[str, ChannelDimension]] = None     ,	**UpperCAmelCase    : int     ,	)     ->      np.ndarray:
     lowerCamelCase__       : Any   					=						get_size_dict(UpperCAmelCase     ,	default_to_square=UpperCAmelCase      )
     if "shortest_edge" not in size and ("height" not in size or "width" not in size):
         raise ValueError(F"""size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}"""      )
     if crop_pct is not None:
         if "shortest_edge" in size:
             lowerCamelCase__       : List[Any]   					=						int(size['shortest_edge'] / crop_pct      )
         elif "height" in size and "width" in size:
             if size["height"] == size["width"]:
                 lowerCamelCase__       : int   					=						int(size['height'] / crop_pct      )
             else:
                 lowerCamelCase__       : Any   					=						(int(size['height'] / crop_pct      ), int(size['width'] / crop_pct      ))
         else:
             raise ValueError('Invalid size for resize: {}'.format(UpperCAmelCase      )      )

         lowerCamelCase__       : Union[str, Any]   					=						get_resize_output_image_size(UpperCAmelCase     ,	size=UpperCAmelCase     ,	default_to_square=UpperCAmelCase      )
     else:
         if "shortest_edge" in size:
             lowerCamelCase__       : int   					=						get_resize_output_image_size(UpperCAmelCase     ,	size=size['shortest_edge']     ,	default_to_square=UpperCAmelCase      )
         elif "height" in size and "width" in size:
             lowerCamelCase__       : List[Any]   					=						(size['height'], size['width'])
         else:
             raise ValueError('Invalid size for resize: {}'.format(UpperCAmelCase      )      )

     return resize(UpperCAmelCase     ,	size=UpperCAmelCase     ,	resample=UpperCAmelCase     ,	data_format=UpperCAmelCase     ,	**UpperCAmelCase      )
 def 	A_      ( self    : Optional[Any]     ,	UpperCAmelCase    : np.ndarray     ,	UpperCAmelCase    : Dict[str, int]     ,	UpperCAmelCase    : Optional[Union[str, ChannelDimension]] = None     ,	**UpperCAmelCase    : str     ,	)     ->      np.ndarray:
     lowerCamelCase__       : Union[str, Any]   					=						get_size_dict(UpperCAmelCase      )
     if "height" not in size or "width" not in size:
         raise ValueError(F"""size must contain 'height' and 'width' as keys. Got {size.keys()}"""      )
     return center_crop(UpperCAmelCase     ,	size=(size['height'], size['width'])     ,	data_format=UpperCAmelCase     ,	**UpperCAmelCase      )
 def 	A_      ( self    : Union[str, Any]     ,	UpperCAmelCase    : np.ndarray     ,	UpperCAmelCase    : Union[int, float]     ,	UpperCAmelCase    : Optional[Union[str, ChannelDimension]] = None     ,	**UpperCAmelCase    : List[Any]     ,	)     ->      int:
     return rescale(UpperCAmelCase     ,	scale=UpperCAmelCase     ,	data_format=UpperCAmelCase     ,	**UpperCAmelCase      )
 def 	A_      ( self    : Dict     ,	UpperCAmelCase    : np.ndarray     ,	UpperCAmelCase    : Union[float, List[float]]     ,	UpperCAmelCase    : Union[float, List[float]]     ,	UpperCAmelCase    : Optional[Union[str, ChannelDimension]] = None     ,	**UpperCAmelCase    : Dict     ,	)     ->      np.ndarray:
     return normalize(UpperCAmelCase     ,	mean=UpperCAmelCase     ,	std=UpperCAmelCase     ,	data_format=UpperCAmelCase     ,	**UpperCAmelCase      )







 def 	A_      ( self    : str     ,	UpperCAmelCase    : ImageInput     ,	UpperCAmelCase    : bool = None     ,	UpperCAmelCase    : Dict[str, int] = None     ,	UpperCAmelCase    : int = None     ,	UpperCAmelCase    : PILImageResampling = None     ,	UpperCAmelCase    : bool = None     ,	UpperCAmelCase    : Dict[str, int] = None     ,	UpperCAmelCase    : bool = None     ,	UpperCAmelCase    : float = None     ,	UpperCAmelCase    : bool = None     ,	UpperCAmelCase    : Optional[Union[float, List[float]]] = None     ,	UpperCAmelCase    : Optional[Union[float, List[float]]] = None     ,	UpperCAmelCase    : Optional[Union[str, TensorType]] = None     ,	UpperCAmelCase    : ChannelDimension = ChannelDimension.FIRST     ,	**UpperCAmelCase    : Any     ,	)     ->      PIL.Image.Image:
     lowerCamelCase__       : Optional[Any]   					=						do_resize if do_resize is not None else self.do_resize
     lowerCamelCase__       : Any   					=						crop_pct if crop_pct is not None else self.crop_pct
     lowerCamelCase__       : Any   					=						resample if resample is not None else self.resample
     lowerCamelCase__       : Any   					=						do_center_crop if do_center_crop is not None else self.do_center_crop
     lowerCamelCase__       : Optional[int]   					=						do_rescale if do_rescale is not None else self.do_rescale
     lowerCamelCase__       : List[Any]   					=						rescale_factor if rescale_factor is not None else self.rescale_factor
     lowerCamelCase__       : Union[str, Any]   					=						do_normalize if do_normalize is not None else self.do_normalize
     lowerCamelCase__       : Any   					=						image_mean if image_mean is not None else self.image_mean
     lowerCamelCase__       : str   					=						image_std if image_std is not None else self.image_std

     lowerCamelCase__       : Optional[Any]   					=						size if size is not None else self.size
     lowerCamelCase__       : Optional[Any]   					=						get_size_dict(UpperCAmelCase     ,	default_to_square=UpperCAmelCase      )
     lowerCamelCase__       : List[str]   					=						crop_size if crop_size is not None else self.crop_size
     lowerCamelCase__       : int   					=						get_size_dict(UpperCAmelCase     ,	param_name='crop_size'      )

     lowerCamelCase__       : Any   					=						make_list_of_images(UpperCAmelCase      )

     if not valid_images(UpperCAmelCase      ):
         raise ValueError(
             'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
             'torch.Tensor, tf.Tensor or jax.ndarray.'      )

     if do_resize and size is None or resample is None:
         raise ValueError('Size and resample must be specified if do_resize is True.'      )

     if do_center_crop and crop_pct is None:
         raise ValueError('Crop_pct must be specified if do_center_crop is True.'      )

     if do_rescale and rescale_factor is None:
         raise ValueError('Rescale factor must be specified if do_rescale is True.'      )

     if do_normalize and (image_mean is None or image_std is None):
         raise ValueError('Image mean and std must be specified if do_normalize is True.'      )

     # All transformations expect numpy arrays.
     lowerCamelCase__       : Dict   					=						[to_numpy_array(UpperCAmelCase      ) for image in images]

     if do_resize:
         lowerCamelCase__       : Any   					=						[self.resize(image=UpperCAmelCase     ,	size=UpperCAmelCase     ,	crop_pct=UpperCAmelCase     ,	resample=UpperCAmelCase      ) for image in images]

     if do_center_crop:
         lowerCamelCase__       : Optional[Any]   					=						[self.center_crop(image=UpperCAmelCase     ,	size=UpperCAmelCase      ) for image in images]

     if do_rescale:
         lowerCamelCase__       : int   					=						[self.rescale(image=UpperCAmelCase     ,	scale=UpperCAmelCase      ) for image in images]

     if do_normalize:
         lowerCamelCase__       : List[Any]   					=						[self.normalize(image=UpperCAmelCase     ,	mean=UpperCAmelCase     ,	std=UpperCAmelCase      ) for image in images]

     lowerCamelCase__       : Dict   					=						[to_channel_dimension_format(UpperCAmelCase     ,	UpperCAmelCase      ) for image in images]

     lowerCamelCase__       : Dict   					=						{'pixel_values': images}
     return BatchFeature(data=UpperCAmelCase     ,	tensor_type=UpperCAmelCase      )





