






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


snake_case__      :	int       	=      logging.get_logger(__name__)


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   ["""input_features""", """attention_mask"""]




  def __init__(     self		,		_UpperCAmelCase=80		,		_UpperCAmelCase=16000		,		_UpperCAmelCase=80		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		**_UpperCAmelCase		,		)			-> Optional[Any]:
     super().__init__(feature_size=_UpperCAmelCase		,		sampling_rate=_UpperCAmelCase		,		padding_value=_UpperCAmelCase		,		**_UpperCAmelCase )
     UpperCamelCase_									=     num_mel_bins
     UpperCamelCase_									=     do_ceptral_normalize
     UpperCamelCase_									=     normalize_means
     UpperCamelCase_									=     normalize_vars
     UpperCamelCase_									=     True




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		)			-> np.ndarray:
     UpperCamelCase_									=     waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
     UpperCamelCase_									=     torch.from_numpy(_UpperCAmelCase ).unsqueeze(0 )
     UpperCamelCase_									=     ta_kaldi.fbank(_UpperCAmelCase		,		num_mel_bins=self.num_mel_bins		,		sample_frequency=self.sampling_rate )
     return features.numpy()




  @staticmethod
  def    _UpperCAmelCase     (     _UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = True		,		_UpperCAmelCase = True		,		_UpperCAmelCase = 0.0		,		)			-> np.ndarray:
     # make sure we normalize float32 arrays
     if normalize_means:
        UpperCamelCase_									=     x[:input_length].mean(axis=0 )
        UpperCamelCase_									=     np.subtract(_UpperCAmelCase		,		_UpperCAmelCase )
     if normalize_vars:
        UpperCamelCase_									=     x[:input_length].std(axis=0 )
        UpperCamelCase_									=     np.divide(_UpperCAmelCase		,		_UpperCAmelCase )

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

     # make sure array is in float32
     UpperCamelCase_									=     x.astype(np.floataa )

     return x




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = None )			-> List[np.ndarray]:
     UpperCamelCase_									=     attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features]
     return [
         self.utterance_cmvn(_UpperCAmelCase		,		_UpperCAmelCase		,		self.normalize_means		,		self.normalize_vars		,		self.padding_value )
         for x, n in zip(_UpperCAmelCase		,		_UpperCAmelCase )
     ]




  def __call__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase = False		,		_UpperCAmelCase = None		,		_UpperCAmelCase = False		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)			-> BatchFeature:

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

     UpperCamelCase_									=     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_									=     is_batched_numpy or (
         isinstance(_UpperCAmelCase		,		(list, tuple) ) and (isinstance(raw_speech[0]		,		(np.ndarray, tuple, list) ))
     )

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

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

     # extract fbank features
     UpperCamelCase_									=     [self._extract_fbank_features(_UpperCAmelCase ) for waveform in raw_speech]

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

     UpperCamelCase_									=     self.pad(
         _UpperCAmelCase		,		padding=_UpperCAmelCase		,		max_length=_UpperCAmelCase		,		truncation=_UpperCAmelCase		,		pad_to_multiple_of=_UpperCAmelCase		,		return_attention_mask=_UpperCAmelCase		,		**_UpperCAmelCase		,		)

     # make sure list is in array format
     UpperCamelCase_									=     padded_inputs.get('input_features' )
     if isinstance(input_features[0]		,		_UpperCAmelCase ):
        UpperCamelCase_									=     [np.asarray(_UpperCAmelCase		,		dtype=np.floataa ) for feature in input_features]

     UpperCamelCase_									=     padded_inputs.get('attention_mask' )
     if attention_mask is not None:
        UpperCamelCase_									=     [np.asarray(_UpperCAmelCase		,		dtype=np.intaa ) for array in attention_mask]

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

     if return_tensors is not None:
        UpperCamelCase_									=     padded_inputs.convert_to_tensors(_UpperCAmelCase )

     return padded_inputs










import inspect
import unittest

from transformers import ViTMSNConfig
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 torch import nn

 from transformers import ViTMSNForImageClassification, ViTMSNModel
 from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor


class 						_a       :






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=30		,		_UpperCAmelCase=2		,		_UpperCAmelCase=3		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=32		,		_UpperCAmelCase=5		,		_UpperCAmelCase=4		,		_UpperCAmelCase=37		,		_UpperCAmelCase="gelu"		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=10		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=None		,		)			-> Optional[Any]:
     UpperCamelCase_									=     parent
     UpperCamelCase_									=     batch_size
     UpperCamelCase_									=     image_size
     UpperCamelCase_									=     patch_size
     UpperCamelCase_									=     num_channels
     UpperCamelCase_									=     is_training
     UpperCamelCase_									=     use_labels
     UpperCamelCase_									=     hidden_size
     UpperCamelCase_									=     num_hidden_layers
     UpperCamelCase_									=     num_attention_heads
     UpperCamelCase_									=     intermediate_size
     UpperCamelCase_									=     hidden_act
     UpperCamelCase_									=     hidden_dropout_prob
     UpperCamelCase_									=     attention_probs_dropout_prob
     UpperCamelCase_									=     type_sequence_label_size
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     scope

     # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
     UpperCamelCase_									=     (image_size // patch_size) ** 2
     UpperCamelCase_									=     num_patches + 1




  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_									=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

     UpperCamelCase_									=     None
     if self.use_labels:
        UpperCamelCase_									=     ids_tensor([self.batch_size]		,		self.type_sequence_label_size )

     UpperCamelCase_									=     self.get_config()

     return config, pixel_values, labels




  def    _UpperCAmelCase     (     self )			-> int:
     return ViTMSNConfig(
         image_size=self.image_size		,		patch_size=self.patch_size		,		num_channels=self.num_channels		,		hidden_size=self.hidden_size		,		num_hidden_layers=self.num_hidden_layers		,		num_attention_heads=self.num_attention_heads		,		intermediate_size=self.intermediate_size		,		hidden_act=self.hidden_act		,		hidden_dropout_prob=self.hidden_dropout_prob		,		attention_probs_dropout_prob=self.attention_probs_dropout_prob		,		initializer_range=self.initializer_range		,		)




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Any:
     UpperCamelCase_									=     ViTMSNModel(config=_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.last_hidden_state.shape		,		(self.batch_size, self.seq_length, self.hidden_size) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> str:
     UpperCamelCase_									=     self.type_sequence_label_size
     UpperCamelCase_									=     ViTMSNForImageClassification(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase		,		labels=_UpperCAmelCase )
     print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}' )
     print('Labels: {labels}' )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size) )

     # test greyscale images
     UpperCamelCase_									=     1
     UpperCamelCase_									=     ViTMSNForImageClassification(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()

     UpperCamelCase_									=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size) )




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     config_and_inputs
     UpperCamelCase_									=     {'pixel_values': pixel_values}
     return config, inputs_dict




@require_torch
class 						_a       (  UpperCAmelCase__						,       UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





  A_						=   (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
  A_						=   (
      {"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification}
      if is_torch_available()
      else {}
  )

  A_						=   False
  A_						=   False
  A_						=   False
  A_						=   False




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     ViTMSNModelTester(self )
     UpperCamelCase_									=     ConfigTester(self		,		config_class=_UpperCAmelCase		,		has_text_modality=_UpperCAmelCase		,		hidden_size=37 )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     self.config_tester.run_common_tests()




  @unittest.skip(reason='ViTMSN does not use inputs_embeds' )
  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     pass




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        self.assertIsInstance(model.get_input_embeddings()		,		(nn.Module) )
        UpperCamelCase_									=     model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(_UpperCAmelCase		,		nn.Linear ) )




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

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

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




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase )




  @slow
  def    _UpperCAmelCase     (     self )			-> Dict:
     for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase_									=     ViTMSNModel.from_pretrained(_UpperCAmelCase )
        self.assertIsNotNone(_UpperCAmelCase )






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


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






  """simple docstring"""





  @cached_property
  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     return ViTImageProcessor.from_pretrained('facebook/vit-msn-small' ) if is_vision_available() else None




  @slow
  def    _UpperCAmelCase     (     self )			-> List[str]:
     torch.manual_seed(2 )
     UpperCamelCase_									=     ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small' ).to(_UpperCAmelCase )

     UpperCamelCase_									=     self.default_image_processor
     UpperCamelCase_									=     prepare_img()
     UpperCamelCase_									=     image_processor(images=_UpperCAmelCase		,		return_tensors='pt' ).to(_UpperCAmelCase )

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

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

     UpperCamelCase_									=     torch.tensor([-0.0_8_0_3, -0.4_4_5_4, -0.2_3_7_5] ).to(_UpperCAmelCase )

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





