

'''simple docstring'''
import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch
     from torch import nn

     from transformers import RegNetForImageClassification, RegNetModel
     from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor







class 							A__    :





  def __init__(		self      :	int							,					_a      :	Optional[int]							,					_a      :	Any=3							,					_a      :	Optional[Any]=32							,					_a      :	Union[str, Any]=3							,					_a      :	Dict=10							,					_a      :	Optional[Any]=[10, 20, 30, 40]							,					_a      :	List[Any]=[1, 1, 2, 1]							,					_a      :	Union[str, Any]=True							,					_a      :	Dict=True							,					_a      :	Any="relu"							,					_a      :	int=3							,					_a      :	Optional[int]=None							,					)	->    Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =parent
       _SCREAMING_SNAKE_CASE							    =batch_size
       _SCREAMING_SNAKE_CASE							    =image_size
       _SCREAMING_SNAKE_CASE							    =num_channels
       _SCREAMING_SNAKE_CASE							    =embeddings_size
       _SCREAMING_SNAKE_CASE							    =hidden_sizes
       _SCREAMING_SNAKE_CASE							    =depths
       _SCREAMING_SNAKE_CASE							    =is_training
       _SCREAMING_SNAKE_CASE							    =use_labels
       _SCREAMING_SNAKE_CASE							    =hidden_act
       _SCREAMING_SNAKE_CASE							    =num_labels
       _SCREAMING_SNAKE_CASE							    =scope
       _SCREAMING_SNAKE_CASE							    =len(_a )





  def 						A  (		self      :	Any )	->    int:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

       _SCREAMING_SNAKE_CASE							    =None
       if self.use_labels:
            _SCREAMING_SNAKE_CASE							    =ids_tensor([self.batch_size]							,					self.num_labels )

       _SCREAMING_SNAKE_CASE							    =self.get_config()

       return config, pixel_values, labels





  def 						A  (		self      :	List[str] )	->    Optional[int]:





       '''simple docstring'''






       return RegNetConfig(
           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							,					)





  def 						A  (		self      :	Optional[Any]							,					_a      :	str							,					_a      :	List[str]							,					_a      :	List[str] )	->    List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =RegNetModel(config=_a )
       model.to(_a )
       model.eval()
       _SCREAMING_SNAKE_CASE							    =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 						A  (		self      :	int							,					_a      :	List[Any]							,					_a      :	Any							,					_a      :	Optional[Any] )	->    List[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.num_labels
       _SCREAMING_SNAKE_CASE							    =RegNetForImageClassification(_a )
       model.to(_a )
       model.eval()
       _SCREAMING_SNAKE_CASE							    =model(_a							,					labels=_a )
       self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.num_labels) )





  def 						A  (		self      :	Optional[Any] )	->    Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.prepare_config_and_inputs()
       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =config_and_inputs
       _SCREAMING_SNAKE_CASE							    ={'pixel_values': pixel_values}
       return config, inputs_dict







@require_torch
class 							A__    (       A__     ,   A__     ,   unittest.TestCase  ):
  A__		 =				(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
  A__		 =				(
      {'feature-extraction': RegNetModel, 'image-classification': RegNetForImageClassification}
      if is_torch_available()
      else {}
  )

  A__		 =				False
  A__		 =				False
  A__		 =				False
  A__		 =				False





  def 						A  (		self      :	Dict )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =RegNetModelTester(self )
       _SCREAMING_SNAKE_CASE							    =ConfigTester(self							,					config_class=_a							,					has_text_modality=_a )





  def 						A  (		self      :	int )	->    Optional[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 						A  (		self      :	Tuple )	->    Tuple:





       '''simple docstring'''






       return





  @unittest.skip(reason='RegNet does not use inputs_embeds' )
  def 						A  (		self      :	Tuple )	->    List[str]:





       '''simple docstring'''






       pass





  @unittest.skip(reason='RegNet does not support input and output embeddings' )
  def 						A  (		self      :	List[Any] )	->    List[str]:





       '''simple docstring'''






       pass





  def 						A  (		self      :	Tuple )	->    List[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            _SCREAMING_SNAKE_CASE							    =model_class(_a )
            _SCREAMING_SNAKE_CASE							    =inspect.signature(model.forward )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            _SCREAMING_SNAKE_CASE							    =[*signature.parameters.keys()]

            _SCREAMING_SNAKE_CASE							    =['pixel_values']
            self.assertListEqual(arg_names[:1]							,					_a )





  def 						A  (		self      :	str )	->    Union[str, Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_a )





  def 						A  (		self      :	Union[str, Any] )	->    Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            _SCREAMING_SNAKE_CASE							    =model_class(config=_a )
            for name, module in model.named_modules():
                 if isinstance(_a							,					(nn.BatchNormad, nn.GroupNorm) ):
                      self.assertTrue(
                          torch.all(module.weight == 1 )							,					msg=f"Parameter {name} of model {model_class} seems not properly initialized"							,					)
                      self.assertTrue(
                          torch.all(module.bias == 0 )							,					msg=f"Parameter {name} of model {model_class} seems not properly initialized"							,					)





  def 						A  (		self      :	int )	->    List[Any]:





       '''simple docstring'''






       def check_hidden_states_output(_a      :	Optional[int]							,					_a      :	int							,					_a      :	Dict ):
            _SCREAMING_SNAKE_CASE							    =model_class(_a )
            model.to(_a )
            model.eval()

            with torch.no_grad():
                 _SCREAMING_SNAKE_CASE							    =model(**self._prepare_for_class(_a							,					_a ) )

            _SCREAMING_SNAKE_CASE							    =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

            _SCREAMING_SNAKE_CASE							    =self.model_tester.num_stages
            self.assertEqual(len(_a )							,					expected_num_stages + 1 )

            # RegNet'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 // 2, self.model_tester.image_size // 2]							,					)

       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =self.model_tester.prepare_config_and_inputs_for_common()
       _SCREAMING_SNAKE_CASE							    =['basic', 'bottleneck']
       for model_class in self.all_model_classes:
            for layer_type in layers_type:
                 _SCREAMING_SNAKE_CASE							    =layer_type
                 _SCREAMING_SNAKE_CASE							    =True
                 check_hidden_states_output(_a							,					_a							,					_a )

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 _SCREAMING_SNAKE_CASE							    =True

                 check_hidden_states_output(_a							,					_a							,					_a )





  def 						A  (		self      :	List[Any] )	->    Union[str, Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_a )





  @slow
  def 						A  (		self      :	List[str] )	->    Dict:





       '''simple docstring'''






       for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _SCREAMING_SNAKE_CASE							    =RegNetModel.from_pretrained(_a )
            self.assertIsNotNone(_a )


def        _lowerCAmelCase					(						)      ->			int:
     """simple docstring"""




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







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





  @cached_property
  def 						A  (		self      :	Optional[Any] )	->    int:





       '''simple docstring'''






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





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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_a )

       _SCREAMING_SNAKE_CASE							    =self.default_image_processor
       _SCREAMING_SNAKE_CASE							    =prepare_img()
       _SCREAMING_SNAKE_CASE							    =image_processor(images=_a							,					return_tensors='pt' ).to(_a )

       # forward pass
       with torch.no_grad():
            _SCREAMING_SNAKE_CASE							    =model(**_a )

       # verify the logits
       _SCREAMING_SNAKE_CASE							    =torch.Size((1, 1000) )
       self.assertEqual(outputs.logits.shape							,					_a )

       _SCREAMING_SNAKE_CASE							    =torch.tensor([-0.41_80, -1.50_51, -3.48_36] ).to(_a )

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

import warnings
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


UpperCamelCase__											=					logging.get_logger(__name__)





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : int      =			['input_values', 'attention_mask']


   def __init__(self     :						Any       ,  __UpperCAmelCase     :						int = 1       ,  __UpperCAmelCase     :						int = 1_6_0_0_0       ,  __UpperCAmelCase     :						float = 0.0       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						int = 8_0       ,  __UpperCAmelCase     :						int = 1_6       ,  __UpperCAmelCase     :						int = 6_4       ,  __UpperCAmelCase     :						str = "hann_window"       ,  __UpperCAmelCase     :						float = 1.0       ,  __UpperCAmelCase     :						float = 8_0       ,  __UpperCAmelCase     :						float = 7_6_0_0       ,  __UpperCAmelCase     :						float = 1E-10       ,  __UpperCAmelCase     :						int = 2       ,  __UpperCAmelCase     :						bool = True       ,  **__UpperCAmelCase     :						Any       ,  )						->				str:
         """simple docstring"""



         super().__init__(feature_size=__UpperCAmelCase       ,  sampling_rate=__UpperCAmelCase       ,  padding_value=__UpperCAmelCase       ,  **__UpperCAmelCase		)
         UpperCAmelCase__								=  do_normalize
         UpperCAmelCase__								=  return_attention_mask

         UpperCAmelCase__								=  num_mel_bins
         UpperCAmelCase__								=  hop_length
         UpperCAmelCase__								=  win_length
         UpperCAmelCase__								=  win_function
         UpperCAmelCase__								=  frame_signal_scale
         UpperCAmelCase__								=  fmin
         UpperCAmelCase__								=  fmax
         UpperCAmelCase__								=  mel_floor
         UpperCAmelCase__								=  reduction_factor

         UpperCAmelCase__								=  win_length * sampling_rate // 1_0_0_0
         UpperCAmelCase__								=  hop_length * sampling_rate // 1_0_0_0
         UpperCAmelCase__								=  optimal_fft_length(self.sample_size		)
         UpperCAmelCase__								=  (self.n_fft // 2) + 1

         UpperCAmelCase__								=  window_function(window_length=self.sample_size       ,  name=self.win_function       ,  periodic=__UpperCAmelCase		)

         UpperCAmelCase__								=  mel_filter_bank(
             num_frequency_bins=self.n_freqs       ,  num_mel_filters=self.num_mel_bins       ,  min_frequency=self.fmin       ,  max_frequency=self.fmax       ,  sampling_rate=self.sampling_rate       ,  norm="slaney"       ,  mel_scale="slaney"       ,  )

         if frame_signal_scale != 1.0:
               warnings.warn(
                   "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers"       ,  __UpperCAmelCase       ,  )
         if reduction_factor != 2.0:
               warnings.warn(
                   "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"       ,  __UpperCAmelCase       ,  )


   @staticmethod
   # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
   def 			lowercase_      (__UpperCAmelCase     :						List[np.ndarray]       ,  __UpperCAmelCase     :						List[np.ndarray]       ,  __UpperCAmelCase     :						float = 0.0		)						->				List[np.ndarray]:
         """simple docstring"""



         if attention_mask is not None:
               UpperCAmelCase__								=  np.array(__UpperCAmelCase       ,  np.intaa		)
               UpperCAmelCase__								=  []

               for vector, length in zip(__UpperCAmelCase       ,  attention_mask.sum(-1		)		):
                     UpperCAmelCase__								=  (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7		)
                     if length < normed_slice.shape[0]:
                           UpperCAmelCase__								=  padding_value

                     normed_input_values.append(__UpperCAmelCase		)
         else:
               UpperCAmelCase__								=  [(x - x.mean()) / np.sqrt(x.var() + 1E-7		) for x in input_values]

         return normed_input_values


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						np.ndarray       ,  )						->				np.ndarray:
         """simple docstring"""



         UpperCAmelCase__								=  spectrogram(
             __UpperCAmelCase       ,  window=self.window       ,  frame_length=self.sample_size       ,  hop_length=self.sample_stride       ,  fft_length=self.n_fft       ,  mel_filters=self.mel_filters       ,  mel_floor=self.mel_floor       ,  log_mel="log10"       ,  )
         return log_mel_spec.T


   def __call__(self     :						Any       ,  __UpperCAmelCase     :						Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None       ,  __UpperCAmelCase     :						Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None       ,  __UpperCAmelCase     :						Union[bool, str, PaddingStrategy] = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						Optional[bool] = None       ,  __UpperCAmelCase     :						Optional[Union[str, TensorType]] = None       ,  __UpperCAmelCase     :						Optional[int] = None       ,  **__UpperCAmelCase     :						str       ,  )						->				BatchFeature:
         """simple docstring"""



         if audio is None and audio_target is None:
               raise ValueError("You must provide either `audio` or `audio_target` values."		)

         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 audio is not None:
               UpperCAmelCase__								=  self._process_audio(
                   __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  **__UpperCAmelCase       ,  )
         else:
               UpperCAmelCase__								=  None

         if audio_target is not None:
               UpperCAmelCase__								=  self._process_audio(
                   __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  **__UpperCAmelCase       ,  )

               if inputs is None:
                     return inputs_target
               else:
                     UpperCAmelCase__								=  inputs_target["input_values"]
                     UpperCAmelCase__								=  inputs_target.get("attention_mask"		)
                     if decoder_attention_mask is not None:
                           UpperCAmelCase__								=  decoder_attention_mask

         return inputs


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Union[bool, str, PaddingStrategy] = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						Optional[bool] = None       ,  __UpperCAmelCase     :						Optional[Union[str, TensorType]] = None       ,  **__UpperCAmelCase     :						Any       ,  )						->				BatchFeature:
         """simple docstring"""



         UpperCAmelCase__								=  isinstance(__UpperCAmelCase       ,  np.ndarray		) and len(speech.shape		) > 1
         if is_batched_numpy and len(speech.shape		) > 2:
               raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""		)
         UpperCAmelCase__								=  is_batched_numpy or (
             isinstance(__UpperCAmelCase       ,  (list, tuple)		) and (isinstance(speech[0]       ,  (np.ndarray, tuple, list)		))
         )

         if is_batched:
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		) for speech in speech]
         elif not is_batched and not isinstance(__UpperCAmelCase       ,  np.ndarray		):
               UpperCAmelCase__								=  np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		)
         elif isinstance(__UpperCAmelCase       ,  np.ndarray		) and speech.dtype is np.dtype(np.floataa		):
               UpperCAmelCase__								=  speech.astype(np.floataa		)

         # always return batch
         if not is_batched:
               UpperCAmelCase__								=  [speech]

         # needed to make pad() work on spectrogram inputs
         UpperCAmelCase__								=  self.feature_size

         # convert into correct format for padding
         if is_target:
               UpperCAmelCase__								=  [self._extract_mel_features(__UpperCAmelCase		) for waveform in speech]
               UpperCAmelCase__								=  BatchFeature({"input_values": features}		)
               UpperCAmelCase__								=  self.num_mel_bins
         else:
               UpperCAmelCase__								=  BatchFeature({"input_values": speech}		)

         UpperCAmelCase__								=  self.pad(
             __UpperCAmelCase       ,  padding=__UpperCAmelCase       ,  max_length=__UpperCAmelCase       ,  truncation=__UpperCAmelCase       ,  pad_to_multiple_of=__UpperCAmelCase       ,  return_attention_mask=__UpperCAmelCase       ,  **__UpperCAmelCase       ,  )

         UpperCAmelCase__								=  feature_size_hack

         # convert input values to correct format
         UpperCAmelCase__								=  padded_inputs["input_values"]
         if not isinstance(input_values[0]       ,  np.ndarray		):
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		) for array in input_values]
         elif (
             not isinstance(__UpperCAmelCase       ,  np.ndarray		)
             and isinstance(input_values[0]       ,  np.ndarray		)
             and input_values[0].dtype is np.dtype(np.floataa		)
         ):
               UpperCAmelCase__								=  [array.astype(np.floataa		) for array in input_values]
         elif isinstance(__UpperCAmelCase       ,  np.ndarray		) and input_values.dtype is np.dtype(np.floataa		):
               UpperCAmelCase__								=  input_values.astype(np.floataa		)

         # convert attention_mask to correct format
         UpperCAmelCase__								=  padded_inputs.get("attention_mask"		)
         if attention_mask is not None:
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.intaa		) for array in attention_mask]

         # zero-mean and unit-variance normalization
         if not is_target and self.do_normalize:
               UpperCAmelCase__								=  (
                   attention_mask
                   if self._get_padding_strategies(__UpperCAmelCase       ,  max_length=__UpperCAmelCase		) is not PaddingStrategy.DO_NOT_PAD
                   else None
               )
               UpperCAmelCase__								=  self.zero_mean_unit_var_norm(
                   padded_inputs["input_values"]       ,  attention_mask=__UpperCAmelCase       ,  padding_value=self.padding_value		)

         if return_tensors is not None:
               UpperCAmelCase__								=  padded_inputs.convert_to_tensors(__UpperCAmelCase		)

         return padded_inputs





   def 			lowercase_      (self     :						Tuple		)						->				Dict[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  super().to_dict()

         # Don't serialize these as they are derived from the other properties.
         UpperCAmelCase__								=  ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"]
         for name in names:
               if name in output:
                     del output[name]

         return output



