'''simple docstring'''






from math import ceil
from typing import List, Optional, Union

import numpy as np

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


_UpperCAmelCase    :     int         =       logging.get_logger(__name__)







class lowercase_       (		_UpperCamelCase			):







   """simple docstring"""

   __lowerCAmelCase         =   ["audio_values", "audio_mask"]
   def __init__(      self      :			Optional[int], UpperCamelCase__      :			Optional[Any]=20_48, UpperCamelCase__      :			Optional[Any]=1, UpperCamelCase__      :			Union[str, Any]=[16, 16], UpperCamelCase__      :			Optional[int]=1_28, UpperCamelCase__      :			Union[str, Any]=4_41_00, UpperCamelCase__      :			Dict=86, UpperCamelCase__      :			List[str]=20_48, UpperCamelCase__      :			Optional[int]=0.0, **UpperCamelCase__      :			Any, )  ->			List[Any]:
        super().__init__(
            feature_size=UpperCamelCase__, sampling_rate=UpperCamelCase__, padding_value=UpperCamelCase__, **UpperCamelCase__, )

        _A    		=  spectrogram_length
        _A    		=  num_channels
        _A    		=  patch_size
        _A    		=  feature_size // self.patch_size[1]
        _A    		=  n_fft
        _A    		=  sampling_rate // hop_length_to_sampling_rate
        _A    		=  sampling_rate
        _A    		=  padding_value
        _A    		=  mel_filter_bank(
            num_frequency_bins=1 + n_fft // 2, num_mel_filters=UpperCamelCase__, min_frequency=0.0, max_frequency=22_050.0, sampling_rate=UpperCamelCase__, norm='slaney', mel_scale='slaney', ).T
   def 	__UpperCAmelCase   (      self      :			List[Any], UpperCamelCase__      :			np.array     )  ->			np.ndarray:
        _A    		=  spectrogram(
            UpperCamelCase__, window_function(self.n_fft, 'hann'     ), frame_length=self.n_fft, hop_length=self.hop_length, power=2.0, mel_filters=self.mel_filters.T, log_mel='dB', db_range=80.0, )
        _A    		=  log_spec[:, :-1]
        _A    		=  log_spec - 20.0
        _A    		=  np.clip(log_spec / 40.0, -2.0, 0.0     ) + 1.0
        return log_spec

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

        if sampling_rate is not None:
             if sampling_rate != self.sampling_rate:
                  raise ValueError(
                      'This feature extractor is set to support sampling rate'
                      f' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled'
                      f' 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.'     )

        _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([speech], dtype=np.floataa     ).T 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    		=  [np.asarray([raw_speech]     ).T]

        # Convert audio signals to log mel spectrograms, truncate by time axis
        _A    		=  [
            self._np_extract_fbank_features(waveform.squeeze()     ).T[: self.spectrogram_length] for waveform in raw_speech
        ]
        if isinstance(audio_features[0], UpperCamelCase__     ):
             _A    		=  [np.asarray(UpperCamelCase__, dtype=np.floataa     ) for feature in audio_features]

        # Create audio attention mask
        _A    		=  max(
            [ceil(feature.shape[0] / self.patch_size[0]     ) * self.freq_len for feature in audio_features]     )  # The maximum number of audio patches in a batch
        if return_attention_mask:
             _A    		=  [
                 (ceil(feature.shape[0] / self.patch_size[0]     ) * self.freq_len) * [1]
                 + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]     ) * self.freq_len) * [0]
                 for feature in audio_features
             ]
             _A    		=  np.array(UpperCamelCase__     ).astype(np.floataa     )

        # convert into correct format for padding
        _A    		=  max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
        _A    		=  np.ones([len(UpperCamelCase__     ), 1, max_time_len, self.feature_size]     ).astype(np.floataa     )
        _A    		=  padded_audio_features * self.padding_value
        for i in range(len(UpperCamelCase__     )     ):
             _A    		=  audio_features[i]
             _A    		=  feature

        # return as BatchFeature
        if return_attention_mask:
             _A    		=  {'audio_values': padded_audio_features, 'audio_mask': audio_mask}
        else:
             _A    		=  {'audio_values': padded_audio_features}

        _A    		=  BatchFeature(data=UpperCamelCase__, tensor_type=UpperCamelCase__     )
        return encoded_inputs




'''simple docstring'''






from . import (
    albert,
    align,
    altclip,
    audio_spectrogram_transformer,
    auto,
    autoformer,
    bark,
    bart,
    barthez,
    bartpho,
    beit,
    bert,
    bert_generation,
    bert_japanese,
    bertweet,
    big_bird,
    bigbird_pegasus,
    biogpt,
    bit,
    blenderbot,
    blenderbot_small,
    blip,
    blip_a,
    bloom,
    bridgetower,
    byta,
    camembert,
    canine,
    chinese_clip,
    clap,
    clip,
    clipseg,
    codegen,
    conditional_detr,
    convbert,
    convnext,
    convnextva,
    cpm,
    cpmant,
    ctrl,
    cvt,
    dataavec,
    deberta,
    deberta_va,
    decision_transformer,
    deformable_detr,
    deit,
    deprecated,
    deta,
    detr,
    dialogpt,
    dinat,
    distilbert,
    dit,
    donut,
    dpr,
    dpt,
    efficientformer,
    efficientnet,
    electra,
    encodec,
    encoder_decoder,
    ernie,
    ernie_m,
    esm,
    falcon,
    flaubert,
    flava,
    fnet,
    focalnet,
    fsmt,
    funnel,
    git,
    glpn,
    gpta,
    gpt_bigcode,
    gpt_neo,
    gpt_neox,
    gpt_neox_japanese,
    gpt_swa,
    gptj,
    gptsan_japanese,
    graphormer,
    groupvit,
    herbert,
    hubert,
    ibert,
    imagegpt,
    informer,
    instructblip,
    jukebox,
    layoutlm,
    layoutlmva,
    layoutlmva,
    layoutxlm,
    led,
    levit,
    lilt,
    llama,
    longformer,
    longta,
    luke,
    lxmert,
    mam_aaa,
    marian,
    markuplm,
    maskaformer,
    maskformer,
    mbart,
    mbartaa,
    mega,
    megatron_bert,
    megatron_gpta,
    mgp_str,
    mluke,
    mobilebert,
    mobilenet_va,
    mobilenet_va,
    mobilevit,
    mobilevitva,
    mpnet,
    mra,
    mta,
    musicgen,
    mvp,
    nat,
    nezha,
    nllb,
    nllb_moe,
    nystromformer,
    oneformer,
    open_llama,
    openai,
    opt,
    owlvit,
    pegasus,
    pegasus_x,
    perceiver,
    phobert,
    pixastruct,
    plbart,
    poolformer,
    prophetnet,
    qdqbert,
    rag,
    realm,
    reformer,
    regnet,
    rembert,
    resnet,
    roberta,
    roberta_prelayernorm,
    roc_bert,
    roformer,
    rwkv,
    sam,
    segformer,
    sew,
    sew_d,
    speech_encoder_decoder,
    speech_to_text,
    speech_to_text_a,
    speechta,
    splinter,
    squeezebert,
    swiftformer,
    swin,
    swinasr,
    swinva,
    switch_transformers,
    ta,
    table_transformer,
    tapas,
    time_series_transformer,
    timesformer,
    timm_backbone,
    transfo_xl,
    trocr,
    tvlt,
    umta,
    unispeech,
    unispeech_sat,
    upernet,
    videomae,
    vilt,
    vision_encoder_decoder,
    vision_text_dual_encoder,
    visual_bert,
    vit,
    vit_hybrid,
    vit_mae,
    vit_msn,
    vivit,
    wavaveca,
    wavaveca_conformer,
    wavaveca_phoneme,
    wavaveca_with_lm,
    wavlm,
    whisper,
    x_clip,
    xglm,
    xlm,
    xlm_prophetnet,
    xlm_roberta,
    xlm_roberta_xl,
    xlnet,
    xmod,
    yolos,
    yoso,
)



