

'''simple docstring'''

from math import ceil
from typing import List, Optional, Union

import numpy as np

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


a   :			List[Any]         = logging.get_logger(__name__)







class   UpperCamelCase__    (   _UpperCamelCase   ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :	str   =							['audio_values', 'audio_mask']







		def __init__( self    ,			snake_case=2_0_4_8    ,			snake_case=1    ,			snake_case=[1_6, 1_6]    ,			snake_case=1_2_8    ,			snake_case=4_4_1_0_0    ,			snake_case=8_6    ,			snake_case=2_0_4_8    ,			snake_case=0.0    ,			**snake_case    ,			):


							'''simple docstring'''

							super().__init__(
							    feature_size=_UpperCAmelCase    ,			sampling_rate=_UpperCAmelCase    ,			padding_value=_UpperCAmelCase    ,			**_UpperCAmelCase    ,			)

							UpperCAmelCase		:							List[Any]   					=   spectrogram_length
							UpperCAmelCase		:							Tuple   					=   num_channels
							UpperCAmelCase		:							Dict   					=   patch_size
							UpperCAmelCase		:							Optional[Any]   					=   feature_size // self.patch_size[1]
							UpperCAmelCase		:							Tuple   					=   n_fft
							UpperCAmelCase		:							List[Any]   					=   sampling_rate // hop_length_to_sampling_rate
							UpperCAmelCase		:							List[str]   					=   sampling_rate
							UpperCAmelCase		:							Union[str, Any]   					=   padding_value
							UpperCAmelCase		:							Any   					=   mel_filter_bank(
							    num_frequency_bins=1 + n_fft // 2    ,			num_mel_filters=_UpperCAmelCase    ,			min_frequency=0.0    ,			max_frequency=2_2_0_5_0.0    ,			sampling_rate=_UpperCAmelCase    ,			norm="slaney"    ,			mel_scale="slaney"    ,			).T







		def       A_       ( self    ,			snake_case			):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]   					=   spectrogram(
							    _UpperCAmelCase    ,			window_function(self.n_fft    ,			"hann"			)    ,			frame_length=self.n_fft    ,			hop_length=self.hop_length    ,			power=2.0    ,			mel_filters=self.mel_filters.T    ,			log_mel="dB"    ,			db_range=80.0    ,			)
							UpperCAmelCase		:							List[Any]   					=   log_spec[:, :-1]
							UpperCAmelCase		:							Optional[Any]   					=   log_spec - 20.0
							UpperCAmelCase		:							Dict   					=   np.clip(log_spec / 40.0    ,			-2.0    ,			0.0			) + 1.0
							return log_spec







		def __call__( self    ,			snake_case    ,			snake_case = None    ,			snake_case = True    ,			snake_case = None    ,			snake_case = False    ,			snake_case = False    ,			**snake_case    ,			):


							'''simple docstring'''

							if sampling_rate is not None:
												if sampling_rate != self.sampling_rate:
																	raise ValueError(
																	    "This feature extractor is set to support sampling rate"
																	    f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"
																	    f" with {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."			)

							UpperCAmelCase		:							Optional[Any]   					=   isinstance(_UpperCAmelCase    ,			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}"			)
							UpperCAmelCase		:							Optional[int]   					=   is_batched_numpy or (
							    isinstance(_UpperCAmelCase    ,			(list, tuple)			) and (isinstance(raw_speech[0]    ,			(np.ndarray, tuple, list)			))
							)
							if is_batched:
												UpperCAmelCase		:							Union[str, Any]   					=   [np.asarray([speech]    ,			dtype=np.floataa			).T for speech in raw_speech]
							elif not is_batched and not isinstance(_UpperCAmelCase    ,			np.ndarray			):
												UpperCAmelCase		:							Optional[int]   					=   np.asarray(_UpperCAmelCase    ,			dtype=np.floataa			)
							elif isinstance(_UpperCAmelCase    ,			np.ndarray			) and raw_speech.dtype is np.dtype(np.floataa			):
												UpperCAmelCase		:							Optional[Any]   					=   raw_speech.astype(np.floataa			)
							# always return batch
							if not is_batched:
												UpperCAmelCase		:							Dict   					=   [np.asarray([raw_speech]			).T]

							# Convert audio signals to log mel spectrograms, truncate by time axis
							UpperCAmelCase		:							Any   					=   [
							    self._np_extract_fbank_features(waveform.squeeze()			).T[: self.spectrogram_length] for waveform in raw_speech
							]
							if isinstance(audio_features[0]    ,			_UpperCAmelCase			):
												UpperCAmelCase		:							Tuple   					=   [np.asarray(_UpperCAmelCase    ,			dtype=np.floataa			) for feature in audio_features]

							# Create audio attention mask
							UpperCAmelCase		:							List[Any]   					=   max(
							    [ceil(feature.shape[0] / self.patch_size[0]			) * self.freq_len for feature in audio_features]			)  # The maximum number of audio patches in a batch
							if return_attention_mask:
												UpperCAmelCase		:							Dict   					=   [
												    (ceil(feature.shape[0] / self.patch_size[0]			) * self.freq_len) * [1]
												    + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]			) * self.freq_len) * [0]
												    for feature in audio_features
												]
												UpperCAmelCase		:							Union[str, Any]   					=   np.array(_UpperCAmelCase			).astype(np.floataa			)

							# convert into correct format for padding
							UpperCAmelCase		:							Dict   					=   max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
							UpperCAmelCase		:							Union[str, Any]   					=   np.ones([len(_UpperCAmelCase			), 1, max_time_len, self.feature_size]			).astype(np.floataa			)
							UpperCAmelCase		:							List[Any]   					=   padded_audio_features * self.padding_value
							for i in range(len(_UpperCAmelCase			)			):
												UpperCAmelCase		:							Any   					=   audio_features[i]
												UpperCAmelCase		:							List[Any]   					=   feature

							# return as BatchFeature
							if return_attention_mask:
												UpperCAmelCase		:							Tuple   					=   {'audio_values': padded_audio_features, 'audio_mask': audio_mask}
							else:
												UpperCAmelCase		:							Tuple   					=   {'audio_values': padded_audio_features}

							UpperCAmelCase		:							Optional[Any]   					=   BatchFeature(data=_UpperCAmelCase    ,			tensor_type=_UpperCAmelCase			)
							return encoded_inputs





'''simple docstring'''

import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
							from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor

class 	__magic_name__						:







							def __init__(							self					:       List[str]	,_UpperCAmelCase					:       List[Any]	,_UpperCAmelCase					:       List[str]=13	,_UpperCAmelCase					:       Any=32	,_UpperCAmelCase					:       Union[str, Any]=3	,_UpperCAmelCase					:       Optional[int]=4	,_UpperCAmelCase					:       Optional[Any]=[10, 20, 30, 40]	,_UpperCAmelCase					:       Tuple=[2, 2, 3, 2]	,_UpperCAmelCase					:       Optional[int]=True	,_UpperCAmelCase					:       Optional[int]=True	,_UpperCAmelCase					:       Union[str, Any]=37	,_UpperCAmelCase					:       Optional[int]="gelu"	,_UpperCAmelCase					:       Optional[Any]=10	,_UpperCAmelCase					:       Tuple=0.02	,_UpperCAmelCase					:       Any=["stage2", "stage3", "stage4"]	,_UpperCAmelCase					:       Any=[2, 3, 4]	,_UpperCAmelCase					:       Tuple=None	,):
									_a     :      Optional[Any]        =							parent
									_a     :      List[Any]        =							batch_size
									_a     :      str        =							image_size
									_a     :      Union[str, Any]        =							num_channels
									_a     :      List[Any]        =							num_stages
									_a     :      Dict        =							hidden_sizes
									_a     :      int        =							depths
									_a     :      Tuple        =							is_training
									_a     :      List[str]        =							use_labels
									_a     :      Dict        =							intermediate_size
									_a     :      int        =							hidden_act
									_a     :      int        =							num_labels
									_a     :      Any        =							initializer_range
									_a     :      Tuple        =							out_features
									_a     :      int        =							out_indices
									_a     :      List[Any]        =							scope







							def 							__lowercase			(							self					:       Dict		):
									_a     :      List[Any]        =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

									_a     :      str        =							self.get_config()

									return config, pixel_values, labels







							def 							__lowercase			(							self					:       Any		):
									return ConvNextVaConfig(
									    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=_UpperCAmelCase	,initializer_range=self.initializer_range	,out_features=self.out_features	,out_indices=self.out_indices	,num_labels=self.num_labels	,)







							def 							__lowercase			(							self					:       Tuple	,_UpperCAmelCase					:       Any	,_UpperCAmelCase					:       Any	,_UpperCAmelCase					:       Optional[Any]		):
									_a     :      Optional[Any]        =							ConvNextVaModel(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_a     :      Any        =							model(_UpperCAmelCase		)
									# 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					:       Tuple	,_UpperCAmelCase					:       Union[str, Any]	,_UpperCAmelCase					:       List[Any]	,_UpperCAmelCase					:       int		):
									_a     :      List[Any]        =							ConvNextVaForImageClassification(_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_a     :      List[str]        =							model(_UpperCAmelCase	,labels=_UpperCAmelCase		)
									self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.num_labels)		)







							def 							__lowercase			(							self					:       str	,_UpperCAmelCase					:       List[Any]	,_UpperCAmelCase					:       str	,_UpperCAmelCase					:       Optional[Any]		):
									_a     :      Optional[int]        =							ConvNextVaBackbone(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_a     :      Dict        =							model(_UpperCAmelCase		)

									# verify hidden states
									self.parent.assertEqual(len(result.feature_maps		)	,len(config.out_features		)		)
									self.parent.assertListEqual(list(result.feature_maps[0].shape		)	,[self.batch_size, self.hidden_sizes[1], 4, 4]		)

									# verify channels
									self.parent.assertEqual(len(model.channels		)	,len(config.out_features		)		)
									self.parent.assertListEqual(model.channels	,config.hidden_sizes[1:]		)

									# verify backbone works with out_features=None
									_a     :      Tuple        =							None
									_a     :      List[Any]        =							ConvNextVaBackbone(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_a     :      List[str]        =							model(_UpperCAmelCase		)

									# verify feature maps
									self.parent.assertEqual(len(result.feature_maps		)	,1		)
									self.parent.assertListEqual(list(result.feature_maps[0].shape		)	,[self.batch_size, self.hidden_sizes[-1], 1, 1]		)

									# verify channels
									self.parent.assertEqual(len(model.channels		)	,1		)
									self.parent.assertListEqual(model.channels	,[config.hidden_sizes[-1]]		)







							def 							__lowercase			(							self					:       Optional[Any]		):
									_a     :      Any        =							self.prepare_config_and_inputs()
									_a       ,					_a       ,					_a     :      Union[str, Any]        =							config_and_inputs
									_a     :      Any        =							{'pixel_values': pixel_values}
									return config, inputs_dict







							def 							__lowercase			(							self					:       str		):
									_a     :      Tuple        =							self.prepare_config_and_inputs()
									_a       ,					_a       ,					_a     :      Tuple        =							config_and_inputs
									_a     :      List[Any]        =							{'pixel_values': pixel_values, 'labels': labels}
									return config, inputs_dict

@require_torch
class 	__magic_name__						(    _UpperCamelCase			,						_UpperCamelCase			,						unittest.TestCase   ):
							lowerCAmelCase       :    str   				=					(
							    (
							        ConvNextVaModel,
							        ConvNextVaForImageClassification,
							        ConvNextVaBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							lowerCAmelCase       :    str   				=					(
							    {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification}
							    if is_torch_available()
							    else {}
							)

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







							def 							__lowercase			(							self					:       List[Any]		):
									_a     :      str        =							ConvNextVaModelTester(self		)
									_a     :      Tuple        =							ConfigTester(self	,config_class=_UpperCAmelCase	,has_text_modality=_UpperCAmelCase	,hidden_size=37		)







							def 							__lowercase			(							self					:       Optional[Any]		):
									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					:       str		):
									return







							@unittest.skip(reason='ConvNextV2 does not use inputs_embeds'		)
							def 							__lowercase			(							self					:       List[Any]		):
									pass







							@unittest.skip(reason='ConvNextV2 does not support input and output embeddings'		)
							def 							__lowercase			(							self					:       Optional[int]		):
									pass







							@unittest.skip(reason='ConvNextV2 does not use feedforward chunking'		)
							def 							__lowercase			(							self					:       Any		):
									pass







							def 							__lowercase			(							self					:       List[str]		):
									if not self.model_tester.is_training:
											return

									for model_class in self.all_model_classes:
											_a       ,					_a     :      List[Any]        =							self.model_tester.prepare_config_and_inputs_with_labels()
											_a     :      Any        =							True

											if model_class.__name__ in [
											    *get_values(_UpperCAmelCase		),
											    *get_values(_UpperCAmelCase		),
											]:
													continue

											_a     :      Optional[Any]        =							model_class(_UpperCAmelCase		)
											model.to(_UpperCAmelCase		)
											model.train()
											_a     :      str        =							self._prepare_for_class(_UpperCAmelCase	,_UpperCAmelCase	,return_labels=_UpperCAmelCase		)
											_a     :      Optional[int]        =							model(**_UpperCAmelCase		).loss
											loss.backward()







							def 							__lowercase			(							self					:       str		):
									if not self.model_tester.is_training:
											return

									for model_class in self.all_model_classes:
											_a       ,					_a     :      Optional[Any]        =							self.model_tester.prepare_config_and_inputs_with_labels()
											_a     :      Optional[int]        =							False
											_a     :      Tuple        =							True

											if (
											    model_class.__name__
											    in [*get_values(_UpperCAmelCase		), *get_values(_UpperCAmelCase		)]
											    or not model_class.supports_gradient_checkpointing
											):
													continue

											_a     :      Tuple        =							model_class(_UpperCAmelCase		)
											model.to(_UpperCAmelCase		)
											model.gradient_checkpointing_enable()
											model.train()
											_a     :      Any        =							self._prepare_for_class(_UpperCAmelCase	,_UpperCAmelCase	,return_labels=_UpperCAmelCase		)
											_a     :      List[Any]        =							model(**_UpperCAmelCase		).loss
											loss.backward()







							def 							__lowercase			(							self					:       List[Any]		):
									_a       ,					_a     :      List[Any]        =							self.model_tester.prepare_config_and_inputs_for_common()

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

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







							def 							__lowercase			(							self					:       int		):
									_a     :      Dict        =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCAmelCase		)







							def 							__lowercase			(							self					:       Any		):
									def check_hidden_states_output(_UpperCAmelCase					:       List[Any]	,_UpperCAmelCase					:       Tuple	,_UpperCAmelCase					:       Dict		):
											_a     :      Union[str, Any]        =							model_class(_UpperCAmelCase		)
											model.to(_UpperCAmelCase		)
											model.eval()

											with torch.no_grad():
													_a     :      List[Any]        =							model(**self._prepare_for_class(_UpperCAmelCase	,_UpperCAmelCase		)		)

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

											_a     :      str        =							self.model_tester.num_stages
											self.assertEqual(len(_UpperCAmelCase		)	,expected_num_stages + 1		)

											# ConvNextV2'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[str]        =							self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											_a     :      int        =							True
											check_hidden_states_output(_UpperCAmelCase	,_UpperCAmelCase	,_UpperCAmelCase		)

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

											check_hidden_states_output(_UpperCAmelCase	,_UpperCAmelCase	,_UpperCAmelCase		)







							def 							__lowercase			(							self					:       List[Any]		):
									_a     :      Optional[Any]        =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase		)







							@slow
							def 							__lowercase			(							self					:       int		):
									for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_a     :      Any        =							ConvNextVaModel.from_pretrained(_UpperCAmelCase		)
											self.assertIsNotNone(_UpperCAmelCase		)



def      __lowerCamelCase     (      )			->      List[Any]:
		_a     :      List[Any]        =							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
		return image

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







							@cached_property
							def 							__lowercase			(							self					:       Optional[Any]		):
									return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'		) if is_vision_available() else None







							@slow
							def 							__lowercase			(							self					:       Any		):
									_a     :      List[str]        =							ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'		).to(_UpperCAmelCase		)

									_a     :      Optional[int]        =							self.default_image_processor
									_a     :      str        =							prepare_img()
									_a     :      str        =							preprocessor(images=_UpperCAmelCase	,return_tensors='pt'		).to(_UpperCAmelCase		)

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

									# verify the logits
									_a     :      Optional[Any]        =							torch.Size((1, 1000)		)
									self.assertEqual(outputs.logits.shape	,_UpperCAmelCase		)

									_a     :      Optional[Any]        =							torch.tensor([0.99_96, 0.19_66, -0.43_86]		).to(_UpperCAmelCase		)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]	,_UpperCAmelCase	,atol=1E-4		)		)




