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


lowercase__  :      Optional[Any]        =					logging.get_logger(__name__)







class lowerCamelCase							(	lowerCamelCase					):




  '''simple docstring'''



  lowerCAmelCase__										=	['''input_features''', '''attention_mask''']






  def __init__(      self			:       Tuple  ,							UpperCAmelCase__			:       List[Any]=80  ,							UpperCAmelCase__			:       List[str]=1_6000  ,							UpperCAmelCase__			:       Dict=80  ,							UpperCAmelCase__			:       Optional[int]=0.0  ,							UpperCAmelCase__			:       List[str]=True  ,							UpperCAmelCase__			:       Optional[int]=True  ,							UpperCAmelCase__			:       List[Any]=True  ,							**UpperCAmelCase__			:       Union[str, Any]  ,							)				->Optional[int]:
        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  lowerCAmelCase__ (      self			:       List[Any]  ,							UpperCAmelCase__			:       np.ndarray  ,							)				->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  lowerCAmelCase__ (      UpperCAmelCase__			:       np.ndarray  ,							UpperCAmelCase__			:       int  ,							UpperCAmelCase__			:       Optional[bool] = True  ,							UpperCAmelCase__			:       Optional[bool] = True  ,							UpperCAmelCase__			:       float = 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  lowerCAmelCase__ (      self			:       int  ,							UpperCAmelCase__			:       List[np.ndarray]  ,							UpperCAmelCase__			:       Optional[np.ndarray] = 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			:       Optional[int]  ,							UpperCAmelCase__			:       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]  ,							UpperCAmelCase__			:       Union[bool, str, PaddingStrategy] = False  ,							UpperCAmelCase__			:       Optional[int] = None  ,							UpperCAmelCase__			:       bool = False  ,							UpperCAmelCase__			:       Optional[int] = None  ,							UpperCAmelCase__			:       Optional[Union[str, TensorType]] = None  ,							UpperCAmelCase__			:       Optional[int] = None  ,							UpperCAmelCase__			:       Optional[bool] = None  ,							**UpperCAmelCase__			:       Optional[int]  ,							)				->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






'''simple docstring'''
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


lowercase__  :      Union[str, Any]        =					{
    "configuration_mobilevit": ["MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTConfig", "MobileViTOnnxConfig"],
}

try:
      if not is_vision_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__  :      Union[str, Any]        =					["MobileViTFeatureExtractor"]
      lowercase__  :      List[Any]        =					["MobileViTImageProcessor"]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__  :      Dict        =					[
          "MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
          "MobileViTForImageClassification",
          "MobileViTForSemanticSegmentation",
          "MobileViTModel",
          "MobileViTPreTrainedModel",
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__  :      Optional[int]        =					[
          "TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
          "TFMobileViTForImageClassification",
          "TFMobileViTForSemanticSegmentation",
          "TFMobileViTModel",
          "TFMobileViTPreTrainedModel",
      ]

if TYPE_CHECKING:
      from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig

      try:
            if not is_vision_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .feature_extraction_mobilevit import MobileViTFeatureExtractor
            from .image_processing_mobilevit import MobileViTImageProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_mobilevit import (
                MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
                MobileViTForImageClassification,
                MobileViTForSemanticSegmentation,
                MobileViTModel,
                MobileViTPreTrainedModel,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_mobilevit import (
                TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
                TFMobileViTForImageClassification,
                TFMobileViTForSemanticSegmentation,
                TFMobileViTModel,
                TFMobileViTPreTrainedModel,
            )


else:
      import sys

      lowercase__  :      int        =					_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)





