
'''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  __A				:
 def __init__(   self			:    Union[str, Any]				,   lowerCamelCase			:    List[Any]				,   lowerCamelCase			:    Union[str, Any]=3				,   lowerCamelCase			:    List[Any]=32				,   lowerCamelCase			:    Optional[Any]=3				,   lowerCamelCase			:    Tuple=10				,   lowerCamelCase			:    Union[str, Any]=[10, 20, 30, 40]				,   lowerCamelCase			:    List[Any]=[1, 1, 2, 1]				,   lowerCamelCase			:    List[Any]=True				,   lowerCamelCase			:    str=True				,   lowerCamelCase			:    Optional[Any]="relu"				,   lowerCamelCase			:    List[str]=3				,   lowerCamelCase			:    Dict=None				,   ):



   """simple docstring"""





   __A		:     Optional[Any]												=		parent
   __A		:     Any												=		batch_size
   __A		:     int												=		image_size
   __A		:     Any												=		num_channels
   __A		:     Union[str, Any]												=		embeddings_size
   __A		:     int												=		hidden_sizes
   __A		:     str												=		depths
   __A		:     Dict												=		is_training
   __A		:     Optional[Any]												=		use_labels
   __A		:     Optional[int]												=		hidden_act
   __A		:     Union[str, Any]												=		num_labels
   __A		:     str												=		scope
   __A		:     List[str]												=		len(_lowerCAmelCase       )
 def 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





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

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

   __A		:     Optional[Any]												=		self.get_config()

   return config, pixel_values, labels
 def 		lowercase_(   self			:    Optional[Any]       ):



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



   """simple docstring"""





   __A		:     Dict												=		TFResNetModel(config=_lowerCAmelCase       )
   __A		:     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 		lowercase_(   self			:    Dict				,   lowerCamelCase			:    int				,   lowerCamelCase			:    Union[str, Any]				,   lowerCamelCase			:    List[Any]       ):



   """simple docstring"""





   __A		:     Any												=		self.num_labels
   __A		:     int												=		TFResNetForImageClassification(_lowerCAmelCase       )
   __A		:     List[str]												=		model(_lowerCAmelCase				,   labels=_lowerCAmelCase       )
   self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.num_labels)       )






 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   __A		:     List[str]												=		self.prepare_config_and_inputs()
   __A							,					__A							,					__A		:     Optional[int]												=		config_and_inputs
   __A		:     Tuple												=		{"""pixel_values""": pixel_values}
   return config, inputs_dict







@require_tf
class  __A				( _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						unittest.TestCase			):
 lowerCamelCase				       =(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 lowerCamelCase				       =(
     {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 lowerCamelCase				       =False
 lowerCamelCase				       =False
 lowerCamelCase				       =False
 lowerCamelCase				       =False
 lowerCamelCase				       =False
 def 		lowercase_(   self			:    str       ):



   """simple docstring"""





   __A		:     str												=		TFResNetModelTester(self       )
   __A		:     List[str]												=		ConfigTester(self				,   config_class=_lowerCAmelCase				,   has_text_modality=_lowerCAmelCase       )
 def 		lowercase_(   self			:    int       ):



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



   """simple docstring"""





   return
 @unittest.skip(reason="""ResNet does not use inputs_embeds"""       )
 def 		lowercase_(   self			:    Dict       ):



   """simple docstring"""





   pass
 @unittest.skip(reason="""ResNet does not support input and output embeddings"""       )
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   pass
 def 		lowercase_(   self			:    Dict       ):



   """simple docstring"""





   __A							,					__A		:     List[Any]												=		self.model_tester.prepare_config_and_inputs_for_common()

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

     __A		:     List[Any]												=		["""pixel_values"""]
     self.assertListEqual(arg_names[:1]				,   _lowerCAmelCase       )
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   __A		:     List[Any]												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*_lowerCAmelCase       )
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   def check_hidden_states_output(lowerCamelCase			:    List[str]				,   lowerCamelCase			:    Dict				,   lowerCamelCase			:    Dict       ):
     __A		:     Tuple												=		model_class(_lowerCAmelCase       )
     __A		:     Optional[Any]												=		model(**self._prepare_for_class(_lowerCAmelCase				,   _lowerCAmelCase       )       )

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

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

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

       check_hidden_states_output(_lowerCAmelCase				,   _lowerCAmelCase				,   _lowerCAmelCase       )
 def 		lowercase_(   self			:    List[Any]       ):



   """simple docstring"""





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






 @slow
 def 		lowercase_(   self			:    Dict       ):



   """simple docstring"""





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







def        A_     (						)				->       Any:





  """simple docstring"""

  __A		:     Union[str, Any]												=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
  return image







@require_tf
@require_vision
class  __A				( unittest.TestCase			):
 @cached_property
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





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






 @slow
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





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

   __A		:     List[str]												=		self.default_image_processor
   __A		:     Any												=		prepare_img()
   __A		:     str												=		image_processor(images=_lowerCAmelCase				,   return_tensors="""tf"""       )

   # forward pass
   __A		:     Any												=		model(**_lowerCAmelCase       )

   # verify the logits
   __A		:     List[str]												=		tf.TensorShape((1, 10_00)       )
   self.assertEqual(outputs.logits.shape				,   _lowerCAmelCase       )

   __A		:     Tuple												=		tf.constant([-11.1_069, -9.7_877, -8.3_777]       )

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





'''simple docstring'''
from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


A__   :		Dict 		=logging.get_logger(__name__)







class  __A				( _SCREAMING_SNAKE_CASE			):
 lowerCamelCase				       =['''input_values''', '''padding_mask''']
 def __init__(   self			:    Optional[int]				,   lowerCamelCase			:    int = 1				,   lowerCamelCase			:    int = 2_40_00				,   lowerCamelCase			:    float = 0.0				,   lowerCamelCase			:    float = None				,   lowerCamelCase			:    float = None				,   **lowerCamelCase			:    Dict				,   ):



   """simple docstring"""





   super().__init__(feature_size=lowerCamelCase				,   sampling_rate=lowerCamelCase				,   padding_value=lowerCamelCase				,   **lowerCamelCase       )
   __A		:     str												=		chunk_length_s
   __A		:     str												=		overlap
 @property
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   if self.chunk_length_s is None:
     return None
   else:
     return int(self.chunk_length_s * self.sampling_rate       )
 @property
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   if self.chunk_length_s is None or self.overlap is None:
     return None
   else:
     return max(1				,   int((1.0 - self.overlap) * self.chunk_length       )       )






 def __call__(   self			:    List[str]				,   lowerCamelCase			:    Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]				,   lowerCamelCase			:    Optional[Union[bool, str, PaddingStrategy]] = None				,   lowerCamelCase			:    Optional[bool] = False				,   lowerCamelCase			:    Optional[int] = None				,   lowerCamelCase			:    Optional[Union[str, TensorType]] = None				,   lowerCamelCase			:    Optional[int] = None				,   ):



   """simple docstring"""





   if sampling_rate is not None:
     if sampling_rate != self.sampling_rate:
       raise ValueError(
           f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
           f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
           f" {self.sampling_rate} and not {sampling_rate}."       )
   else:
     logger.warning(
         """It is strongly recommended to pass the `sampling_rate` argument to this function. """
         """Failing to do so can result in silent errors that might be hard to debug."""       )

   if padding and truncation:
     raise ValueError("""Both padding and truncation were set. Make sure you only set one."""       )
   elif padding is None:
     # by default let's pad the inputs
     __A		:     List[Any]												=		True

   __A		:     List[str]												=		bool(
       isinstance(lowerCamelCase				,   (list, tuple)       ) and (isinstance(raw_audio[0]				,   (np.ndarray, tuple, list)       ))       )

   if is_batched:
     __A		:     Optional[Any]												=		[np.asarray(lowerCamelCase				,   dtype=np.floataa       ).T for audio in raw_audio]
   elif not is_batched and not isinstance(lowerCamelCase				,   np.ndarray       ):
     __A		:     Union[str, Any]												=		np.asarray(lowerCamelCase				,   dtype=np.floataa       )
   elif isinstance(lowerCamelCase				,   np.ndarray       ) and raw_audio.dtype is np.dtype(np.floataa       ):
     __A		:     Optional[Any]												=		raw_audio.astype(np.floataa       )

   # always return batch
   if not is_batched:
     __A		:     Tuple												=		[np.asarray(lowerCamelCase       ).T]

   # verify inputs are valid
   for idx, example in enumerate(lowerCamelCase       ):
     if example.ndim > 2:
       raise ValueError(f"Expected input shape (channels, length) but got shape {example.shape}"       )
     if self.feature_size == 1 and example.ndim != 1:
       raise ValueError(f"Expected mono audio but example has {example.shape[-1]} channels"       )
     if self.feature_size == 2 and example.shape[-1] != 2:
       raise ValueError(f"Expected stereo audio but example has {example.shape[-1]} channels"       )

   __A		:     Optional[Any]												=		None
   __A		:     Dict												=		BatchFeature({"""input_values""": raw_audio}       )
   if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
     if truncation:
       __A		:     Optional[Any]												=		min(array.shape[0] for array in raw_audio       )
       __A		:     Dict												=		int(np.floor(max_length / self.chunk_stride       )       )
       __A		:     Union[str, Any]												=		(nb_step - 1) * self.chunk_stride + self.chunk_length
     elif padding:
       __A		:     int												=		max(array.shape[0] for array in raw_audio       )
       __A		:     Optional[Any]												=		int(np.ceil(max_length / self.chunk_stride       )       )
       __A		:     Any												=		(nb_step - 1) * self.chunk_stride + self.chunk_length
       __A		:     Optional[int]												=		"""max_length"""
     else:
       __A		:     Optional[Any]												=		input_values

        # normal padding on batch
   if padded_inputs is None:
     __A		:     Tuple												=		self.pad(
         lowerCamelCase				,   max_length=lowerCamelCase				,   truncation=lowerCamelCase				,   padding=lowerCamelCase				,   return_attention_mask=lowerCamelCase				,   )
     if padding:
       __A		:     List[Any]												=		padded_inputs.pop("""attention_mask"""       )

   __A		:     List[Any]												=		[]
   for example in padded_inputs.pop("""input_values"""       ):
     if self.feature_size == 1:
       __A		:     Optional[Any]												=		example[..., None]
     input_values.append(example.T       )

   __A		:     str												=		input_values
   if return_tensors is not None:
     __A		:     Any												=		padded_inputs.convert_to_tensors(lowerCamelCase       )

   return padded_inputs



