






"""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 TensorType, logging


UpperCamelCase											=     logging.get_logger(__name__)




class  lowercase_     (lowerCAmelCase_  ):
      A__						:		int							      =					['''input_values''', '''attention_mask''']






      def __init__(     self  ,  a_=1  ,  a_=1_6_0_0_0  ,  a_=1_2_8  ,  a_=1_0_2_4  ,  a_=0.0  ,  a_=True  ,  a_=-4.2_677_393  ,  a_=4.5_689_974  ,  a_=False  ,  **a_  ,  )						->Union[str, Any]:







        '''simple docstring'''


        super().__init__(feature_size=__UpperCamelCase  ,  sampling_rate=__UpperCamelCase  ,  padding_value=__UpperCamelCase  ,  **__UpperCamelCase						)
        _a					      =						num_mel_bins
        _a					      =						max_length
        _a					      =						do_normalize
        _a					      =						mean
        _a					      =						std
        _a					      =						return_attention_mask






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







        '''simple docstring'''


        _a					      =						torch.from_numpy(__UpperCamelCase						).unsqueeze(0						)
        _a					      =						ta_kaldi.fbank(
            __UpperCamelCase  ,  htk_compat=__UpperCamelCase  ,  sample_frequency=self.sampling_rate  ,  use_energy=__UpperCamelCase  ,  window_type="hanning"  ,  num_mel_bins=self.num_mel_bins  ,  dither=0.0  ,  frame_shift=1_0  ,  )

        _a					      =						fbank.shape[0]
        _a					      =						max_length - n_frames

        # pad or truncate, depending on difference
        if difference > 0:
          _a					      =						torch.nn.ZeroPadad((0, 0, 0, difference)						)
          _a					      =						pad_module(__UpperCamelCase						)
        elif difference < 0:
          _a					      =						fbank[0:max_length, :]

        _a					      =						fbank.numpy()

        return fbank






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







        '''simple docstring'''


        return (input_values - (self.mean)) / (self.std * 2)






      def __call__(     self  ,  a_  ,  a_ = None  ,  a_ = None  ,  **a_  ,  )						->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					      =						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}'''						)
        _a					      =						is_batched_numpy or (
            isinstance(__UpperCamelCase  ,  (list, tuple)						) and (isinstance(raw_speech[0]  ,  (np.ndarray, tuple, list)						))
        )

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

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

        # extract fbank features and pad/truncate to max_length
        _a					      =						[self._extract_fbank_features(__UpperCamelCase  ,  max_length=self.max_length						) for waveform in raw_speech]

        # convert into BatchFeature
        _a					      =						BatchFeature({"input_values": features}						)

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

        # normalization
        if self.do_normalize:
          _a					      =						[self.normalize(__UpperCamelCase						) for feature in input_values]

        if return_tensors is not None:
          _a					      =						padded_inputs.convert_to_tensors(__UpperCamelCase						)

        return padded_inputs




"""simple docstring"""




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


A__   :						Optional[Any] 							=     {"""configuration_vilt""": ["""VILT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViltConfig"""]}

try:
    if not is_vision_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    A__   :						List[Any] 							=     ["""ViltFeatureExtractor"""]
    A__   :						Any 							=     ["""ViltImageProcessor"""]
    A__   :						int 							=     ["""ViltProcessor"""]

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    A__   :						str 							=     [
        """VILT_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """ViltForImageAndTextRetrieval""",
        """ViltForImagesAndTextClassification""",
        """ViltForTokenClassification""",
        """ViltForMaskedLM""",
        """ViltForQuestionAnswering""",
        """ViltLayer""",
        """ViltModel""",
        """ViltPreTrainedModel""",
    ]


if TYPE_CHECKING:
    from .configuration_vilt import VILT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViltConfig

    try:
        if not is_vision_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .feature_extraction_vilt import ViltFeatureExtractor
        from .image_processing_vilt import ViltImageProcessor
        from .processing_vilt import ViltProcessor

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_vilt import (
            VILT_PRETRAINED_MODEL_ARCHIVE_LIST,
            ViltForImageAndTextRetrieval,
            ViltForImagesAndTextClassification,
            ViltForMaskedLM,
            ViltForQuestionAnswering,
            ViltForTokenClassification,
            ViltLayer,
            ViltModel,
            ViltPreTrainedModel,
        )


else:
    import sys

    A__   :						Any 							=     _LazyModule(__name__, globals()["""__file__"""], _import_structure)



