





'''simple docstring'''


import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("3.8"):
       import importlib_metadata
else:
       import importlib.metadata as importlib_metadata


def 						__a(SCREAMING_SNAKE_CASE_	:       Any		,							SCREAMING_SNAKE_CASE_	:       Tuple=False     ):



    '''simple docstring'''





    try:
        _lowerCAmelCase						      =   os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        _lowerCAmelCase						      =   default
    else:
        # KEY is set, convert it to True or False.
        try:
            _lowerCAmelCase						      =   strtobool(SCREAMING_SNAKE_CASE_     )
        except ValueError:
            # More values are supported, but let's keep the message simple.
            raise ValueError(F'''If set, {key} must be yes or no.'''     )
    return _value


_SCREAMING_SNAKE_CASE									=				parse_flag_from_env("RUN_SLOW", default=False)
_SCREAMING_SNAKE_CASE									=				parse_flag_from_env("RUN_REMOTE", default=False)
_SCREAMING_SNAKE_CASE									=				parse_flag_from_env("RUN_LOCAL", default=True)
_SCREAMING_SNAKE_CASE									=				parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; ",
)

# Beam
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)


def 						__a(SCREAMING_SNAKE_CASE_	:       str     ):



    '''simple docstring'''





    try:
        import faiss  # noqa
    except ImportError:
        _lowerCAmelCase						      =   unittest.skip("test requires faiss"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Any     ):



    '''simple docstring'''





    try:
        import regex  # noqa
    except ImportError:
        _lowerCAmelCase						      =   unittest.skip("test requires regex"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):



    '''simple docstring'''





    try:
        import elasticsearch  # noqa
    except ImportError:
        _lowerCAmelCase						      =   unittest.skip("test requires elasticsearch"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[Any]     ):



    '''simple docstring'''





    try:
        import sqlalchemy  # noqa
    except ImportError:
        _lowerCAmelCase						      =   unittest.skip("test requires sqlalchemy"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       str     ):



    '''simple docstring'''





    if not config.TORCH_AVAILABLE:
        _lowerCAmelCase						      =   unittest.skip("test requires PyTorch"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[Any]     ):



    '''simple docstring'''





    if not config.TF_AVAILABLE:
        _lowerCAmelCase						      =   unittest.skip("test requires TensorFlow"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Tuple     ):



    '''simple docstring'''





    if not config.JAX_AVAILABLE:
        _lowerCAmelCase						      =   unittest.skip("test requires JAX"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Dict     ):



    '''simple docstring'''





    if not config.PIL_AVAILABLE:
        _lowerCAmelCase						      =   unittest.skip("test requires Pillow"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       int     ):



    '''simple docstring'''





    try:
        import transformers  # noqa F401
    except ImportError:
        return unittest.skip("test requires transformers"     )(SCREAMING_SNAKE_CASE_     )
    else:
        return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Any     ):



    '''simple docstring'''





    try:
        import tiktoken  # noqa F401
    except ImportError:
        return unittest.skip("test requires tiktoken"     )(SCREAMING_SNAKE_CASE_     )
    else:
        return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       List[str]     ):



    '''simple docstring'''





    try:
        import spacy  # noqa F401
    except ImportError:
        return unittest.skip("test requires spacy"     )(SCREAMING_SNAKE_CASE_     )
    else:
        return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[int]     ):



    '''simple docstring'''





    def _require_spacy_model(SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):
        try:
            import spacy  # noqa F401

            spacy.load(SCREAMING_SNAKE_CASE_     )
        except ImportError:
            return unittest.skip("test requires spacy"     )(SCREAMING_SNAKE_CASE_     )
        except OSError:
            return unittest.skip("test requires spacy model '{}'".format(SCREAMING_SNAKE_CASE_     )     )(SCREAMING_SNAKE_CASE_     )
        else:
            return test_case

    return _require_spacy_model


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[int]     ):



    '''simple docstring'''





    try:
        import pyspark  # noqa F401
    except ImportError:
        return unittest.skip("test requires pyspark"     )(SCREAMING_SNAKE_CASE_     )
    else:
        return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):



    '''simple docstring'''





    try:
        import joblibspark  # noqa F401
    except ImportError:
        return unittest.skip("test requires joblibspark"     )(SCREAMING_SNAKE_CASE_     )
    else:
        return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[int]     ):



    '''simple docstring'''





    if not _run_slow_tests or _run_slow_tests == 0:
        _lowerCAmelCase						      =   unittest.skip("test is slow"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Dict     ):



    '''simple docstring'''





    if not _run_local_tests or _run_local_tests == 0:
        _lowerCAmelCase						      =   unittest.skip("test is local"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[Any]     ):



    '''simple docstring'''





    if not _run_packaged_tests or _run_packaged_tests == 0:
        _lowerCAmelCase						      =   unittest.skip("test is packaged"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Any     ):



    '''simple docstring'''





    if not _run_remote_tests or _run_remote_tests == 0:
        _lowerCAmelCase						      =   unittest.skip("test requires remote"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(*SCREAMING_SNAKE_CASE_	:       Optional[Any]     ):



    '''simple docstring'''





    def decorate(cls	:       Any     ):
        for name, fn in cls.__dict__.items():
            if callable(SCREAMING_SNAKE_CASE_     ) and name.startswith("test"     ):
                for decorator in decorators:
                    _lowerCAmelCase						      =   decorator(SCREAMING_SNAKE_CASE_     )
                setattr(cls		,							SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_     )
        return cls

    return decorate

class  lowerCAmelCase_		(		__magic_name__		):
 pass







class  lowerCAmelCase_		(		__magic_name__		):
 __lowerCamelCase    :				Any								=       0
 __lowerCamelCase    :				Any								=       1
 __lowerCamelCase    :				Optional[int]								=       2







@contextmanager
def 						__a(SCREAMING_SNAKE_CASE_	:       List[str]=OfflineSimulationMode.CONNECTION_FAILS		,							SCREAMING_SNAKE_CASE_	:       Dict=1e-16     ):



    '''simple docstring'''





    _lowerCAmelCase						      =   requests.Session().request

    def timeout_request(SCREAMING_SNAKE_CASE_	:       str		,							SCREAMING_SNAKE_CASE_	:       int		,							SCREAMING_SNAKE_CASE_	:       Optional[int]		,							**SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):
        # Change the url to an invalid url so that the connection hangs
        _lowerCAmelCase						      =   "https://10.255.255.1"
        if kwargs.get("timeout"     ) is None:
            raise RequestWouldHangIndefinitelyError(
                F'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'''     )
        _lowerCAmelCase						      =   timeout
        try:
            return online_request(SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_		,							**SCREAMING_SNAKE_CASE_     )
        except Exception as e:
            # The following changes in the error are just here to make the offline timeout error prettier
            _lowerCAmelCase						      =   url
            _lowerCAmelCase						      =   e.args[0]
            _lowerCAmelCase						      =   (max_retry_error.args[0].replace("10.255.255.1"		,							F'''OfflineMock[{url}]'''     ),)
            _lowerCAmelCase						      =   (max_retry_error,)
            raise

    def raise_connection_error(SCREAMING_SNAKE_CASE_	:       List[str]		,							SCREAMING_SNAKE_CASE_	:       List[Any]		,							**SCREAMING_SNAKE_CASE_	:       int     ):
        raise requests.ConnectionError("Offline mode is enabled."		,							request=SCREAMING_SNAKE_CASE_     )

    if mode is OfflineSimulationMode.CONNECTION_FAILS:
        with patch("requests.Session.send"		,							SCREAMING_SNAKE_CASE_     ):
            yield
    elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
        # inspired from https://stackoverflow.com/a/904609
        with patch("requests.Session.request"		,							SCREAMING_SNAKE_CASE_     ):
            yield
    elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
        with patch("datasets.config.HF_DATASETS_OFFLINE"		,							SCREAMING_SNAKE_CASE_     ):
            yield
    else:
        raise ValueError("Please use a value from the OfflineSimulationMode enum."     )


@contextmanager
def 						__a(*SCREAMING_SNAKE_CASE_	:       str		,							**SCREAMING_SNAKE_CASE_	:       Optional[int]     ):



    '''simple docstring'''





    _lowerCAmelCase						      =   str(Path().resolve()     )
    with tempfile.TemporaryDirectory(*SCREAMING_SNAKE_CASE_		,							**SCREAMING_SNAKE_CASE_     ) as tmp_dir:
        try:
            os.chdir(SCREAMING_SNAKE_CASE_     )
            yield
        finally:
            os.chdir(SCREAMING_SNAKE_CASE_     )


@contextmanager
def 						__a():



    '''simple docstring'''





    import gc

    gc.collect()
    _lowerCAmelCase						      =   pa.total_allocated_bytes()
    yield
    assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."


@contextmanager
def 						__a():



    '''simple docstring'''





    import gc

    gc.collect()
    _lowerCAmelCase						      =   pa.total_allocated_bytes()
    yield
    assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."


def 						__a(SCREAMING_SNAKE_CASE_	:       int		,							SCREAMING_SNAKE_CASE_	:       Tuple     ):



    '''simple docstring'''





    return deepcopy(SCREAMING_SNAKE_CASE_     ).integers(0		,							100		,							10     ).tolist() == deepcopy(SCREAMING_SNAKE_CASE_     ).integers(0		,							100		,							10     ).tolist()


def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):



    '''simple docstring'''





    import decorator
    from requests.exceptions import HTTPError

    def _wrapper(SCREAMING_SNAKE_CASE_	:       Dict		,							*SCREAMING_SNAKE_CASE_	:       Optional[Any]		,							**SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):
        try:
            return func(*SCREAMING_SNAKE_CASE_		,							**SCREAMING_SNAKE_CASE_     )
        except HTTPError as err:
            if str(SCREAMING_SNAKE_CASE_     ).startswith("500"     ) or str(SCREAMING_SNAKE_CASE_     ).startswith("502"     ):
                pytest.xfail(str(SCREAMING_SNAKE_CASE_     )     )
            raise err

    return decorator.decorator(_wrapper		,							SCREAMING_SNAKE_CASE_     )

class  lowerCAmelCase_		:




 def __init__(						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				Optional[Any]:
     _lowerCAmelCase						      =   returncode
     _lowerCAmelCase						      =   stdout
     _lowerCAmelCase						      =   stderr







async def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]		,							SCREAMING_SNAKE_CASE_	:       Dict     ):



    '''simple docstring'''





    while True:
        _lowerCAmelCase						      =   await stream.readline()
        if line:
            callback(SCREAMING_SNAKE_CASE_     )
        else:
            break


async def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]		,							SCREAMING_SNAKE_CASE_	:       Any=None		,							SCREAMING_SNAKE_CASE_	:       Union[str, Any]=None		,							SCREAMING_SNAKE_CASE_	:       Dict=None		,							SCREAMING_SNAKE_CASE_	:       int=False		,							SCREAMING_SNAKE_CASE_	:       Tuple=False     ):



    '''simple docstring'''





    if echo:
        print("\nRunning: "		,							" ".join(SCREAMING_SNAKE_CASE_     )     )

    _lowerCAmelCase						      =   await asyncio.create_subprocess_exec(
        cmd[0]		,							*cmd[1:]		,							stdin=SCREAMING_SNAKE_CASE_		,							stdout=asyncio.subprocess.PIPE		,							stderr=asyncio.subprocess.PIPE		,							env=SCREAMING_SNAKE_CASE_		,							)

    # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
    # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
    #
    # If it starts hanging, will need to switch to the following code. The problem is that no data
    # will be seen until it's done and if it hangs for example there will be no debug info.
    # out, err = await p.communicate()
    # return _RunOutput(p.returncode, out, err)

    _lowerCAmelCase						      =   []
    _lowerCAmelCase						      =   []

    def tee(SCREAMING_SNAKE_CASE_	:       List[Any]		,							SCREAMING_SNAKE_CASE_	:       Optional[Any]		,							SCREAMING_SNAKE_CASE_	:       List[str]		,							SCREAMING_SNAKE_CASE_	:       int=""     ):
        _lowerCAmelCase						      =   line.decode("utf-8"     ).rstrip()
        sink.append(SCREAMING_SNAKE_CASE_     )
        if not quiet:
            print(SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_		,							file=SCREAMING_SNAKE_CASE_     )

    # XXX: the timeout doesn't seem to make any difference here
    await asyncio.wait(
        [
            _read_stream(p.stdout		,							lambda SCREAMING_SNAKE_CASE_     : tee(SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_		,							sys.stdout		,							label="stdout:"     )     ),
            _read_stream(p.stderr		,							lambda SCREAMING_SNAKE_CASE_     : tee(SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_		,							sys.stderr		,							label="stderr:"     )     ),
        ]		,							timeout=SCREAMING_SNAKE_CASE_		,							)
    return _RunOutput(await p.wait()		,							SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_     )


def 						__a(SCREAMING_SNAKE_CASE_	:       List[str]		,							SCREAMING_SNAKE_CASE_	:       Union[str, Any]=None		,							SCREAMING_SNAKE_CASE_	:       Tuple=None		,							SCREAMING_SNAKE_CASE_	:       str=180		,							SCREAMING_SNAKE_CASE_	:       Optional[Any]=False		,							SCREAMING_SNAKE_CASE_	:       int=True     ):



    '''simple docstring'''





    _lowerCAmelCase						      =   asyncio.get_event_loop()
    _lowerCAmelCase						      =   loop.run_until_complete(
        _stream_subprocess(SCREAMING_SNAKE_CASE_		,							env=SCREAMING_SNAKE_CASE_		,							stdin=SCREAMING_SNAKE_CASE_		,							timeout=SCREAMING_SNAKE_CASE_		,							quiet=SCREAMING_SNAKE_CASE_		,							echo=SCREAMING_SNAKE_CASE_     )     )

    _lowerCAmelCase						      =   " ".join(SCREAMING_SNAKE_CASE_     )
    if result.returncode > 0:
        _lowerCAmelCase						      =   "\n".join(result.stderr     )
        raise RuntimeError(
            F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
            F'''The combined stderr from workers follows:\n{stderr}'''     )

    # check that the subprocess actually did run and produced some output, should the test rely on
    # the remote side to do the testing
    if not result.stdout and not result.stderr:
        raise RuntimeError(F'''\'{cmd_str}\' produced no output.'''     )

    return result


def 						__a():



    '''simple docstring'''





    _lowerCAmelCase						      =   os.environ.get("PYTEST_XDIST_WORKER"		,							"gw0"     )
    _lowerCAmelCase						      =   re.sub(R"^gw"		,							""		,							SCREAMING_SNAKE_CASE_		,							0		,							re.M     )
    return int(SCREAMING_SNAKE_CASE_     )





def 						__a():



    '''simple docstring'''





    _lowerCAmelCase						      =   29500
    _lowerCAmelCase						      =   pytest_xdist_worker_id()
    return port + uniq_delta






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


lowercase				=logging.get_logger(__name__)






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 =["input_features", "attention_mask"]






       def __init__(     self    ,				snake_case=8_0    ,				snake_case=1_6_0_0_0    ,				snake_case=8_0    ,				snake_case=0.0    ,				snake_case=True    ,				snake_case=True    ,				snake_case=True    ,				**snake_case    ,				)		->    str:




          '''simple docstring'''
          super().__init__(feature_size=snake_case    ,				sampling_rate=snake_case    ,				padding_value=snake_case    ,				**snake_case)
          _UpperCAmelCase  :  Optional[Any]				       =num_mel_bins
          _UpperCAmelCase  :  Optional[int]				       =do_ceptral_normalize
          _UpperCAmelCase  :  Optional[Any]				       =normalize_means
          _UpperCAmelCase  :  Optional[Any]				       =normalize_vars
          _UpperCAmelCase  :  Tuple				       =True






       def      lowerCAmelCase						(     self    ,				snake_case    ,				)		->    np.ndarray:




          '''simple docstring'''
          _UpperCAmelCase  :  List[Any]				       =waveform * (2**1_5)  # Kaldi compliance: 16-bit signed integers
          _UpperCAmelCase  :  Dict				       =torch.from_numpy(snake_case).unsqueeze(0)
          _UpperCAmelCase  :  Union[str, Any]				       =ta_kaldi.fbank(snake_case    ,				num_mel_bins=self.num_mel_bins    ,				sample_frequency=self.sampling_rate)
          return features.numpy()






       @staticmethod
       def      lowerCAmelCase						(     snake_case    ,				snake_case    ,				snake_case = True    ,				snake_case = True    ,				snake_case = 0.0    ,				)		->    np.ndarray:




          '''simple docstring'''
          # make sure we normalize float32 arrays
          if normalize_means:
             _UpperCAmelCase  :  int				       =x[:input_length].mean(axis=0)
             _UpperCAmelCase  :  List[Any]				       =np.subtract(snake_case    ,				snake_case)
          if normalize_vars:
             _UpperCAmelCase  :  List[Any]				       =x[:input_length].std(axis=0)
             _UpperCAmelCase  :  Optional[int]				       =np.divide(snake_case    ,				snake_case)

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

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

          return x






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




          '''simple docstring'''
          _UpperCAmelCase  :  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.')

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

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

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

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

          # convert into correct format for padding
          _UpperCAmelCase  :  List[str]				       =BatchFeature({'input_features': features})

          _UpperCAmelCase  :  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
          _UpperCAmelCase  :  Dict				       =padded_inputs.get('input_features')
          if isinstance(input_features[0]    ,				snake_case):
             _UpperCAmelCase  :  Any				       =[np.asarray(snake_case    ,				dtype=np.floataa) for feature in input_features]

          _UpperCAmelCase  :  int				       =padded_inputs.get('attention_mask')
          if attention_mask is not None:
             _UpperCAmelCase  :  Tuple				       =[np.asarray(snake_case    ,				dtype=np.intaa) for array in attention_mask]

          # Utterance-level cepstral mean and variance normalization
          if self.do_ceptral_normalize:
             _UpperCAmelCase  :  Optional[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
             )
             _UpperCAmelCase  :  Optional[int]				       =self.normalize(
                 padded_inputs['input_features']    ,				attention_mask=snake_case)

          if return_tensors is not None:
             _UpperCAmelCase  :  List[Any]				       =padded_inputs.convert_to_tensors(snake_case)

          return padded_inputs

