

from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


_SCREAMING_SNAKE_CASE					:  Tuple             =      [
    """openmmlab/upernet-convnext-tiny""",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
_SCREAMING_SNAKE_CASE					:  List[str]             =      """UperNetConfig"""






class 	UpperCAmelCase__		(	nn.Module	):






  """simple docstring"""


  def __init__(							self						:		int     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		Union[int, Tuple[int, int]]     ,       __lowerCamelCase						:		Union[int, Tuple[int, int], str] = 0     ,       __lowerCamelCase						:		bool = False     ,       __lowerCamelCase						:		Union[int, Tuple[int, int]] = 1     ,       )		->							None:
         super().__init__()
         SCREAMING_SNAKE_CASE__   =   nn.Convad(
             in_channels=__lowerCamelCase     ,       out_channels=__lowerCamelCase     ,       kernel_size=__lowerCamelCase     ,       padding=__lowerCamelCase     ,       bias=__lowerCamelCase     ,       dilation=__lowerCamelCase     ,       )
         SCREAMING_SNAKE_CASE__   =   nn.BatchNormad(__lowerCamelCase )
         SCREAMING_SNAKE_CASE__   =   nn.ReLU()







  def 				lowercase_		(							self						:		Tuple     ,       __lowerCamelCase						:		torch.Tensor )		->							torch.Tensor:
         SCREAMING_SNAKE_CASE__   =   self.conv(__lowerCamelCase )
         SCREAMING_SNAKE_CASE__   =   self.batch_norm(__lowerCamelCase )
         SCREAMING_SNAKE_CASE__   =   self.activation(__lowerCamelCase )

         return output






class 	UpperCAmelCase__		(	nn.Module	):






  """simple docstring"""


  def __init__(							self						:		Optional[Any]     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		int )		->							None:
         super().__init__()
         SCREAMING_SNAKE_CASE__   =   [
             nn.AdaptiveAvgPoolad(__lowerCamelCase ),
             UperNetConvModule(__lowerCamelCase     ,       __lowerCamelCase     ,       kernel_size=1 ),
         ]
         for i, layer in enumerate(self.layers ):
                self.add_module(str(__lowerCamelCase )     ,       __lowerCamelCase )







  def 				lowercase_		(							self						:		Union[str, Any]     ,       __lowerCamelCase						:		torch.Tensor )		->							torch.Tensor:
         SCREAMING_SNAKE_CASE__   =   input
         for layer in self.layers:
                SCREAMING_SNAKE_CASE__   =   layer(__lowerCamelCase )
         return hidden_state






class 	UpperCAmelCase__		(	nn.Module	):






  """simple docstring"""


  def __init__(							self						:		Tuple     ,       __lowerCamelCase						:		Tuple[int, ...]     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		bool )		->							None:
         super().__init__()
         SCREAMING_SNAKE_CASE__   =   pool_scales
         SCREAMING_SNAKE_CASE__   =   align_corners
         SCREAMING_SNAKE_CASE__   =   in_channels
         SCREAMING_SNAKE_CASE__   =   channels
         SCREAMING_SNAKE_CASE__   =   []
         for i, pool_scale in enumerate(__lowerCamelCase ):
                SCREAMING_SNAKE_CASE__   =   UperNetPyramidPoolingBlock(pool_scale=__lowerCamelCase     ,       in_channels=__lowerCamelCase     ,       channels=__lowerCamelCase )
                self.blocks.append(__lowerCamelCase )
                self.add_module(str(__lowerCamelCase )     ,       __lowerCamelCase )







  def 				lowercase_		(							self						:		Optional[int]     ,       __lowerCamelCase						:		torch.Tensor )		->							List[torch.Tensor]:
         SCREAMING_SNAKE_CASE__   =   []
         for ppm in self.blocks:
                SCREAMING_SNAKE_CASE__   =   ppm(__lowerCamelCase )
                SCREAMING_SNAKE_CASE__   =   nn.functional.interpolate(
                    __lowerCamelCase     ,       size=x.size()[2:]     ,       mode='''bilinear'''     ,       align_corners=self.align_corners )
                ppm_outs.append(__lowerCamelCase )
         return ppm_outs






class 	UpperCAmelCase__		(	nn.Module	):






  """simple docstring"""


  def __init__(							self						:		str     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		Any )		->							int:
         super().__init__()

         SCREAMING_SNAKE_CASE__   =   config
         SCREAMING_SNAKE_CASE__   =   config.pool_scales  # e.g. (1, 2, 3, 6)
         SCREAMING_SNAKE_CASE__   =   in_channels
         SCREAMING_SNAKE_CASE__   =   config.hidden_size
         SCREAMING_SNAKE_CASE__   =   False
         SCREAMING_SNAKE_CASE__   =   nn.Convad(self.channels     ,       config.num_labels     ,       kernel_size=1 )

         # PSP Module
         SCREAMING_SNAKE_CASE__   =   UperNetPyramidPoolingModule(
             self.pool_scales     ,       self.in_channels[-1]     ,       self.channels     ,       align_corners=self.align_corners     ,       )
         SCREAMING_SNAKE_CASE__   =   UperNetConvModule(
             self.in_channels[-1] + len(self.pool_scales ) * self.channels     ,       self.channels     ,       kernel_size=3     ,       padding=1     ,       )
         # FPN Module
         SCREAMING_SNAKE_CASE__   =   nn.ModuleList()
         SCREAMING_SNAKE_CASE__   =   nn.ModuleList()
         for in_channels in self.in_channels[:-1]:  # skip the top layer
                SCREAMING_SNAKE_CASE__   =   UperNetConvModule(__lowerCamelCase     ,       self.channels     ,       kernel_size=1 )
                SCREAMING_SNAKE_CASE__   =   UperNetConvModule(self.channels     ,       self.channels     ,       kernel_size=3     ,       padding=1 )
                self.lateral_convs.append(__lowerCamelCase )
                self.fpn_convs.append(__lowerCamelCase )

         SCREAMING_SNAKE_CASE__   =   UperNetConvModule(
             len(self.in_channels ) * self.channels     ,       self.channels     ,       kernel_size=3     ,       padding=1     ,       )






  def 				lowercase_		(							self						:		Tuple )		->							List[Any]:
         self.apply(self._init_weights )






  def 				lowercase_		(							self						:		Tuple     ,       __lowerCamelCase						:		Dict )		->							str:
         if isinstance(__lowerCamelCase     ,       nn.Convad ):
                module.weight.data.normal_(mean=0.0     ,       std=self.config.initializer_range )
                if module.bias is not None:
                       module.bias.data.zero_()






  def 				lowercase_		(							self						:		Optional[int]     ,       __lowerCamelCase						:		Optional[int] )		->							Optional[int]:
         SCREAMING_SNAKE_CASE__   =   inputs[-1]
         SCREAMING_SNAKE_CASE__   =   [x]
         psp_outs.extend(self.psp_modules(__lowerCamelCase ) )
         SCREAMING_SNAKE_CASE__   =   torch.cat(__lowerCamelCase     ,       dim=1 )
         SCREAMING_SNAKE_CASE__   =   self.bottleneck(__lowerCamelCase )

         return output







  def 				lowercase_		(							self						:		str     ,       __lowerCamelCase						:		torch.Tensor )		->							torch.Tensor:
         # build laterals
         SCREAMING_SNAKE_CASE__   =   [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )]

         laterals.append(self.psp_forward(__lowerCamelCase ) )

         # build top-down path
         SCREAMING_SNAKE_CASE__   =   len(__lowerCamelCase )
         for i in range(used_backbone_levels - 1     ,       0     ,       -1 ):
                SCREAMING_SNAKE_CASE__   =   laterals[i - 1].shape[2:]
                SCREAMING_SNAKE_CASE__   =   laterals[i - 1] + nn.functional.interpolate(
                    laterals[i]     ,       size=__lowerCamelCase     ,       mode='''bilinear'''     ,       align_corners=self.align_corners )

         # build outputs
         SCREAMING_SNAKE_CASE__   =   [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )]
         # append psp feature
         fpn_outs.append(laterals[-1] )

         for i in range(used_backbone_levels - 1     ,       0     ,       -1 ):
                SCREAMING_SNAKE_CASE__   =   nn.functional.interpolate(
                    fpn_outs[i]     ,       size=fpn_outs[0].shape[2:]     ,       mode='''bilinear'''     ,       align_corners=self.align_corners )
         SCREAMING_SNAKE_CASE__   =   torch.cat(__lowerCamelCase     ,       dim=1 )
         SCREAMING_SNAKE_CASE__   =   self.fpn_bottleneck(__lowerCamelCase )
         SCREAMING_SNAKE_CASE__   =   self.classifier(__lowerCamelCase )

         return output






class 	UpperCAmelCase__		(	nn.Module	):






  """simple docstring"""


  def __init__(							self						:		Optional[int]     ,       __lowerCamelCase						:		Optional[int]     ,       __lowerCamelCase						:		int = 2     ,       __lowerCamelCase						:		int = 3     ,       __lowerCamelCase						:		Union[int, Tuple[int, int]] = 1 )		->							None:
         super().__init__()

         SCREAMING_SNAKE_CASE__   =   config
         SCREAMING_SNAKE_CASE__   =   config.auxiliary_in_channels
         SCREAMING_SNAKE_CASE__   =   config.auxiliary_channels
         SCREAMING_SNAKE_CASE__   =   config.auxiliary_num_convs
         SCREAMING_SNAKE_CASE__   =   config.auxiliary_concat_input
         SCREAMING_SNAKE_CASE__   =   in_index

         SCREAMING_SNAKE_CASE__   =   (kernel_size // 2) * dilation
         SCREAMING_SNAKE_CASE__   =   []
         convs.append(
             UperNetConvModule(
                 self.in_channels     ,       self.channels     ,       kernel_size=__lowerCamelCase     ,       padding=__lowerCamelCase     ,       dilation=__lowerCamelCase ) )
         for i in range(self.num_convs - 1 ):
                convs.append(
                    UperNetConvModule(
                        self.channels     ,       self.channels     ,       kernel_size=__lowerCamelCase     ,       padding=__lowerCamelCase     ,       dilation=__lowerCamelCase ) )
         if self.num_convs == 0:
                SCREAMING_SNAKE_CASE__   =   nn.Identity()
         else:
                SCREAMING_SNAKE_CASE__   =   nn.Sequential(*__lowerCamelCase )
         if self.concat_input:
                SCREAMING_SNAKE_CASE__   =   UperNetConvModule(
                    self.in_channels + self.channels     ,       self.channels     ,       kernel_size=__lowerCamelCase     ,       padding=kernel_size // 2 )

         SCREAMING_SNAKE_CASE__   =   nn.Convad(self.channels     ,       config.num_labels     ,       kernel_size=1 )






  def 				lowercase_		(							self						:		Tuple )		->							Tuple:
         self.apply(self._init_weights )






  def 				lowercase_		(							self						:		Union[str, Any]     ,       __lowerCamelCase						:		List[Any] )		->							List[str]:
         if isinstance(__lowerCamelCase     ,       nn.Convad ):
                module.weight.data.normal_(mean=0.0     ,       std=self.config.initializer_range )
                if module.bias is not None:
                       module.bias.data.zero_()







  def 				lowercase_		(							self						:		Tuple     ,       __lowerCamelCase						:		torch.Tensor )		->							torch.Tensor:
         # just take the relevant feature maps
         SCREAMING_SNAKE_CASE__   =   encoder_hidden_states[self.in_index]
         SCREAMING_SNAKE_CASE__   =   self.convs(__lowerCamelCase )
         if self.concat_input:
                SCREAMING_SNAKE_CASE__   =   self.conv_cat(torch.cat([hidden_states, output]     ,       dim=1 ) )
         SCREAMING_SNAKE_CASE__   =   self.classifier(__lowerCamelCase )
         return output






class 	UpperCAmelCase__		(	__UpperCamelCase	):






  """simple docstring"""


  a									= UperNetConfig
  a									= "pixel_values"
  a									= True






  def 				lowercase_		(							self						:		Optional[Any]     ,       __lowerCamelCase						:		Union[str, Any] )		->							Optional[int]:
         if isinstance(__lowerCamelCase     ,       __lowerCamelCase ):
                module.backbone.init_weights()
                module.decode_head.init_weights()
                module.auxiliary_head.init_weights()






  def 				lowercase_		(							self						:		str )		->							Tuple:
         self.backbone.init_weights()
         self.decode_head.init_weights()
         self.auxiliary_head.init_weights()







  def 				lowercase_		(							self						:		Any     ,       __lowerCamelCase						:		Dict     ,       __lowerCamelCase						:		Optional[int]=False )		->							str:
         if isinstance(__lowerCamelCase     ,       __lowerCamelCase ):
                SCREAMING_SNAKE_CASE__   =   value



_SCREAMING_SNAKE_CASE					:  List[Any]             =      R"""
    Parameters:
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.
        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

_SCREAMING_SNAKE_CASE					:  Union[str, Any]             =      R"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See
            `attentions` under returned tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under
            returned tensors for more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""






@add_start_docstrings(
    "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes."						,					__UpperCamelCase						,					)
class 	UpperCAmelCase__		(	__UpperCamelCase	):






  """simple docstring"""


  def __init__(							self						:		Optional[int]     ,       __lowerCamelCase						:		Union[str, Any] )		->							Dict:
         super().__init__(__lowerCamelCase )

         SCREAMING_SNAKE_CASE__   =   AutoBackbone.from_config(config.backbone_config )

         # Semantic segmentation head(s)
         SCREAMING_SNAKE_CASE__   =   UperNetHead(__lowerCamelCase     ,       in_channels=self.backbone.channels )
         SCREAMING_SNAKE_CASE__   =   UperNetFCNHead(__lowerCamelCase ) if config.use_auxiliary_head else None

         # Initialize weights and apply final processing
         self.post_init()







  @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('''batch_size, sequence_length''' ) )
  @replace_return_docstrings(output_type=__lowerCamelCase     ,       config_class=_CONFIG_FOR_DOC )
  def 				lowercase_		(							self						:		Union[str, Any]     ,       __lowerCamelCase						:		Optional[torch.Tensor] = None     ,       __lowerCamelCase						:		Optional[bool] = None     ,       __lowerCamelCase						:		Optional[bool] = None     ,       __lowerCamelCase						:		Optional[torch.Tensor] = None     ,       __lowerCamelCase						:		Optional[bool] = None     ,       )		->							Union[tuple, SemanticSegmenterOutput]:
         SCREAMING_SNAKE_CASE__   =   return_dict if return_dict is not None else self.config.use_return_dict
         SCREAMING_SNAKE_CASE__   =   (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         SCREAMING_SNAKE_CASE__   =   output_attentions if output_attentions is not None else self.config.output_attentions

         SCREAMING_SNAKE_CASE__   =   self.backbone.forward_with_filtered_kwargs(
             __lowerCamelCase     ,       output_hidden_states=__lowerCamelCase     ,       output_attentions=__lowerCamelCase )
         SCREAMING_SNAKE_CASE__   =   outputs.feature_maps

         SCREAMING_SNAKE_CASE__   =   self.decode_head(__lowerCamelCase )
         SCREAMING_SNAKE_CASE__   =   nn.functional.interpolate(__lowerCamelCase     ,       size=pixel_values.shape[2:]     ,       mode='''bilinear'''     ,       align_corners=__lowerCamelCase )

         SCREAMING_SNAKE_CASE__   =   None
         if self.auxiliary_head is not None:
                SCREAMING_SNAKE_CASE__   =   self.auxiliary_head(__lowerCamelCase )
                SCREAMING_SNAKE_CASE__   =   nn.functional.interpolate(
                    __lowerCamelCase     ,       size=pixel_values.shape[2:]     ,       mode='''bilinear'''     ,       align_corners=__lowerCamelCase )

         SCREAMING_SNAKE_CASE__   =   None
         if labels is not None:
                if self.config.num_labels == 1:
                       raise ValueError('''The number of labels should be greater than one''' )
                else:
                       # compute weighted loss
                       SCREAMING_SNAKE_CASE__   =   CrossEntropyLoss(ignore_index=self.config.loss_ignore_index )
                       SCREAMING_SNAKE_CASE__   =   loss_fct(__lowerCamelCase     ,       __lowerCamelCase )
                       SCREAMING_SNAKE_CASE__   =   loss_fct(__lowerCamelCase     ,       __lowerCamelCase )
                       SCREAMING_SNAKE_CASE__   =   main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

         if not return_dict:
                if output_hidden_states:
                       SCREAMING_SNAKE_CASE__   =   (logits,) + outputs[1:]
                else:
                       SCREAMING_SNAKE_CASE__   =   (logits,) + outputs[2:]
                return ((loss,) + output) if loss is not None else output

         return SemanticSegmenterOutput(
             loss=__lowerCamelCase     ,       logits=__lowerCamelCase     ,       hidden_states=outputs.hidden_states     ,       attentions=outputs.attentions     ,       )





import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np

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


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






class 	UpperCAmelCase__		(	A__	):






  """simple docstring"""


  a									= ["input_features"]






  def __init__(							self						:		Dict     ,       __lowerCamelCase						:		Tuple=80     ,       __lowerCamelCase						:		List[Any]=1_6000     ,       __lowerCamelCase						:		Optional[int]=160     ,       __lowerCamelCase						:		List[str]=30     ,       __lowerCamelCase						:		List[Any]=400     ,       __lowerCamelCase						:		Union[str, Any]=0.0     ,       __lowerCamelCase						:		str=False     ,       **__lowerCamelCase						:		List[str]     ,       )		->							Any:
       super().__init__(
           feature_size=__lowerCamelCase     ,       sampling_rate=__lowerCamelCase     ,       padding_value=__lowerCamelCase     ,       return_attention_mask=__lowerCamelCase     ,       **__lowerCamelCase     ,       )
       SCREAMING_SNAKE_CASE__   =   n_fft
       SCREAMING_SNAKE_CASE__   =   hop_length
       SCREAMING_SNAKE_CASE__   =   chunk_length
       SCREAMING_SNAKE_CASE__   =   chunk_length * sampling_rate
       SCREAMING_SNAKE_CASE__   =   self.n_samples // hop_length
       SCREAMING_SNAKE_CASE__   =   sampling_rate
       SCREAMING_SNAKE_CASE__   =   mel_filter_bank(
           num_frequency_bins=1 + n_fft // 2     ,       num_mel_filters=__lowerCamelCase     ,       min_frequency=0.0     ,       max_frequency=8000.0     ,       sampling_rate=__lowerCamelCase     ,       norm='''slaney'''     ,       mel_scale='''slaney'''     ,       )






  def 				lowercase_		(							self						:		int     ,       __lowerCamelCase						:		np.array )		->							np.ndarray:
       SCREAMING_SNAKE_CASE__   =   spectrogram(
           __lowerCamelCase     ,       window_function(self.n_fft     ,       '''hann''' )     ,       frame_length=self.n_fft     ,       hop_length=self.hop_length     ,       power=2.0     ,       mel_filters=self.mel_filters     ,       log_mel='''log10'''     ,       )
       SCREAMING_SNAKE_CASE__   =   log_spec[:, :-1]
       SCREAMING_SNAKE_CASE__   =   np.maximum(__lowerCamelCase     ,       log_spec.max() - 8.0 )
       SCREAMING_SNAKE_CASE__   =   (log_spec + 4.0) / 4.0
       return log_spec






  @staticmethod
  # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
  def 				lowercase_		(							__lowerCamelCase						:		List[np.ndarray]     ,       __lowerCamelCase						:		List[np.ndarray]     ,       __lowerCamelCase						:		float = 0.0 )		->							List[np.ndarray]:
       if attention_mask is not None:
            SCREAMING_SNAKE_CASE__   =   np.array(__lowerCamelCase     ,       np.intaa )
            SCREAMING_SNAKE_CASE__   =   []

            for vector, length in zip(__lowerCamelCase     ,       attention_mask.sum(-1 ) ):
                 SCREAMING_SNAKE_CASE__   =   (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 )
                 if length < normed_slice.shape[0]:
                      SCREAMING_SNAKE_CASE__   =   padding_value

                 normed_input_values.append(__lowerCamelCase )
       else:
            SCREAMING_SNAKE_CASE__   =   [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values]

       return normed_input_values






  def __call__(							self						:		List[str]     ,       __lowerCamelCase						:		Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]     ,       __lowerCamelCase						:		bool = True     ,       __lowerCamelCase						:		Optional[int] = None     ,       __lowerCamelCase						:		Optional[Union[str, TensorType]] = None     ,       __lowerCamelCase						:		Optional[bool] = None     ,       __lowerCamelCase						:		Optional[str] = "max_length"     ,       __lowerCamelCase						:		Optional[int] = None     ,       __lowerCamelCase						:		Optional[int] = None     ,       __lowerCamelCase						:		Optional[bool] = None     ,       **__lowerCamelCase						:		List[str]     ,       )		->							BatchFeature:

       if sampling_rate is not None:
            if sampling_rate != self.sampling_rate:
                 raise ValueError(
                     f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'''
                     f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'''
                     f''' was sampled 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.''' )

       SCREAMING_SNAKE_CASE__   =   isinstance(__lowerCamelCase     ,       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}''' )
       SCREAMING_SNAKE_CASE__   =   is_batched_numpy or (
           isinstance(__lowerCamelCase     ,       (list, tuple) ) and (isinstance(raw_speech[0]     ,       (np.ndarray, tuple, list) ))
       )

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

       # always return batch
       if not is_batched:
            SCREAMING_SNAKE_CASE__   =   [np.asarray([raw_speech] ).T]

       SCREAMING_SNAKE_CASE__   =   BatchFeature({'''input_features''': raw_speech} )

       # convert into correct format for padding

       SCREAMING_SNAKE_CASE__   =   self.pad(
           __lowerCamelCase     ,       padding=__lowerCamelCase     ,       max_length=max_length if max_length else self.n_samples     ,       truncation=__lowerCamelCase     ,       pad_to_multiple_of=__lowerCamelCase     ,       return_attention_mask=return_attention_mask or do_normalize     ,       )

       # zero-mean and unit-variance normalization
       if do_normalize:
            SCREAMING_SNAKE_CASE__   =   self.zero_mean_unit_var_norm(
                padded_inputs['''input_features''']     ,       attention_mask=padded_inputs['''attention_mask''']     ,       padding_value=self.padding_value     ,       )
            SCREAMING_SNAKE_CASE__   =   np.stack(padded_inputs['''input_features''']     ,       axis=0 )

       # make sure list is in array format
       SCREAMING_SNAKE_CASE__   =   padded_inputs.get('''input_features''' ).transpose(2     ,       0     ,       1 )

       SCREAMING_SNAKE_CASE__   =   [self._np_extract_fbank_features(__lowerCamelCase ) for waveform in input_features[0]]

       if isinstance(input_features[0]     ,       __lowerCamelCase ):
            SCREAMING_SNAKE_CASE__   =   [np.asarray(__lowerCamelCase     ,       dtype=np.floataa ) for feature in input_features]
       else:
            SCREAMING_SNAKE_CASE__   =   input_features

       if return_attention_mask:
            # rescale from sample (48000) to feature (3000)
            SCREAMING_SNAKE_CASE__   =   padded_inputs['''attention_mask'''][:, :: self.hop_length]

       if return_tensors is not None:
            SCREAMING_SNAKE_CASE__   =   padded_inputs.convert_to_tensors(__lowerCamelCase )

       return padded_inputs







  def 				lowercase_		(							self						:		str )		->							Dict[str, Any]:
       SCREAMING_SNAKE_CASE__   =   copy.deepcopy(self.__dict__ )
       SCREAMING_SNAKE_CASE__   =   self.__class__.__name__
       if "mel_filters" in output:
            del output["mel_filters"]
       return output


