
'''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 TensorType, logging


__lowercase							:				List[str]					=       logging.get_logger(__name__)

class 		__lowercase			(					_lowercase      ):
			lowerCamelCase     :						List[str]		 =     ["input_values", "attention_mask"]

			def __init__(self     ,				A=1     ,				A=1_6_0_0_0     ,				A=1_2_8     ,				A=1_0_2_4     ,				A=0.0     ,				A=True     ,				A=-4.2_67_73_93     ,				A=4.5_68_99_74     ,				A=False     ,				**A     ,				):
								super().__init__(feature_size=A     ,				sampling_rate=A     ,				padding_value=A     ,				**A )
								lowerCamelCase_   : Any       =						num_mel_bins
								lowerCamelCase_   : List[Any]       =						max_length
								lowerCamelCase_   : Optional[int]       =						do_normalize
								lowerCamelCase_   : str       =						mean
								lowerCamelCase_   : List[str]       =						std
								lowerCamelCase_   : Dict       =						return_attention_mask

			def     UpperCAmelCase__	(self     ,				A     ,				A     ,				):
								lowerCamelCase_   : List[Any]       =						torch.from_numpy(A ).unsqueeze(0 )
								lowerCamelCase_   : Optional[int]       =						ta_kaldi.fbank(
								    A     ,				htk_compat=A     ,				sample_frequency=self.sampling_rate     ,				use_energy=A     ,				window_type='''hanning'''     ,				num_mel_bins=self.num_mel_bins     ,				dither=0.0     ,				frame_shift=1_0     ,				)

								lowerCamelCase_   : str       =						fbank.shape[0]
								lowerCamelCase_   : str       =						max_length - n_frames

								# pad or truncate, depending on difference
								if difference > 0:
													lowerCamelCase_   : str       =						torch.nn.ZeroPadad((0, 0, 0, difference) )
													lowerCamelCase_   : Optional[int]       =						pad_module(A )
								elif difference < 0:
													lowerCamelCase_   : str       =						fbank[0:max_length, :]

								lowerCamelCase_   : Union[str, Any]       =						fbank.numpy()

								return fbank

			def     UpperCAmelCase__	(self     ,				A ):
								return (input_values - (self.mean)) / (self.std * 2)






			def __call__(self     ,				A     ,				A = None     ,				A = None     ,				**A     ,				):

								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_   : Optional[Any]       =						isinstance(A     ,				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_   : int       =						is_batched_numpy or (
								    isinstance(A     ,				(list, tuple) ) and (isinstance(raw_speech[0]     ,				(np.ndarray, tuple, list) ))
								)

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

								# always return batch
								if not is_batched:
													lowerCamelCase_   : List[str]       =						[raw_speech]

								# extract fbank features and pad/truncate to max_length
								lowerCamelCase_   : str       =						[self._extract_fbank_features(A     ,				max_length=self.max_length ) for waveform in raw_speech]

								# convert into BatchFeature
								lowerCamelCase_   : Any       =						BatchFeature({'''input_values''': features} )

								# make sure list is in array format
								lowerCamelCase_   : Dict       =						padded_inputs.get('''input_values''' )
								if isinstance(input_values[0]     ,				A ):
													lowerCamelCase_   : Any       =						[np.asarray(A     ,				dtype=np.floataa ) for feature in input_values]

								# normalization
								if self.do_normalize:
													lowerCamelCase_   : int       =						[self.normalize(A ) for feature in input_values]

								if return_tensors is not None:
													lowerCamelCase_   : Optional[int]       =						padded_inputs.convert_to_tensors(A )

								return padded_inputs




'''simple docstring'''


from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
					from PIL import Image

					from transformers import ConvNextImageProcessor

class 		__lowercase			:

			def __init__(self     ,				A     ,				A=1_3     ,				A=3_2     ,				A=3     ,				A=4     ,				A=[1_0, 2_0, 3_0, 4_0]     ,				A=[2, 2, 3, 2]     ,				A=True     ,				A=True     ,				A=3_7     ,				A="gelu"     ,				A=1_0     ,				A=0.02     ,				A=3     ,				A=None     ,				):
								lowerCamelCase_   : List[str]       =						parent
								lowerCamelCase_   : List[Any]       =						batch_size
								lowerCamelCase_   : List[str]       =						image_size
								lowerCamelCase_   : List[str]       =						num_channels
								lowerCamelCase_   : Union[str, Any]       =						num_stages
								lowerCamelCase_   : Optional[Any]       =						hidden_sizes
								lowerCamelCase_   : Optional[int]       =						depths
								lowerCamelCase_   : Optional[Any]       =						is_training
								lowerCamelCase_   : Dict       =						use_labels
								lowerCamelCase_   : Optional[int]       =						intermediate_size
								lowerCamelCase_   : Union[str, Any]       =						hidden_act
								lowerCamelCase_   : Tuple       =						type_sequence_label_size
								lowerCamelCase_   : Optional[Any]       =						initializer_range
								lowerCamelCase_   : str       =						scope

			def     UpperCAmelCase__	(self ):
								lowerCamelCase_   : Optional[int]       =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

								lowerCamelCase_   : str       =						None
								if self.use_labels:
													lowerCamelCase_   : Optional[Any]       =						ids_tensor([self.batch_size]     ,				self.type_sequence_label_size )

								lowerCamelCase_   : List[Any]       =						self.get_config()

								return config, pixel_values, labels

			def     UpperCAmelCase__	(self ):
								return ConvNextConfig(
								    num_channels=self.num_channels     ,				hidden_sizes=self.hidden_sizes     ,				depths=self.depths     ,				num_stages=self.num_stages     ,				hidden_act=self.hidden_act     ,				is_decoder=A     ,				initializer_range=self.initializer_range     ,				)

			def     UpperCAmelCase__	(self     ,				A     ,				A     ,				A ):
								lowerCamelCase_   : List[str]       =						TFConvNextModel(config=A )
								lowerCamelCase_   : Tuple       =						model(A     ,				training=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 // 3_2, self.image_size // 3_2)     ,				)

			def     UpperCAmelCase__	(self     ,				A     ,				A     ,				A ):
								lowerCamelCase_   : Union[str, Any]       =						self.type_sequence_label_size
								lowerCamelCase_   : Dict       =						TFConvNextForImageClassification(A )
								lowerCamelCase_   : Optional[Any]       =						model(A     ,				labels=A     ,				training=A )
								self.parent.assertEqual(result.logits.shape     ,				(self.batch_size, self.type_sequence_label_size) )






			def     UpperCAmelCase__	(self ):
								lowerCamelCase_   : str       =						self.prepare_config_and_inputs()
								lowerCamelCase_, lowerCamelCase_, lowerCamelCase_   : List[str]       =						config_and_inputs
								lowerCamelCase_   : Tuple       =						{'''pixel_values''': pixel_values}
								return config, inputs_dict

@require_tf
class 		__lowercase			(					_lowercase ,       _lowercase ,       unittest.TestCase      ):
			lowerCamelCase     :						Tuple		 =     (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
			lowerCamelCase     :						List[str]		 =     (
			    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
			    if is_tf_available()
			    else {}
			)

			lowerCamelCase     :						List[Any]		 =     False
			lowerCamelCase     :						List[str]		 =     False
			lowerCamelCase     :						Optional[int]		 =     False
			lowerCamelCase     :						List[Any]		 =     False
			lowerCamelCase     :						List[Any]		 =     False

			def     UpperCAmelCase__	(self ):
								lowerCamelCase_   : List[str]       =						TFConvNextModelTester(self )
								lowerCamelCase_   : int       =						ConfigTester(
								    self     ,				config_class=A     ,				has_text_modality=A     ,				hidden_size=3_7     ,				)

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

			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0     ,				reason='''TF does not support backprop for grouped convolutions on CPU.'''     ,				)
			@slow
			def     UpperCAmelCase__	(self ):
								super().test_keras_fit()

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

			def     UpperCAmelCase__	(self ):
								lowerCamelCase_, lowerCamelCase_   : Tuple       =						self.model_tester.prepare_config_and_inputs_for_common()

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

													lowerCamelCase_   : str       =						['''pixel_values''']
													self.assertListEqual(arg_names[:1]     ,				A )

			def     UpperCAmelCase__	(self ):
								lowerCamelCase_   : List[Any]       =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A )

			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0     ,				reason='''TF does not support backprop for grouped convolutions on CPU.'''     ,				)
			def     UpperCAmelCase__	(self ):
								super().test_dataset_conversion()

			def     UpperCAmelCase__	(self ):
								def check_hidden_states_output(A     ,				A     ,				A ):
													lowerCamelCase_   : str       =						model_class(A )

													lowerCamelCase_   : Dict       =						model(**self._prepare_for_class(A     ,				A ) )
													lowerCamelCase_   : List[str]       =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													lowerCamelCase_   : Tuple       =						self.model_tester.num_stages
													self.assertEqual(len(A )     ,				expected_num_stages + 1 )

													# ConvNext'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_   : Union[str, Any]       =						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													lowerCamelCase_   : Optional[Any]       =						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     UpperCAmelCase__	(self ):
								lowerCamelCase_, lowerCamelCase_   : Dict       =						self.model_tester.prepare_config_and_inputs_for_common()

								def check_equivalence(A     ,				A     ,				A     ,				A={} ):
													lowerCamelCase_   : Tuple       =						model(A     ,				return_dict=A     ,				**A )
													lowerCamelCase_   : List[str]       =						model(A     ,				return_dict=A     ,				**A ).to_tuple()

													def recursive_check(A     ,				A ):
																		if isinstance(A     ,				(List, Tuple) ):
																							for tuple_iterable_value, dict_iterable_value in zip(A     ,				A ):
																												recursive_check(A     ,				A )
																		elif tuple_object is None:
																							return
																		else:
																							self.assertTrue(
																							    all(tf.equal(A     ,				A ) )     ,				msg=(
																							        '''Tuple and dict output are not equal. Difference:'''
																							        F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}"""
																							    )     ,				)

																		recursive_check(A     ,				A )

								for model_class in self.all_model_classes:
													lowerCamelCase_   : Optional[Any]       =						model_class(A )

													lowerCamelCase_   : Any       =						self._prepare_for_class(A     ,				A )
													lowerCamelCase_   : Any       =						self._prepare_for_class(A     ,				A )
													check_equivalence(A     ,				A     ,				A )

													lowerCamelCase_   : Optional[Any]       =						self._prepare_for_class(A     ,				A     ,				return_labels=A )
													lowerCamelCase_   : int       =						self._prepare_for_class(A     ,				A     ,				return_labels=A )
													check_equivalence(A     ,				A     ,				A )

													lowerCamelCase_   : Union[str, Any]       =						self._prepare_for_class(A     ,				A )
													lowerCamelCase_   : List[str]       =						self._prepare_for_class(A     ,				A )
													check_equivalence(A     ,				A     ,				A     ,				{'''output_hidden_states''': True} )

													lowerCamelCase_   : Optional[int]       =						self._prepare_for_class(A     ,				A     ,				return_labels=A )
													lowerCamelCase_   : List[str]       =						self._prepare_for_class(A     ,				A     ,				return_labels=A )
													check_equivalence(A     ,				A     ,				A     ,				{'''output_hidden_states''': True} )

			def     UpperCAmelCase__	(self ):
								lowerCamelCase_   : str       =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*A )






			@slow
			def     UpperCAmelCase__	(self ):
								lowerCamelCase_   : List[str]       =						TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224''' )
								self.assertIsNotNone(A )




def lowercase_		(				)       ->							Optional[Any]:
					'''simple docstring'''

					lowerCamelCase_   : Optional[Any]       =						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
					return image






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

			@cached_property
			def     UpperCAmelCase__	(self ):
								return ConvNextImageProcessor.from_pretrained('''facebook/convnext-tiny-224''' ) if is_vision_available() else None






			@slow
			def     UpperCAmelCase__	(self ):
								lowerCamelCase_   : List[str]       =						TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224''' )

								lowerCamelCase_   : Tuple       =						self.default_image_processor
								lowerCamelCase_   : List[str]       =						prepare_img()
								lowerCamelCase_   : Optional[Any]       =						image_processor(images=A     ,				return_tensors='''tf''' )

								# forward pass
								lowerCamelCase_   : Optional[int]       =						model(**A )

								# verify the logits
								lowerCamelCase_   : List[str]       =						tf.TensorShape((1, 1_0_0_0) )
								self.assertEqual(outputs.logits.shape     ,				A )

								lowerCamelCase_   : Optional[int]       =						tf.constant([-0.02_60, -0.47_39, 0.19_11] )

								tf.debugging.assert_near(outputs.logits[0, :3]     ,				A     ,				atol=1E-4 )


