'''simple docstring'''




import importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


__SCREAMING_SNAKE_CASE       :     Dict     =  (
    """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py"""
)


__SCREAMING_SNAKE_CASE       :     List[Any]     =  logging.get_logger(__name__)  # pylint: disable=invalid-name

def 	UpperCamelCase_							(					)    ->    Optional[int]:


       """simple docstring"""







       _UpperCAmelCase     :  int							      =    "https://pypi.org/pypi/diffusers/json"
       _UpperCAmelCase     :  Optional[int]							      =    json.loads(request.urlopen(_UpperCAmelCase    ).read()    )["releases"].keys()
       return sorted(_UpperCAmelCase			,	key=lambda _UpperCAmelCase    : version.Version(_UpperCAmelCase    )    )

def 	UpperCamelCase_							(					)    ->    List[Any]:


       """simple docstring"""







       if HF_MODULES_CACHE in sys.path:
              return

       sys.path.append(_UpperCAmelCase    )
       os.makedirs(_UpperCAmelCase			,	exist_ok=_UpperCAmelCase    )
       _UpperCAmelCase     :  List[Any]							      =    Path(_UpperCAmelCase    ) / "__init__.py"
       if not init_path.exists():
              init_path.touch()

def 	UpperCamelCase_							(					_UpperCAmelCase  :      Union[str, os.PathLike]    )    ->    List[str]:


       """simple docstring"""







       init_hf_modules()
       _UpperCAmelCase     :  List[Any]							      =    Path(_UpperCAmelCase    ) / name
       # If the parent module does not exist yet, recursively create it.
       if not dynamic_module_path.parent.exists():
              create_dynamic_module(dynamic_module_path.parent    )
       os.makedirs(_UpperCAmelCase			,	exist_ok=_UpperCAmelCase    )
       _UpperCAmelCase     :  str							      =    dynamic_module_path / "__init__.py"
       if not init_path.exists():
              init_path.touch()

def 	UpperCamelCase_							(					_UpperCAmelCase  :      Optional[Any]    )    ->    Dict:


       """simple docstring"""







       with open(_UpperCAmelCase			,	"r"			,	encoding="utf-8"    ) as f:
              _UpperCAmelCase     :  Optional[int]							      =    f.read()

       # Imports of the form `import .xxx`
       _UpperCAmelCase     :  str							      =    re.findall("^\s*import\s+\.(\S+)\s*$"			,	_UpperCAmelCase			,	flags=re.MULTILINE    )
       # Imports of the form `from .xxx import yyy`
       relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import"			,	_UpperCAmelCase			,	flags=re.MULTILINE    )
       # Unique-ify
       return list(set(_UpperCAmelCase    )    )

def 	UpperCamelCase_							(					_UpperCAmelCase  :      Optional[int]    )    ->    Any:


       """simple docstring"""







       _UpperCAmelCase     :  Optional[Any]							      =    False
       _UpperCAmelCase     :  Dict							      =    [module_file]
       _UpperCAmelCase     :  Optional[int]							      =    []

       # Let's recurse through all relative imports
       while not no_change:
              _UpperCAmelCase     :  List[str]							      =    []
              for f in files_to_check:
                     new_imports.extend(get_relative_imports(_UpperCAmelCase    )    )

              _UpperCAmelCase     :  str							      =    Path(_UpperCAmelCase    ).parent
              _UpperCAmelCase     :  Optional[Any]							      =    [str(module_path / m    ) for m in new_imports]
              _UpperCAmelCase     :  List[Any]							      =    [f for f in new_import_files if f not in all_relative_imports]
              _UpperCAmelCase     :  Tuple							      =    [F"""{f}.py""" for f in new_import_files]

              _UpperCAmelCase     :  Tuple							      =    len(_UpperCAmelCase    ) == 0
              all_relative_imports.extend(_UpperCAmelCase    )

       return all_relative_imports

def 	UpperCamelCase_							(					_UpperCAmelCase  :      Union[str, Any]    )    ->    Optional[int]:


       """simple docstring"""







       with open(_UpperCAmelCase			,	"r"			,	encoding="utf-8"    ) as f:
              _UpperCAmelCase     :  Optional[Any]							      =    f.read()

       # Imports of the form `import xxx`
       _UpperCAmelCase     :  List[Any]							      =    re.findall("^\s*import\s+(\S+)\s*$"			,	_UpperCAmelCase			,	flags=re.MULTILINE    )
       # Imports of the form `from xxx import yyy`
       imports += re.findall("^\s*from\s+(\S+)\s+import"			,	_UpperCAmelCase			,	flags=re.MULTILINE    )
       # Only keep the top-level module
       _UpperCAmelCase     :  Union[str, Any]							      =    [imp.split("."    )[0] for imp in imports if not imp.startswith("."    )]

       # Unique-ify and test we got them all
       _UpperCAmelCase     :  str							      =    list(set(_UpperCAmelCase    )    )
       _UpperCAmelCase     :  Tuple							      =    []
       for imp in imports:
              try:
                     importlib.import_module(_UpperCAmelCase    )
              except ImportError:
                     missing_packages.append(_UpperCAmelCase    )

       if len(_UpperCAmelCase    ) > 0:
              raise ImportError(
                  "This modeling file requires the following packages that were not found in your environment: "
                  F"""{', '.join(_UpperCAmelCase    )}. Run `pip install {' '.join(_UpperCAmelCase    )}`"""    )

       return get_relative_imports(_UpperCAmelCase    )

def 	UpperCamelCase_							(					_UpperCAmelCase  :      List[Any]			,	_UpperCAmelCase  :      Any    )    ->    Any:


       """simple docstring"""







       _UpperCAmelCase     :  Any							      =    module_path.replace(os.path.sep			,	"."    )
       _UpperCAmelCase     :  str							      =    importlib.import_module(_UpperCAmelCase    )

       if class_name is None:
              return find_pipeline_class(_UpperCAmelCase    )
       return getattr(_UpperCAmelCase			,	_UpperCAmelCase    )

def 	UpperCamelCase_							(					_UpperCAmelCase  :      List[str]    )    ->    Optional[Any]:


       """simple docstring"""







       from ..pipelines import DiffusionPipeline

       _UpperCAmelCase     :  List[Any]							      =    dict(inspect.getmembers(_UpperCAmelCase			,	inspect.isclass    )    )

       _UpperCAmelCase     :  int							      =    None
       for cls_name, cls in cls_members.items():
              if (
                  cls_name != DiffusionPipeline.__name__
                  and issubclass(cls			,	_UpperCAmelCase    )
                  and cls.__module__.split("."    )[0] != "diffusers"
              ):
                     if pipeline_class is not None:
                            raise ValueError(
                                F"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:"""
                                F""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in"""
                                F""" {loaded_module}."""    )
                     _UpperCAmelCase     :  Dict							      =    cls

       return pipeline_class

def 	UpperCamelCase_							(					_UpperCAmelCase  :      Union[str, os.PathLike]			,	_UpperCAmelCase  :      str			,	_UpperCAmelCase  :      Optional[Union[str, os.PathLike]] = None			,	_UpperCAmelCase  :      bool = False			,	_UpperCAmelCase  :      bool = False			,	_UpperCAmelCase  :      Optional[Dict[str, str]] = None			,	_UpperCAmelCase  :      Optional[Union[bool, str]] = None			,	_UpperCAmelCase  :      Optional[str] = None			,	_UpperCAmelCase  :      bool = False			,	)    ->    str:


       """simple docstring"""







       _UpperCAmelCase     :  Tuple							      =    str(_UpperCAmelCase    )

       _UpperCAmelCase     :  Optional[int]							      =    os.path.join(_UpperCAmelCase			,	_UpperCAmelCase    )

       if os.path.isfile(_UpperCAmelCase    ):
              _UpperCAmelCase     :  Union[str, Any]							      =    module_file_or_url
              _UpperCAmelCase     :  Optional[Any]							      =    "local"
       elif pretrained_model_name_or_path.count("/"    ) == 0:
              _UpperCAmelCase     :  Tuple							      =    get_diffusers_versions()
              # cut ".dev0"
              _UpperCAmelCase     :  str							      =    "v" + ".".join(__version__.split("."    )[:3]    )

              # retrieve github version that matches
              if revision is None:
                     _UpperCAmelCase     :  Tuple							      =    latest_version if latest_version[1:] in available_versions else "main"
                     logger.info(F"""Defaulting to latest_version: {revision}."""    )
              elif revision in available_versions:
                     _UpperCAmelCase     :  Tuple							      =    F"""v{revision}"""
              elif revision == "main":
                     _UpperCAmelCase     :  Tuple							      =    revision
              else:
                     raise ValueError(
                         F"""`custom_revision`: {revision} does not exist. Please make sure to choose one of"""
                         F""" {', '.join(available_versions + ['main']    )}."""    )

              # community pipeline on GitHub
              _UpperCAmelCase     :  List[str]							      =    COMMUNITY_PIPELINES_URL.format(revision=_UpperCAmelCase			,	pipeline=_UpperCAmelCase    )
              try:
                     _UpperCAmelCase     :  str							      =    cached_download(
                         _UpperCAmelCase			,	cache_dir=_UpperCAmelCase			,	force_download=_UpperCAmelCase			,	proxies=_UpperCAmelCase			,	resume_download=_UpperCAmelCase			,	local_files_only=_UpperCAmelCase			,	use_auth_token=_UpperCAmelCase			,	)
                     _UpperCAmelCase     :  int							      =    "git"
                     _UpperCAmelCase     :  Tuple							      =    pretrained_model_name_or_path + ".py"
              except EnvironmentError:
                     logger.error(F"""Could not locate the {module_file} inside {pretrained_model_name_or_path}."""    )
                     raise
       else:
              try:
                     # Load from URL or cache if already cached
                     _UpperCAmelCase     :  Union[str, Any]							      =    hf_hub_download(
                         _UpperCAmelCase			,	_UpperCAmelCase			,	cache_dir=_UpperCAmelCase			,	force_download=_UpperCAmelCase			,	proxies=_UpperCAmelCase			,	resume_download=_UpperCAmelCase			,	local_files_only=_UpperCAmelCase			,	use_auth_token=_UpperCAmelCase			,	)
                     _UpperCAmelCase     :  Tuple							      =    os.path.join("local"			,	"--".join(pretrained_model_name_or_path.split("/"    )    )    )
              except EnvironmentError:
                     logger.error(F"""Could not locate the {module_file} inside {pretrained_model_name_or_path}."""    )
                     raise

    # Check we have all the requirements in our environment
       _UpperCAmelCase     :  Optional[Any]							      =    check_imports(_UpperCAmelCase    )

       # Now we move the module inside our cached dynamic modules.
       _UpperCAmelCase     :  Optional[Any]							      =    DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
       create_dynamic_module(_UpperCAmelCase    )
       _UpperCAmelCase     :  List[Any]							      =    Path(_UpperCAmelCase    ) / full_submodule
       if submodule == "local" or submodule == "git":
              # We always copy local files (we could hash the file to see if there was a change, and give them the name of
              # that hash, to only copy when there is a modification but it seems overkill for now).
              # The only reason we do the copy is to avoid putting too many folders in sys.path.
              shutil.copy(_UpperCAmelCase			,	submodule_path / module_file    )
              for module_needed in modules_needed:
                     _UpperCAmelCase     :  Optional[int]							      =    F"""{module_needed}.py"""
                     shutil.copy(os.path.join(_UpperCAmelCase			,	_UpperCAmelCase    )			,	submodule_path / module_needed    )
       else:
              # Get the commit hash
              # TODO: we will get this info in the etag soon, so retrieve it from there and not here.
              if isinstance(_UpperCAmelCase			,	_UpperCAmelCase    ):
                     _UpperCAmelCase     :  List[Any]							      =    use_auth_token
              elif use_auth_token is True:
                     _UpperCAmelCase     :  Tuple							      =    HfFolder.get_token()
              else:
                     _UpperCAmelCase     :  Dict							      =    None

              _UpperCAmelCase     :  Tuple							      =    model_info(_UpperCAmelCase			,	revision=_UpperCAmelCase			,	token=_UpperCAmelCase    ).sha

              # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
              # benefit of versioning.
              _UpperCAmelCase     :  Any							      =    submodule_path / commit_hash
              _UpperCAmelCase     :  List[str]							      =    full_submodule + os.path.sep + commit_hash
              create_dynamic_module(_UpperCAmelCase    )

              if not (submodule_path / module_file).exists():
                     shutil.copy(_UpperCAmelCase			,	submodule_path / module_file    )
              # Make sure we also have every file with relative
              for module_needed in modules_needed:
                     if not (submodule_path / module_needed).exists():
                            get_cached_module_file(
                                _UpperCAmelCase			,	F"""{module_needed}.py"""			,	cache_dir=_UpperCAmelCase			,	force_download=_UpperCAmelCase			,	resume_download=_UpperCAmelCase			,	proxies=_UpperCAmelCase			,	use_auth_token=_UpperCAmelCase			,	revision=_UpperCAmelCase			,	local_files_only=_UpperCAmelCase			,	)
       return os.path.join(_UpperCAmelCase			,	_UpperCAmelCase    )


def 	UpperCamelCase_							(					_UpperCAmelCase  :      Union[str, os.PathLike]			,	_UpperCAmelCase  :      str			,	_UpperCAmelCase  :      Optional[str] = None			,	_UpperCAmelCase  :      Optional[Union[str, os.PathLike]] = None			,	_UpperCAmelCase  :      bool = False			,	_UpperCAmelCase  :      bool = False			,	_UpperCAmelCase  :      Optional[Dict[str, str]] = None			,	_UpperCAmelCase  :      Optional[Union[bool, str]] = None			,	_UpperCAmelCase  :      Optional[str] = None			,	_UpperCAmelCase  :      bool = False			,	**_UpperCAmelCase  :      Any			,	)    ->    List[str]:


       """simple docstring"""







       _UpperCAmelCase     :  int							      =    get_cached_module_file(
           _UpperCAmelCase			,	_UpperCAmelCase			,	cache_dir=_UpperCAmelCase			,	force_download=_UpperCAmelCase			,	resume_download=_UpperCAmelCase			,	proxies=_UpperCAmelCase			,	use_auth_token=_UpperCAmelCase			,	revision=_UpperCAmelCase			,	local_files_only=_UpperCAmelCase			,	)
       return get_class_in_module(_UpperCAmelCase			,	final_module.replace(".py"			,	""    )    )


'''simple docstring'''




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

import numpy as np
import torch

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 	lowerCamelCase_	(snake_case__    ):
      '''simple docstring'''

      __UpperCamelCase:  Optional[int]						=						["input_features", "is_longer"]




      def __init__(       self						:				str						,					A						:				int=64						,					A						:				Dict=48000						,					A						:				str=480						,					A						:				List[Any]=10						,					A						:				Optional[Any]=1024						,					A						:				Tuple=0.0						,					A						:				List[Any]=False						,					A						:				float = 0						,					A						:				float = 14000						,					A						:				int = None						,					A						:				str = "fusion"						,					A						:				str = "repeatpad"						,					**A						:				Dict						,					):
             super().__init__(
                 feature_size=A						,					sampling_rate=A						,					padding_value=A						,					return_attention_mask=A						,					**A						,					)
             _UpperCAmelCase     :  Optional[Any]							      =    top_db
             _UpperCAmelCase     :  Dict							      =    truncation
             _UpperCAmelCase     :  List[Any]							      =    padding
             _UpperCAmelCase     :  Optional[Any]							      =    fft_window_size
             _UpperCAmelCase     :  Dict							      =    (fft_window_size >> 1) + 1
             _UpperCAmelCase     :  Any							      =    hop_length
             _UpperCAmelCase     :  Tuple							      =    max_length_s
             _UpperCAmelCase     :  str							      =    max_length_s * sampling_rate
             _UpperCAmelCase     :  Any							      =    sampling_rate
             _UpperCAmelCase     :  Optional[int]							      =    frequency_min
             _UpperCAmelCase     :  str							      =    frequency_max
             _UpperCAmelCase     :  Union[str, Any]							      =    mel_filter_bank(
                 num_frequency_bins=self.nb_frequency_bins						,					num_mel_filters=A						,					min_frequency=A						,					max_frequency=A						,					sampling_rate=A						,					norm=A						,					mel_scale="htk"						,					)
             _UpperCAmelCase     :  Tuple							      =    mel_filter_bank(
                 num_frequency_bins=self.nb_frequency_bins						,					num_mel_filters=A						,					min_frequency=A						,					max_frequency=A						,					sampling_rate=A						,					norm="slaney"						,					mel_scale="slaney"						,					)




      def      _A	(       self						:				List[str]       ):
             _UpperCAmelCase     :  Union[str, Any]							      =    copy.deepcopy(self.__dict__       )
             _UpperCAmelCase     :  Dict							      =    self.__class__.__name__
             if "mel_filters" in output:
                    del output["mel_filters"]
             if "mel_filters_slaney" in output:
                    del output["mel_filters_slaney"]
             return output




      def      _A	(       self						:				Optional[Any]						,					A						:				np.array						,					A						:				Optional[np.array] = None       ):
             _UpperCAmelCase     :  Dict							      =    spectrogram(
                 A						,					window_function(self.fft_window_size						,					"hann"       )						,					frame_length=self.fft_window_size						,					hop_length=self.hop_length						,					power=2.0						,					mel_filters=A						,					log_mel="dB"						,					)
             return log_mel_spectrogram.T




      def      _A	(       self						:				str						,					A						:				str						,					A						:				List[str]						,					A						:				List[Any]       ):
             _UpperCAmelCase     :  List[str]							      =    np.array_split(list(range(0						,					total_frames - chunk_frames + 1       )       )						,					3       )
             if len(ranges[1]       ) == 0:
                    # if the audio is too short, we just use the first chunk
                    _UpperCAmelCase     :  Optional[Any]							      =    [0]
             if len(ranges[2]       ) == 0:
                    # if the audio is too short, we just use the first chunk
                    _UpperCAmelCase     :  Tuple							      =    [0]
             # randomly choose index for each part
             _UpperCAmelCase     :  Dict							      =    np.random.choice(ranges[0]       )
             _UpperCAmelCase     :  str							      =    np.random.choice(ranges[1]       )
             _UpperCAmelCase     :  Tuple							      =    np.random.choice(ranges[2]       )

             _UpperCAmelCase     :  str							      =    mel[idx_front : idx_front + chunk_frames, :]
             _UpperCAmelCase     :  str							      =    mel[idx_middle : idx_middle + chunk_frames, :]
             _UpperCAmelCase     :  List[Any]							      =    mel[idx_back : idx_back + chunk_frames, :]

             _UpperCAmelCase     :  Dict							      =    torch.tensor(mel[None, None, :]       )
             _UpperCAmelCase     :  Optional[Any]							      =    torch.nn.functional.interpolate(
                 A						,					size=[chunk_frames, 64]						,					mode="bilinear"						,					align_corners=A       )
             _UpperCAmelCase     :  List[str]							      =    mel_shrink[0][0].numpy()
             _UpperCAmelCase     :  str							      =    np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back]						,					axis=0       )
             return mel_fusion




      def      _A	(       self						:				List[Any]						,					A						:				np.array						,					A						:				List[str]						,					A						:				Any						,					A						:				Optional[int]       ):
             if waveform.shape[0] > max_length:
                    if truncation == "rand_trunc":
                           _UpperCAmelCase     :  int							      =    True
                           # random crop to max_length (for compatibility) -> this should be handled by self.pad
                           _UpperCAmelCase     :  str							      =    len(A       ) - max_length
                           _UpperCAmelCase     :  str							      =    np.random.randint(0						,					overflow + 1       )
                           _UpperCAmelCase     :  int							      =    waveform[idx : idx + max_length]
                           _UpperCAmelCase     :  Any							      =    self._np_extract_fbank_features(A						,					self.mel_filters_slaney       )[None, :]
                    elif truncation == "fusion":
                           _UpperCAmelCase     :  Tuple							      =    self._np_extract_fbank_features(A						,					self.mel_filters       )
                           _UpperCAmelCase     :  List[str]							      =    max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
                           _UpperCAmelCase     :  Optional[Any]							      =    mel.shape[0]
                           if chunk_frames == total_frames:
                                  # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
                                  # In this case, we just use the whole audio.
                                  _UpperCAmelCase     :  Any							      =    np.stack([mel, mel, mel, mel]						,					axis=0       )
                                  _UpperCAmelCase     :  int							      =    False
                           else:
                                  _UpperCAmelCase     :  Tuple							      =    self._random_mel_fusion(A						,					A						,					A       )
                                  _UpperCAmelCase     :  Any							      =    True
                    else:
                           raise NotImplementedError(F"""data_truncating {truncation} not implemented"""       )

             else:
                    _UpperCAmelCase     :  Optional[Any]							      =    False
                    # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
                    if waveform.shape[0] < max_length:
                           if padding == "repeat":
                                  _UpperCAmelCase     :  str							      =    int(max_length / len(A       )       )
                                  _UpperCAmelCase     :  Dict							      =    np.stack(np.tile(A						,					n_repeat + 1       )       )[:max_length]
                           if padding == "repeatpad":
                                  _UpperCAmelCase     :  Dict							      =    int(max_length / len(A       )       )
                                  _UpperCAmelCase     :  List[str]							      =    np.stack(np.tile(A						,					A       )       )
                           _UpperCAmelCase     :  Optional[Any]							      =    np.pad(A						,					(0, max_length - waveform.shape[0])						,					mode="constant"						,					constant_values=0       )

                    if truncation == "fusion":
                           _UpperCAmelCase     :  str							      =    self._np_extract_fbank_features(A						,					self.mel_filters       )
                           _UpperCAmelCase     :  Optional[int]							      =    np.stack([input_mel, input_mel, input_mel, input_mel]						,					axis=0       )
                    else:
                           _UpperCAmelCase     :  List[str]							      =    self._np_extract_fbank_features(A						,					self.mel_filters_slaney       )[None, :]

             return input_mel, longer





      def __call__(       self						:				Union[str, Any]						,					A						:				Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]						,					A						:				str = None						,					A						:				Optional[str] = None						,					A						:				Optional[int] = None						,					A						:				Optional[int] = None						,					A						:				Optional[Union[str, TensorType]] = None						,					**A						:				List[str]						,					):
             _UpperCAmelCase     :  int							      =    truncation if truncation is not None else self.truncation
             _UpperCAmelCase     :  Optional[int]							      =    padding if padding else self.padding

             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."       )

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

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

             # always return batch
             if not is_batched:
                    _UpperCAmelCase     :  List[str]							      =    [np.asarray(A       )]

             # convert to mel spectrogram, truncate and pad if needed.
             _UpperCAmelCase     :  Dict							      =    [
                 self._get_input_mel(A						,					max_length if max_length else self.nb_max_samples						,					A						,					A       )
                 for waveform in raw_speech
             ]

             _UpperCAmelCase     :  int							      =    []
             _UpperCAmelCase     :  Optional[Any]							      =    []
             for mel, longer in padded_inputs:
                    input_mel.append(A       )
                    is_longer.append(A       )

             if truncation == "fusion" and sum(A       ) == 0:
                    # if no audio is longer than 10s, then randomly select one audio to be longer
                    _UpperCAmelCase     :  Union[str, Any]							      =    np.random.randint(0						,					len(A       )       )
                    _UpperCAmelCase     :  Optional[Any]							      =    True

             if isinstance(input_mel[0]						,					A       ):
                    _UpperCAmelCase     :  List[str]							      =    [np.asarray(A						,					dtype=np.floataa       ) for feature in input_mel]

             # is_longer is a list of bool
             _UpperCAmelCase     :  Tuple							      =    [[longer] for longer in is_longer]

             _UpperCAmelCase     :  Optional[Any]							      =    {"input_features": input_mel, "is_longer": is_longer}
             _UpperCAmelCase     :  Tuple							      =    BatchFeature(A       )

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

             return input_features

