
"""simple docstring"""







from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

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


lowerCamelCase__           =	logging.get_logger(__name__)




class 				A__ (			_lowerCamelCase):
		A_		: List[str]            =			['input_features', 'attention_mask']

		def __init__(   self ,	_SCREAMING_SNAKE_CASE=80 ,	_SCREAMING_SNAKE_CASE=1_60_00 ,	_SCREAMING_SNAKE_CASE=80 ,	_SCREAMING_SNAKE_CASE=0.0 ,	_SCREAMING_SNAKE_CASE=True ,	_SCREAMING_SNAKE_CASE=True ,	_SCREAMING_SNAKE_CASE=True ,	**_SCREAMING_SNAKE_CASE ,	):
			super().__init__(feature_size=_SCREAMING_SNAKE_CASE ,	sampling_rate=_SCREAMING_SNAKE_CASE ,	padding_value=_SCREAMING_SNAKE_CASE ,	**_SCREAMING_SNAKE_CASE				)
			__lowerCAmelCase    :		List[Any]		    =   num_mel_bins
			__lowerCAmelCase    :		List[Any]		    =   do_ceptral_normalize
			__lowerCAmelCase    :		Any		    =   normalize_means
			__lowerCAmelCase    :		List[Any]		    =   normalize_vars
			__lowerCAmelCase    :		List[str]		    =   True

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	):
			__lowerCAmelCase    :		str		    =   waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
			__lowerCAmelCase    :		List[str]		    =   torch.from_numpy(_SCREAMING_SNAKE_CASE				).unsqueeze(0				)
			__lowerCAmelCase    :		Optional[Any]		    =   ta_kaldi.fbank(_SCREAMING_SNAKE_CASE ,	num_mel_bins=self.num_mel_bins ,	sample_frequency=self.sampling_rate				)
			return features.numpy()

		@staticmethod
		def 							__lowerCamelCase							(   _SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE = True ,	_SCREAMING_SNAKE_CASE = True ,	_SCREAMING_SNAKE_CASE = 0.0 ,	):
			# make sure we normalize float32 arrays
			if normalize_means:
				__lowerCAmelCase    :		Any		    =   x[:input_length].mean(axis=0				)
				__lowerCAmelCase    :		int		    =   np.subtract(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)
			if normalize_vars:
				__lowerCAmelCase    :		Any		    =   x[:input_length].std(axis=0				)
				__lowerCAmelCase    :		Union[str, Any]		    =   np.divide(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

			if input_length < x.shape[0]:
				__lowerCAmelCase    :		Tuple		    =   padding_value

			# make sure array is in float32
			__lowerCAmelCase    :		Tuple		    =   x.astype(np.floataa				)

			return x

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE = None				):
			__lowerCAmelCase    :		int		    =   attention_mask.sum(-1				) if attention_mask is not None else [x.shape[0] for x in input_features]
			return [
			    self.utterance_cmvn(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	self.normalize_means ,	self.normalize_vars ,	self.padding_value				)
			    for x, n in zip(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)
			]







		def __call__(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE = False ,	_SCREAMING_SNAKE_CASE = None ,	_SCREAMING_SNAKE_CASE = False ,	_SCREAMING_SNAKE_CASE = None ,	_SCREAMING_SNAKE_CASE = None ,	_SCREAMING_SNAKE_CASE = None ,	_SCREAMING_SNAKE_CASE = None ,	**_SCREAMING_SNAKE_CASE ,	):

			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 `raw_speech` 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.'				)

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

			if is_batched:
				__lowerCAmelCase    :		Dict		    =   [np.asarray(_SCREAMING_SNAKE_CASE ,	dtype=np.floataa				) for speech in raw_speech]
			elif not is_batched and not isinstance(_SCREAMING_SNAKE_CASE ,	np.ndarray				):
				__lowerCAmelCase    :		List[str]		    =   np.asarray(_SCREAMING_SNAKE_CASE ,	dtype=np.floataa				)
			elif isinstance(_SCREAMING_SNAKE_CASE ,	np.ndarray				) and raw_speech.dtype is np.dtype(np.floataa				):
				__lowerCAmelCase    :		str		    =   raw_speech.astype(np.floataa				)

			# always return batch
			if not is_batched:
				__lowerCAmelCase    :		Any		    =   [raw_speech]

			# extract fbank features
			__lowerCAmelCase    :		Any		    =   [self._extract_fbank_features(_SCREAMING_SNAKE_CASE				) for waveform in raw_speech]

			# convert into correct format for padding
			__lowerCAmelCase    :		str		    =   BatchFeature({'input_features': features}				)

			__lowerCAmelCase    :		Dict		    =   self.pad(
			    _SCREAMING_SNAKE_CASE ,	padding=_SCREAMING_SNAKE_CASE ,	max_length=_SCREAMING_SNAKE_CASE ,	truncation=_SCREAMING_SNAKE_CASE ,	pad_to_multiple_of=_SCREAMING_SNAKE_CASE ,	return_attention_mask=_SCREAMING_SNAKE_CASE ,	**_SCREAMING_SNAKE_CASE ,	)

			# make sure list is in array format
			__lowerCAmelCase    :		Optional[Any]		    =   padded_inputs.get('input_features'				)
			if isinstance(input_features[0] ,	_SCREAMING_SNAKE_CASE				):
				__lowerCAmelCase    :		List[str]		    =   [np.asarray(_SCREAMING_SNAKE_CASE ,	dtype=np.floataa				) for feature in input_features]

			__lowerCAmelCase    :		str		    =   padded_inputs.get('attention_mask'				)
			if attention_mask is not None:
				__lowerCAmelCase    :		Any		    =   [np.asarray(_SCREAMING_SNAKE_CASE ,	dtype=np.intaa				) for array in attention_mask]

			# Utterance-level cepstral mean and variance normalization
			if self.do_ceptral_normalize:
				__lowerCAmelCase    :		Union[str, Any]		    =   (
				    np.array(_SCREAMING_SNAKE_CASE ,	dtype=np.intaa				)
				    if self._get_padding_strategies(_SCREAMING_SNAKE_CASE ,	max_length=_SCREAMING_SNAKE_CASE				) is not PaddingStrategy.DO_NOT_PAD
				    else None
				)
				__lowerCAmelCase    :		Tuple		    =   self.normalize(
				    padded_inputs['input_features'] ,	attention_mask=_SCREAMING_SNAKE_CASE				)

			if return_tensors is not None:
				__lowerCAmelCase    :		List[Any]		    =   padded_inputs.convert_to_tensors(_SCREAMING_SNAKE_CASE				)

			return padded_inputs

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

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		Optional[Any]		    =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

			__lowerCAmelCase    :		List[str]		    =   None
			if self.use_labels:
				__lowerCAmelCase    :		Tuple		    =   ids_tensor([self.batch_size] ,	self.num_labels				)

			__lowerCAmelCase    :		int		    =   self.get_config()

			return config, pixel_values, labels

		def 							__lowerCamelCase							(   self				):
			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 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			__lowerCAmelCase    :		Any		    =   RegNetModel(config=_SCREAMING_SNAKE_CASE				)
			model.to(_SCREAMING_SNAKE_CASE				)
			model.eval()
			__lowerCAmelCase    :		Any		    =   model(_SCREAMING_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 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			__lowerCAmelCase    :		Optional[Any]		    =   self.num_labels
			__lowerCAmelCase    :		str		    =   RegNetForImageClassification(_SCREAMING_SNAKE_CASE				)
			model.to(_SCREAMING_SNAKE_CASE				)
			model.eval()
			__lowerCAmelCase    :		Any		    =   model(_SCREAMING_SNAKE_CASE ,	labels=_SCREAMING_SNAKE_CASE				)
			self.parent.assertEqual(result.logits.shape ,	(self.batch_size, self.num_labels)				)







		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		Optional[Any]		    =   self.prepare_config_and_inputs()
			__lowerCAmelCase    ,     __lowerCAmelCase    ,     __lowerCAmelCase    :		Any		    =   config_and_inputs
			__lowerCAmelCase    :		List[str]		    =   {'pixel_values': pixel_values}
			return config, inputs_dict




@require_torch
class 				A__ (			_lowerCamelCase ,  _lowerCamelCase ,  unittest.TestCase):
		A_		: List[str]            =			(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
		A_		: List[Any]            =			(
		    {'feature-extraction': RegNetModel, 'image-classification': RegNetForImageClassification}
		    if is_torch_available()
		    else {}
		)

		A_		: Dict            =			False
		A_		: str            =			False
		A_		: int            =			False
		A_		: Union[str, Any]            =			False

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		List[str]		    =   RegNetModelTester(self				)
			__lowerCAmelCase    :		int		    =   ConfigTester(self ,	config_class=_SCREAMING_SNAKE_CASE ,	has_text_modality=_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			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				):
			return

		@unittest.skip(reason='RegNet does not use inputs_embeds'				)
		def 							__lowerCamelCase							(   self				):
			pass

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

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    ,     __lowerCAmelCase    :		List[Any]		    =   self.model_tester.prepare_config_and_inputs_for_common()

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

				__lowerCAmelCase    :		Optional[int]		    =   ['pixel_values']
				self.assertListEqual(arg_names[:1] ,	_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		Optional[Any]		    =   self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    ,     __lowerCAmelCase    :		List[str]		    =   self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				__lowerCAmelCase    :		Union[str, Any]		    =   model_class(config=_SCREAMING_SNAKE_CASE				)
				for name, module in model.named_modules():
					if isinstance(_SCREAMING_SNAKE_CASE ,	(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 							__lowerCamelCase							(   self				):
			def check_hidden_states_output(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
				__lowerCAmelCase    :		Any		    =   model_class(_SCREAMING_SNAKE_CASE				)
				model.to(_SCREAMING_SNAKE_CASE				)
				model.eval()

				with torch.no_grad():
					__lowerCAmelCase    :		List[str]		    =   model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)				)

				__lowerCAmelCase    :		Any		    =   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

				__lowerCAmelCase    :		List[str]		    =   self.model_tester.num_stages
				self.assertEqual(len(_SCREAMING_SNAKE_CASE				) ,	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] ,	)

			__lowerCAmelCase    ,     __lowerCAmelCase    :		Dict		    =   self.model_tester.prepare_config_and_inputs_for_common()
			__lowerCAmelCase    :		List[Any]		    =   ['basic', 'bottleneck']
			for model_class in self.all_model_classes:
				for layer_type in layers_type:
					__lowerCAmelCase    :		List[Any]		    =   layer_type
					__lowerCAmelCase    :		Tuple		    =   True
					check_hidden_states_output(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

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

					check_hidden_states_output(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		List[Any]		    =   self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE				)







		@slow
		def 							__lowerCamelCase							(   self				):
			for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__lowerCAmelCase    :		Dict		    =   RegNetModel.from_pretrained(_SCREAMING_SNAKE_CASE				)
				self.assertIsNotNone(_SCREAMING_SNAKE_CASE				)



def 					__lowerCAmelCase       ():
	__lowerCAmelCase    :		str		    =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
	return image




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

		@cached_property
		def 							__lowerCamelCase							(   self				):
			return (
			    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
			    if is_vision_available()
			    else None
			)







		@slow
		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		List[str]		    =   RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		str		    =   self.default_image_processor
			__lowerCAmelCase    :		Any		    =   prepare_img()
			__lowerCAmelCase    :		Any		    =   image_processor(images=_SCREAMING_SNAKE_CASE ,	return_tensors='pt'				).to(_SCREAMING_SNAKE_CASE				)

			# forward pass
			with torch.no_grad():
				__lowerCAmelCase    :		List[str]		    =   model(**_SCREAMING_SNAKE_CASE				)

			# verify the logits
			__lowerCAmelCase    :		Union[str, Any]		    =   torch.Size((1, 10_00)				)
			self.assertEqual(outputs.logits.shape ,	_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		Optional[int]		    =   torch.tensor([-0.4180, -1.5051, -3.4836]				).to(_SCREAMING_SNAKE_CASE				)

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