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


__A								=			logging.get_logger(__name__)





class 	A							(				UpperCAmelCase__ ):
			lowerCamelCase							:							Optional[Any]										=     ['input_features', 'attention_mask']



			def __init__(    self				,   lowerCamelCase__=80				,   lowerCamelCase__=16_000				,   lowerCamelCase__=80				,   lowerCamelCase__=0.0				,   lowerCamelCase__=True				,   lowerCamelCase__=True				,   lowerCamelCase__=True				,   **lowerCamelCase__				,   )	->						Dict:




									'''simple docstring'''



									super().__init__(feature_size=_SCREAMING_SNAKE_CASE				,   sampling_rate=_SCREAMING_SNAKE_CASE				,   padding_value=_SCREAMING_SNAKE_CASE				,   **_SCREAMING_SNAKE_CASE				)
									lowercase__							       =				num_mel_bins
									lowercase__							       =				do_ceptral_normalize
									lowercase__							       =				normalize_means
									lowercase__							       =				normalize_vars
									lowercase__							       =				True



			def A__       (    self				,   lowerCamelCase__				,   )	->						np.ndarray:




									'''simple docstring'''



									lowercase__							       =				waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
									lowercase__							       =				torch.from_numpy(_SCREAMING_SNAKE_CASE				).unsqueeze(0				)
									lowercase__							       =				ta_kaldi.fbank(_SCREAMING_SNAKE_CASE				,   num_mel_bins=self.num_mel_bins				,   sample_frequency=self.sampling_rate				)
									return features.numpy()



			@staticmethod
			def A__       (    lowerCamelCase__				,   lowerCamelCase__				,   lowerCamelCase__ = True				,   lowerCamelCase__ = True				,   lowerCamelCase__ = 0.0				,   )	->						np.ndarray:




									'''simple docstring'''



									if normalize_means:
															lowercase__							       =				x[:input_length].mean(axis=0				)
															lowercase__							       =				np.subtract(_SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE				)
									if normalize_vars:
															lowercase__							       =				x[:input_length].std(axis=0				)
															lowercase__							       =				np.divide(_SCREAMING_SNAKE_CASE				,   _SCREAMING_SNAKE_CASE				)

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

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

									return x



			def A__       (    self				,   lowerCamelCase__				,   lowerCamelCase__ = None				)	->						List[np.ndarray]:




									'''simple docstring'''



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



			def __call__(    self				,   lowerCamelCase__				,   lowerCamelCase__ = False				,   lowerCamelCase__ = None				,   lowerCamelCase__ = False				,   lowerCamelCase__ = None				,   lowerCamelCase__ = None				,   lowerCamelCase__ = None				,   lowerCamelCase__ = None				,   **lowerCamelCase__				,   )	->						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."""				)

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

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

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

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

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

									lowercase__							       =				self.pad(
									    _SCREAMING_SNAKE_CASE				,   padding=_SCREAMING_SNAKE_CASE				,   max_length=_SCREAMING_SNAKE_CASE				,   truncation=_SCREAMING_SNAKE_CASE				,   pad_to_multiple_of=_SCREAMING_SNAKE_CASE				,   return_attention_mask=_SCREAMING_SNAKE_CASE				,   **_SCREAMING_SNAKE_CASE				,   )

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

									lowercase__							       =				padded_inputs.get("""attention_mask"""				)
									if attention_mask is not None:
															lowercase__							       =				[np.asarray(_SCREAMING_SNAKE_CASE				,   dtype=np.intaa				) for array in attention_mask]

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

									if return_tensors is not None:
															lowercase__							       =				padded_inputs.convert_to_tensors(_SCREAMING_SNAKE_CASE				)

									return padded_inputs











"""simple docstring"""
import copy
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


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

A:   Dict								=		{
    "microsoft/conditional-detr-resnet-50": (
        "https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json"
    ),
}



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):
   __lowerCAmelCase  :   Any						=						'conditional_detr'
   __lowerCAmelCase  :   Union[str, Any]						=						['past_key_values']
   __lowerCAmelCase  :   int						=						{
       'hidden_size': 'd_model',
       'num_attention_heads': 'encoder_attention_heads',
   }

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE=True      ,     _SCREAMING_SNAKE_CASE=None      ,     _SCREAMING_SNAKE_CASE=3      ,     _SCREAMING_SNAKE_CASE=300      ,     _SCREAMING_SNAKE_CASE=6      ,     _SCREAMING_SNAKE_CASE=2048      ,     _SCREAMING_SNAKE_CASE=8      ,     _SCREAMING_SNAKE_CASE=6      ,     _SCREAMING_SNAKE_CASE=2048      ,     _SCREAMING_SNAKE_CASE=8      ,     _SCREAMING_SNAKE_CASE=0.0      ,     _SCREAMING_SNAKE_CASE=0.0      ,     _SCREAMING_SNAKE_CASE=True      ,     _SCREAMING_SNAKE_CASE="relu"      ,     _SCREAMING_SNAKE_CASE=256      ,     _SCREAMING_SNAKE_CASE=0.1      ,     _SCREAMING_SNAKE_CASE=0.0      ,     _SCREAMING_SNAKE_CASE=0.0      ,     _SCREAMING_SNAKE_CASE=0.02      ,     _SCREAMING_SNAKE_CASE=1.0      ,     _SCREAMING_SNAKE_CASE=False      ,     _SCREAMING_SNAKE_CASE="sine"      ,     _SCREAMING_SNAKE_CASE="resnet50"      ,     _SCREAMING_SNAKE_CASE=True      ,     _SCREAMING_SNAKE_CASE=False      ,     _SCREAMING_SNAKE_CASE=2      ,     _SCREAMING_SNAKE_CASE=5      ,     _SCREAMING_SNAKE_CASE=2      ,     _SCREAMING_SNAKE_CASE=1      ,     _SCREAMING_SNAKE_CASE=1      ,     _SCREAMING_SNAKE_CASE=2      ,     _SCREAMING_SNAKE_CASE=5      ,     _SCREAMING_SNAKE_CASE=2      ,     _SCREAMING_SNAKE_CASE=0.25      ,     **_SCREAMING_SNAKE_CASE      ,     )  ->      Tuple:





    '''simple docstring'''




    if backbone_config is not None and use_timm_backbone:
     raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`."""						)

    if not use_timm_backbone:
     if backbone_config is None:
      logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""						)
      UpperCAmelCase	:					Tuple	=	CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""]						)
     elif isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						):
      UpperCAmelCase	:					str	=	backbone_config.get("""model_type"""						)
      UpperCAmelCase	:					int	=	CONFIG_MAPPING[backbone_model_type]
      UpperCAmelCase	:					Union[str, Any]	=	config_class.from_dict(_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Union[str, Any]	=	use_timm_backbone
    UpperCAmelCase	:					Optional[int]	=	backbone_config
    UpperCAmelCase	:					List[str]	=	num_channels
    UpperCAmelCase	:					Any	=	num_queries
    UpperCAmelCase	:					Union[str, Any]	=	d_model
    UpperCAmelCase	:					List[str]	=	encoder_ffn_dim
    UpperCAmelCase	:					Optional[int]	=	encoder_layers
    UpperCAmelCase	:					Union[str, Any]	=	encoder_attention_heads
    UpperCAmelCase	:					Optional[Any]	=	decoder_ffn_dim
    UpperCAmelCase	:					Any	=	decoder_layers
    UpperCAmelCase	:					Optional[int]	=	decoder_attention_heads
    UpperCAmelCase	:					Optional[int]	=	dropout
    UpperCAmelCase	:					Dict	=	attention_dropout
    UpperCAmelCase	:					Dict	=	activation_dropout
    UpperCAmelCase	:					Any	=	activation_function
    UpperCAmelCase	:					Any	=	init_std
    UpperCAmelCase	:					Tuple	=	init_xavier_std
    UpperCAmelCase	:					Optional[int]	=	encoder_layerdrop
    UpperCAmelCase	:					Any	=	decoder_layerdrop
    UpperCAmelCase	:					Any	=	encoder_layers
    UpperCAmelCase	:					Optional[Any]	=	auxiliary_loss
    UpperCAmelCase	:					List[Any]	=	position_embedding_type
    UpperCAmelCase	:					Union[str, Any]	=	backbone
    UpperCAmelCase	:					List[Any]	=	use_pretrained_backbone
    UpperCAmelCase	:					Dict	=	dilation
    # Hungarian matcher
    UpperCAmelCase	:					Optional[int]	=	class_cost
    UpperCAmelCase	:					List[str]	=	bbox_cost
    UpperCAmelCase	:					List[str]	=	giou_cost
    # Loss coefficients
    UpperCAmelCase	:					List[Any]	=	mask_loss_coefficient
    UpperCAmelCase	:					List[str]	=	dice_loss_coefficient
    UpperCAmelCase	:					Optional[int]	=	cls_loss_coefficient
    UpperCAmelCase	:					Union[str, Any]	=	bbox_loss_coefficient
    UpperCAmelCase	:					Union[str, Any]	=	giou_loss_coefficient
    UpperCAmelCase	:					int	=	focal_alpha
    super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      int:





    '''simple docstring'''




    return self.encoder_attention_heads

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      int:





    '''simple docstring'''




    return self.d_model




   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Any:





    '''simple docstring'''




    UpperCAmelCase	:					List[Any]	=	copy.deepcopy(self.__dict__						)
    if self.backbone_config is not None:
     UpperCAmelCase	:					Union[str, Any]	=	self.backbone_config.to_dict()
    UpperCAmelCase	:					Dict	=	self.__class__.model_type
    return output



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):
   __lowerCAmelCase  :   Any						=						version.parse('1.11' )

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Mapping[str, Mapping[int, str]]:





    '''simple docstring'''




    return OrderedDict(
        [
            ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
            ("""pixel_mask""", {0: """batch"""}),
        ]						)

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      float:





    '''simple docstring'''




    return 1E-5




   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      int:





    '''simple docstring'''




    return 12
