

"""simple docstring"""






from typing import Dict, List, Optional, Union

import numpy as np

from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy


_lowerCAmelCase						=		logging.get_logger(__name__)







class 	__UpperCamelCase    (    __A						):

  def __init__(		self    ,_A    ,_A    ,_A    ,**_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    feature_size
      _lowerCAmelCase       :   List[Any]  =    sampling_rate
      _lowerCAmelCase       :   Dict  =    padding_value

      _lowerCAmelCase       :   List[Any]  =    kwargs.pop('padding_side'    ,'right'      )
      _lowerCAmelCase       :   str  =    kwargs.pop('return_attention_mask'    ,_A      )

      super().__init__(**_A      )

  def __lowerCamelCase		(		self    ,_A    ,_A = True    ,_A = None    ,_A = False    ,_A = None    ,_A = None    ,_A = None    ,):
      '''simple docstring'''

      if isinstance(_A    ,(list, tuple)      ) and isinstance(processed_features[0]    ,(dict, BatchFeature)      ):
          _lowerCAmelCase       :   int  =    {
              key: [example[key] for example in processed_features] for key in processed_features[0].keys()
          }

      # The model's main input name, usually `input_values`, has be passed for padding
      if self.model_input_names[0] not in processed_features:
          raise ValueError(
              'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`'
              F""" to this method that includes {self.model_input_names[0]}, but you provided"""
              F""" {list(processed_features.keys()      )}"""      )

      _lowerCAmelCase       :   Union[str, Any]  =    processed_features[self.model_input_names[0]]
      _lowerCAmelCase       :   str  =    (
          return_attention_mask if return_attention_mask is not None else self.return_attention_mask
      )

      if len(_A      ) == 0:
          if return_attention_mask:
              _lowerCAmelCase       :   Optional[Any]  =    []
          return processed_features

      # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
      # and rebuild them afterwards if no return_tensors is specified
      # Note that we lose the specific device the tensor may be on for PyTorch

      _lowerCAmelCase       :   Optional[Any]  =    required_input[0]
      if isinstance(_A    ,(list, tuple)      ):
          # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
          _lowerCAmelCase       :   str  =    0
          while len(required_input[index]      ) == 0:
              index += 1
          if index < len(_A      ):
              _lowerCAmelCase       :   List[Any]  =    required_input[index][0]

      if return_tensors is None:
          if is_tf_tensor(_A      ):
              _lowerCAmelCase       :   List[str]  =    'tf'
          elif is_torch_tensor(_A      ):
              _lowerCAmelCase       :   Tuple  =    'pt'
          elif isinstance(_A    ,(int, float, list, tuple, np.ndarray)      ):
              _lowerCAmelCase       :   str  =    'np'
          else:
              raise ValueError(
                  F"""type of {first_element} unknown: {type(_A      )}. """
                  'Should be one of a python, numpy, pytorch or tensorflow object.'      )

      for key, value in processed_features.items():
          if isinstance(value[0]    ,(int, float)      ):
              _lowerCAmelCase       :   Dict  =    to_numpy(_A      )
          else:
              _lowerCAmelCase       :   str  =    [to_numpy(_A      ) for v in value]

        # Convert padding_strategy in PaddingStrategy
      _lowerCAmelCase       :   List[Any]  =    self._get_padding_strategies(padding=_A    ,max_length=_A      )

      _lowerCAmelCase       :   Union[str, Any]  =    processed_features[self.model_input_names[0]]

      _lowerCAmelCase       :   List[str]  =    len(_A      )
      if not all(len(_A      ) == batch_size for v in processed_features.values()      ):
          raise ValueError('Some items in the output dictionary have a different batch size than others.'      )

      _lowerCAmelCase       :   List[str]  =    []
      for i in range(_A      ):
          _lowerCAmelCase       :   Optional[int]  =    {k: v[i] for k, v in processed_features.items()}
          # truncation
          _lowerCAmelCase       :   Tuple  =    self._truncate(
              _A    ,max_length=_A    ,pad_to_multiple_of=_A    ,truncation=_A    ,)
          truncated_inputs.append(_A      )

      if padding_strategy == PaddingStrategy.LONGEST:
          # make sure that `max_length` cannot be longer than the longest truncated length
          _lowerCAmelCase       :   int  =    max(len(input_slice[self.model_input_names[0]]      ) for input_slice in truncated_inputs      )
          _lowerCAmelCase       :   Optional[Any]  =    PaddingStrategy.MAX_LENGTH

      _lowerCAmelCase       :   List[str]  =    {}
      for i in range(_A      ):
          # padding
          _lowerCAmelCase       :   int  =    self._pad(
              truncated_inputs[i]    ,max_length=_A    ,padding_strategy=_A    ,pad_to_multiple_of=_A    ,return_attention_mask=_A    ,)

          for key, value in outputs.items():
              if key not in batch_outputs:
                  _lowerCAmelCase       :   Optional[int]  =    []
              if value.dtype is np.dtype(np.floataa      ):
                  _lowerCAmelCase       :   Any  =    value.astype(np.floataa      )
              batch_outputs[key].append(_A      )

      return BatchFeature(_A    ,tensor_type=_A      )

  def __lowerCamelCase		(		self    ,_A    ,_A = None    ,_A = PaddingStrategy.DO_NOT_PAD    ,_A = None    ,_A = None    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    processed_features[self.model_input_names[0]]

      if padding_strategy == PaddingStrategy.LONGEST:
          _lowerCAmelCase       :   List[Any]  =    len(_A      )

      if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
          _lowerCAmelCase       :   Optional[Any]  =    ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

      _lowerCAmelCase       :   Dict  =    padding_strategy != PaddingStrategy.DO_NOT_PAD and len(_A      ) < max_length

      if return_attention_mask and "attention_mask" not in processed_features:
          _lowerCAmelCase       :   List[Any]  =    np.ones(len(_A      )    ,dtype=np.intaa      )

      if needs_to_be_padded:
          _lowerCAmelCase       :   int  =    max_length - len(_A      )
          if self.padding_side == "right":
              if return_attention_mask:
                  _lowerCAmelCase       :   Union[str, Any]  =    np.pad(
                      processed_features['attention_mask']    ,(0, difference)      )
              _lowerCAmelCase       :   int  =    ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
              _lowerCAmelCase       :   str  =    np.pad(
                  _A    ,_A    ,'constant'    ,constant_values=self.padding_value      )
          elif self.padding_side == "left":
              if return_attention_mask:
                  _lowerCAmelCase       :   Any  =    np.pad(
                      processed_features['attention_mask']    ,(difference, 0)      )
              _lowerCAmelCase       :   List[str]  =    ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
              _lowerCAmelCase       :   Union[str, Any]  =    np.pad(
                  _A    ,_A    ,'constant'    ,constant_values=self.padding_value      )
          else:
              raise ValueError('Invalid padding strategy:' + str(self.padding_side      )      )

      return processed_features

  def __lowerCamelCase		(		self    ,_A    ,_A = None    ,_A = None    ,_A = None    ,):
      '''simple docstring'''

      if not truncation:
          return processed_features
      elif truncation and max_length is None:
          raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.'      )

      _lowerCAmelCase       :   Any  =    processed_features[self.model_input_names[0]]

      # find `max_length` that fits `pad_to_multiple_of`
      if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
          _lowerCAmelCase       :   int  =    ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

      _lowerCAmelCase       :   Optional[int]  =    len(_A      ) > max_length

      if needs_to_be_truncated:
          _lowerCAmelCase       :   str  =    processed_features[self.model_input_names[0]][:max_length]
          if "attention_mask" in processed_features:
              _lowerCAmelCase       :   Dict  =    processed_features['attention_mask'][:max_length]

      return processed_features







  def __lowerCamelCase		(		self    ,_A=False    ,_A=None      ):
      '''simple docstring'''

      if padding is not False:
          if padding is True:
              _lowerCAmelCase       :   Union[str, Any]  =    PaddingStrategy.LONGEST  # Default to pad to the longest sequence in the batch
          elif not isinstance(_A    ,_A      ):
              _lowerCAmelCase       :   Optional[int]  =    PaddingStrategy(_A      )
          elif isinstance(_A    ,_A      ):
              _lowerCAmelCase       :   str  =    padding
      else:
          _lowerCAmelCase       :   str  =    PaddingStrategy.DO_NOT_PAD

      # Set max length if needed
      if max_length is None:
          if padding_strategy == PaddingStrategy.MAX_LENGTH:
              raise ValueError(
                  F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined"""      )

        # Test if we have a padding value
      if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
          raise ValueError(
              'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use'
              ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.'      )

      return padding_strategy








"""simple docstring"""






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 	__UpperCamelCase    :

  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       :   Union[str, Any]  =    parent
      _lowerCAmelCase       :   int  =    batch_size
      _lowerCAmelCase       :   int  =    image_size
      _lowerCAmelCase       :   List[str]  =    num_channels
      _lowerCAmelCase       :   Optional[int]  =    embeddings_size
      _lowerCAmelCase       :   Optional[int]  =    hidden_sizes
      _lowerCAmelCase       :   str  =    depths
      _lowerCAmelCase       :   str  =    is_training
      _lowerCAmelCase       :   int  =    use_labels
      _lowerCAmelCase       :   Optional[int]  =    hidden_act
      _lowerCAmelCase       :   Optional[int]  =    num_labels
      _lowerCAmelCase       :   Dict  =    scope
      _lowerCAmelCase       :   Union[str, Any]  =    len(_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

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

      _lowerCAmelCase       :   Union[str, Any]  =    self.get_config()

      return config, pixel_values, labels

  def __lowerCamelCase		(		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 __lowerCamelCase		(		self    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    TFResNetModel(config=_A      )
      _lowerCAmelCase       :   List[str]  =    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 __lowerCamelCase		(		self    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    self.num_labels
      _lowerCAmelCase       :   Dict  =    TFResNetForImageClassification(_A      )
      _lowerCAmelCase       :   int  =    model(_A    ,labels=_A      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)      )







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.prepare_config_and_inputs()
      _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   Tuple  =    config_and_inputs
      _lowerCAmelCase       :   Any  =    {'pixel_values': pixel_values}
      return config, inputs_dict







@require_tf
class 	__UpperCamelCase    (    a__							,							a__							,							unittest.TestCase						):
  _UpperCAmelCase          =		(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
  _UpperCAmelCase          =		(
      {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
      if is_tf_available()
      else {}
  )

  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    TFResNetModelTester(self      )
      _lowerCAmelCase       :   List[str]  =    ConfigTester(self    ,config_class=_A    ,has_text_modality=_A      )

  def __lowerCamelCase		(		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 __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return

  @unittest.skip(reason='ResNet does not use inputs_embeds'      )
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      pass

  @unittest.skip(reason='ResNet does not support input and output embeddings'      )
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      pass

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase,					_lowerCAmelCase       :   Optional[int]  =    self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          _lowerCAmelCase       :   int  =    model_class(_A      )
          _lowerCAmelCase       :   Union[str, Any]  =    inspect.signature(model.call      )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          _lowerCAmelCase       :   Any  =    [*signature.parameters.keys()]

          _lowerCAmelCase       :   str  =    ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      def check_hidden_states_output(_A    ,_A    ,_A      ):
          _lowerCAmelCase       :   int  =    model_class(_A      )
          _lowerCAmelCase       :   int  =    model(**self._prepare_for_class(_A    ,_A      )      )

          _lowerCAmelCase       :   Dict  =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

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

              check_hidden_states_output(_A    ,_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_A      )







  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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





def 		lowerCamelCase__		(					):

    '''simple docstring'''



    _lowerCAmelCase       :   Tuple  =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
    return image







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

  @cached_property
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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







  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

      _lowerCAmelCase       :   Tuple  =    self.default_image_processor
      _lowerCAmelCase       :   Optional[Any]  =    prepare_img()
      _lowerCAmelCase       :   int  =    image_processor(images=_A    ,return_tensors='tf'      )

      # forward pass
      _lowerCAmelCase       :   int  =    model(**_A      )

      # verify the logits
      _lowerCAmelCase       :   Optional[Any]  =    tf.TensorShape((1, 1000)      )
      self.assertEqual(outputs.logits.shape    ,_A      )

      _lowerCAmelCase       :   Any  =    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()    ,_A    ,atol=1E-4      )      )





