






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


SCREAMING_SNAKE_CASE__       :			Dict			      =						logging.get_logger(__name__)







class   __lowerCAmelCase			(					_UpperCamelCase  ):
   _UpperCamelCase :						Any     		=				["""input_features""", """attention_mask"""]





   def __init__( self					,			snake_case=80					,			snake_case=16_000					,			snake_case=80					,			snake_case=0.0					,			snake_case=True					,			snake_case=True					,			snake_case=True					,			**snake_case					,			)				->  List[str]:
      """simple docstring"""





      super().__init__(feature_size=snake_case					,			sampling_rate=snake_case					,			padding_value=snake_case					,			**snake_case      )
      a__	:						Tuple      		=  num_mel_bins
      a__	:						Dict      		=  do_ceptral_normalize
      a__	:						Any      		=  normalize_means
      a__	:						List[Any]      		=  normalize_vars
      a__	:						str      		=  True





   def 	_snake_case ( self					,			snake_case					,			)				->  np.ndarray:
      """simple docstring"""





      a__	:						Any      		=  waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
      a__	:						Tuple      		=  torch.from_numpy(snake_case      ).unsqueeze(0      )
      a__	:						Optional[Any]      		=  ta_kaldi.fbank(snake_case					,			num_mel_bins=self.num_mel_bins					,			sample_frequency=self.sampling_rate      )
      return features.numpy()





   @staticmethod
   def 	_snake_case ( snake_case					,			snake_case					,			snake_case = True					,			snake_case = True					,			snake_case = 0.0					,			)				->  np.ndarray:
      """simple docstring"""





      if normalize_means:
         a__	:						Optional[Any]      		=  x[:input_length].mean(axis=0      )
         a__	:						Any      		=  np.subtract(snake_case					,			snake_case      )
      if normalize_vars:
         a__	:						Union[str, Any]      		=  x[:input_length].std(axis=0      )
         a__	:						Tuple      		=  np.divide(snake_case					,			snake_case      )

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

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

      return x





   def 	_snake_case ( self					,			snake_case					,			snake_case = None      )				->  List[np.ndarray]:
      """simple docstring"""





      a__	:						List[str]      		=  attention_mask.sum(-1      ) if attention_mask is not None else [x.shape[0] for x in input_features]
      return [
          self.utterance_cmvn(snake_case					,			snake_case					,			self.normalize_means					,			self.normalize_vars					,			self.padding_value      )
          for x, n in zip(snake_case					,			snake_case      )
      ]





   def __call__( self					,			snake_case					,			snake_case = False					,			snake_case = None					,			snake_case = False					,			snake_case = None					,			snake_case = None					,			snake_case = None					,			snake_case = None					,			**snake_case					,			)				->  BatchFeature:
      """simple docstring"""





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

      a__	:						str      		=  isinstance(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}"""      )
      a__	:						Union[str, Any]      		=  is_batched_numpy or (
          isinstance(snake_case					,			(list, tuple)      ) and (isinstance(raw_speech[0]					,			(np.ndarray, tuple, list)      ))
      )

      if is_batched:
         a__	:						int      		=  [np.asarray(snake_case					,			dtype=np.floataa      ) for speech in raw_speech]
      elif not is_batched and not isinstance(snake_case					,			np.ndarray      ):
         a__	:						Optional[int]      		=  np.asarray(snake_case					,			dtype=np.floataa      )
      elif isinstance(snake_case					,			np.ndarray      ) and raw_speech.dtype is np.dtype(np.floataa      ):
         a__	:						Any      		=  raw_speech.astype(np.floataa      )

      # always return batch
      if not is_batched:
         a__	:						Optional[int]      		=  [raw_speech]

      # extract fbank features
      a__	:						List[Any]      		=  [self._extract_fbank_features(snake_case      ) for waveform in raw_speech]

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

      a__	:						List[Any]      		=  self.pad(
          snake_case					,			padding=snake_case					,			max_length=snake_case					,			truncation=snake_case					,			pad_to_multiple_of=snake_case					,			return_attention_mask=snake_case					,			**snake_case					,			)

      # make sure list is in array format
      a__	:						Dict      		=  padded_inputs.get("input_features"      )
      if isinstance(input_features[0]					,			snake_case      ):
         a__	:						Optional[int]      		=  [np.asarray(snake_case					,			dtype=np.floataa      ) for feature in input_features]

      a__	:						Union[str, Any]      		=  padded_inputs.get("attention_mask"      )
      if attention_mask is not None:
         a__	:						int      		=  [np.asarray(snake_case					,			dtype=np.intaa      ) for array in attention_mask]

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

      if return_tensors is not None:
         a__	:						Union[str, Any]      		=  padded_inputs.convert_to_tensors(snake_case      )

      return padded_inputs








import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import CONFIG_MAPPING


SCREAMING_SNAKE_CASE__       :			int			      =						logging.get_logger(__name__)







class   __lowerCAmelCase			(					_UpperCamelCase  ):
   _UpperCamelCase :						int     		=				"""upernet"""





   def __init__( self					,			snake_case=None					,			snake_case=512					,			snake_case=0.02					,			snake_case=[1, 2, 3, 6]					,			snake_case=True					,			snake_case=0.4					,			snake_case=384					,			snake_case=256					,			snake_case=1					,			snake_case=False					,			snake_case=255					,			**snake_case					,			)				->  Optional[Any]:
      """simple docstring"""





      super().__init__(**snake_case      )

      if backbone_config is None:
         logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."      )
         a__	:						List[str]      		=  CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"]      )
      elif isinstance(snake_case					,			snake_case      ):
         a__	:						Optional[int]      		=  backbone_config.get("model_type"      )
         a__	:						str      		=  CONFIG_MAPPING[backbone_model_type]
         a__	:						str      		=  config_class.from_dict(snake_case      )

      a__	:						int      		=  backbone_config
      a__	:						Optional[Any]      		=  hidden_size
      a__	:						Optional[Any]      		=  initializer_range
      a__	:						Tuple      		=  pool_scales
      a__	:						Optional[Any]      		=  use_auxiliary_head
      a__	:						Optional[Any]      		=  auxiliary_loss_weight
      a__	:						Dict      		=  auxiliary_in_channels
      a__	:						Optional[int]      		=  auxiliary_channels
      a__	:						Any      		=  auxiliary_num_convs
      a__	:						Any      		=  auxiliary_concat_input
      a__	:						int      		=  loss_ignore_index





   def 	_snake_case ( self      )				->  str:
      """simple docstring"""





      a__	:						Tuple      		=  copy.deepcopy(self.__dict__      )
      a__	:						Optional[Any]      		=  self.backbone_config.to_dict()
      a__	:						List[Any]      		=  self.__class__.model_type
      return output

