




"""simple docstring"""


import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    PNDMScheduler,
    StableDiffusionLDMaDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS


enable_full_determinism()






class 					lowercase(     unittest.TestCase ):







 '''simple docstring'''





 lowercase__ 					=					StableDiffusionLDMaDPipeline
 lowercase__ 					=					TEXT_TO_IMAGE_PARAMS
 lowercase__ 					=					TEXT_TO_IMAGE_BATCH_PARAMS
 lowercase__ 					=					TEXT_TO_IMAGE_IMAGE_PARAMS


 def  UpperCamelCase_   (				self:		Any		):




   '''simple docstring'''



   torch.manual_seed(0		)
   _snake_case							:		List[Any]								=  UNetaDConditionModel(
       block_out_channels=(32, 64),      layers_per_block=2,      sample_size=32,      in_channels=4,      out_channels=4,      down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D"""),      up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D"""),      cross_attention_dim=32,      )
   _snake_case							:		str								=  DDIMScheduler(
       beta_start=0.00_085,      beta_end=0.012,      beta_schedule="""scaled_linear""",      clip_sample=__UpperCAmelCase,      set_alpha_to_one=__UpperCAmelCase,      )
   torch.manual_seed(0		)
   _snake_case							:		int								=  AutoencoderKL(
       block_out_channels=[32, 64],      in_channels=6,      out_channels=6,      down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""],      up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""],      latent_channels=4,      )
   torch.manual_seed(0		)
   _snake_case							:		int								=  CLIPTextConfig(
       bos_token_id=0,      eos_token_id=2,      hidden_size=32,      intermediate_size=37,      layer_norm_eps=1E-05,      num_attention_heads=4,      num_hidden_layers=5,      pad_token_id=1,      vocab_size=1_000,      )
   _snake_case							:		Tuple								=  CLIPTextModel(__UpperCAmelCase		)
   _snake_case							:		int								=  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""		)

   _snake_case							:		Any								=  {
       """unet""": unet,
       """scheduler""": scheduler,
       """vae""": vae,
       """text_encoder""": text_encoder,
       """tokenizer""": tokenizer,
       """safety_checker""": None,
       """feature_extractor""": None,
   }
   return components


 def  UpperCamelCase_   (				self:		Any,      a_:		Optional[Any],      a_:		Dict=0		):




   '''simple docstring'''



   if str(__UpperCAmelCase		).startswith("""mps"""		):
     _snake_case							:		List[Any]								=  torch.manual_seed(__UpperCAmelCase		)
   else:
     _snake_case							:		Any								=  torch.Generator(device=__UpperCAmelCase		).manual_seed(__UpperCAmelCase		)
   _snake_case							:		int								=  {
       """prompt""": """A painting of a squirrel eating a burger""",
       """generator""": generator,
       """num_inference_steps""": 2,
       """guidance_scale""": 6.0,
       """output_type""": """numpy""",
   }
   return inputs


 def  UpperCamelCase_   (				self:		List[str]		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  """cpu"""  # ensure determinism for the device-dependent torch.Generator

   _snake_case							:		Union[str, Any]								=  self.get_dummy_components()
   _snake_case							:		str								=  StableDiffusionLDMaDPipeline(**__UpperCAmelCase		)
   _snake_case							:		Optional[Any]								=  ldmad_pipe.to(__UpperCAmelCase		)
   ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

   _snake_case							:		Union[str, Any]								=  self.get_dummy_inputs(__UpperCAmelCase		)
   _snake_case							:		Optional[int]								=  ldmad_pipe(**__UpperCAmelCase		)
   _snake_case		,					_snake_case							:		Tuple								=  output.rgb, output.depth

   _snake_case							:		Tuple								=  rgb[0, -3:, -3:, -1]
   _snake_case							:		Tuple								=  depth[0, -3:, -1]

   assert rgb.shape == (1, 64, 64, 3)
   assert depth.shape == (1, 64, 64)

   _snake_case							:		Optional[int]								=  np.array(
       [0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262]		)
   _snake_case							:		List[Any]								=  np.array([103.46_727, 85.812_004, 87.849_236]		)

   assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb		).max() < 1E-2
   assert np.abs(image_slice_depth.flatten() - expected_slice_depth		).max() < 1E-2


 def  UpperCamelCase_   (				self:		int		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  self.get_dummy_components()
   _snake_case							:		Optional[int]								=  StableDiffusionLDMaDPipeline(**__UpperCAmelCase		)
   _snake_case							:		Tuple								=  ldmad_pipe.to(__UpperCAmelCase		)
   ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

   _snake_case							:		Dict								=  self.get_dummy_inputs(__UpperCAmelCase		)
   _snake_case							:		Optional[Any]								=  3 * [inputs["""prompt"""]]

   # forward
   _snake_case							:		Any								=  ldmad_pipe(**__UpperCAmelCase		)
   _snake_case		,					_snake_case							:		str								=  output.rgb, output.depth
   _snake_case							:		Optional[int]								=  rgb_slice_a[0, -3:, -3:, -1]
   _snake_case							:		Any								=  depth_slice_a[0, -3:, -1]

   _snake_case							:		Optional[Any]								=  self.get_dummy_inputs(__UpperCAmelCase		)
   _snake_case							:		Union[str, Any]								=  3 * [inputs.pop("""prompt"""		)]

   _snake_case							:		List[str]								=  ldmad_pipe.tokenizer(
       __UpperCAmelCase,      padding="""max_length""",      max_length=ldmad_pipe.tokenizer.model_max_length,      truncation=__UpperCAmelCase,      return_tensors="""pt""",      )
   _snake_case							:		int								=  text_inputs["""input_ids"""].to(__UpperCAmelCase		)

   _snake_case							:		int								=  ldmad_pipe.text_encoder(__UpperCAmelCase		)[0]

   _snake_case							:		str								=  prompt_embeds

   # forward
   _snake_case							:		List[Any]								=  ldmad_pipe(**__UpperCAmelCase		)
   _snake_case		,					_snake_case							:		Tuple								=  output.rgb, output.depth
   _snake_case							:		Union[str, Any]								=  rgb_slice_a[0, -3:, -3:, -1]
   _snake_case							:		Optional[Any]								=  depth_slice_a[0, -3:, -1]

   assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten()		).max() < 1E-4
   assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten()		).max() < 1E-4


 def  UpperCamelCase_   (				self:		List[Any]		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  """cpu"""  # ensure determinism for the device-dependent torch.Generator
   _snake_case							:		List[Any]								=  self.get_dummy_components()
   _snake_case							:		Optional[Any]								=  PNDMScheduler(skip_prk_steps=__UpperCAmelCase		)
   _snake_case							:		Dict								=  StableDiffusionLDMaDPipeline(**__UpperCAmelCase		)
   _snake_case							:		Dict								=  ldmad_pipe.to(__UpperCAmelCase		)
   ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

   _snake_case							:		str								=  self.get_dummy_inputs(__UpperCAmelCase		)
   _snake_case							:		Dict								=  """french fries"""
   _snake_case							:		List[str]								=  ldmad_pipe(**__UpperCAmelCase,      negative_prompt=__UpperCAmelCase		)

   _snake_case		,					_snake_case							:		str								=  output.rgb, output.depth
   _snake_case							:		Union[str, Any]								=  rgb[0, -3:, -3:, -1]
   _snake_case							:		Any								=  depth[0, -3:, -1]

   assert rgb.shape == (1, 64, 64, 3)
   assert depth.shape == (1, 64, 64)

   _snake_case							:		Dict								=  np.array(
       [0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217]		)
   _snake_case							:		Tuple								=  np.array([107.84_738, 84.62_802, 89.962_135]		)
   assert np.abs(rgb_slice.flatten() - expected_slice_rgb		).max() < 1E-2
   assert np.abs(depth_slice.flatten() - expected_slice_depth		).max() < 1E-2







@slow
@require_torch_gpu
class 					lowercase(     unittest.TestCase ):







 '''simple docstring'''





 def  UpperCamelCase_   (				self:		List[Any]		):




   '''simple docstring'''



   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()


 def  UpperCamelCase_   (				self:		Tuple,      a_:		Optional[int],      a_:		Tuple="cpu",      a_:		Tuple=torch.floataa,      a_:		Optional[int]=0		):




   '''simple docstring'''



   _snake_case							:		int								=  torch.Generator(device=__UpperCAmelCase		).manual_seed(__UpperCAmelCase		)
   _snake_case							:		List[Any]								=  np.random.RandomState(__UpperCAmelCase		).standard_normal((1, 4, 64, 64)		)
   _snake_case							:		Tuple								=  torch.from_numpy(__UpperCAmelCase		).to(device=__UpperCAmelCase,      dtype=__UpperCAmelCase		)
   _snake_case							:		Optional[Any]								=  {
       """prompt""": """a photograph of an astronaut riding a horse""",
       """latents""": latents,
       """generator""": generator,
       """num_inference_steps""": 3,
       """guidance_scale""": 7.5,
       """output_type""": """numpy""",
   }
   return inputs


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		Tuple								=  StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d"""		)
   _snake_case							:		str								=  ldmad_pipe.to(__UpperCAmelCase		)
   ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

   _snake_case							:		Optional[int]								=  self.get_inputs(__UpperCAmelCase		)
   _snake_case							:		int								=  ldmad_pipe(**__UpperCAmelCase		)
   _snake_case		,					_snake_case							:		Union[str, Any]								=  output.rgb, output.depth
   _snake_case							:		List[str]								=  rgb[0, -3:, -3:, -1].flatten()
   _snake_case							:		Tuple								=  rgb[0, -3:, -1].flatten()

   assert rgb.shape == (1, 512, 512, 3)
   assert depth.shape == (1, 512, 512)

   _snake_case							:		int								=  np.array(
       [0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706]		)
   _snake_case							:		Any								=  np.array(
       [0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706]		)
   assert np.abs(rgb_slice - expected_slice_rgb		).max() < 3E-3
   assert np.abs(depth_slice - expected_slice_depth		).max() < 3E-3







@nightly
@require_torch_gpu
class 					lowercase(     unittest.TestCase ):







 '''simple docstring'''





 def  UpperCamelCase_   (				self:		Union[str, Any]		):




   '''simple docstring'''



   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()


 def  UpperCamelCase_   (				self:		Optional[int],      a_:		int,      a_:		Optional[Any]="cpu",      a_:		Optional[int]=torch.floataa,      a_:		Optional[int]=0		):




   '''simple docstring'''



   _snake_case							:		Any								=  torch.Generator(device=__UpperCAmelCase		).manual_seed(__UpperCAmelCase		)
   _snake_case							:		Any								=  np.random.RandomState(__UpperCAmelCase		).standard_normal((1, 4, 64, 64)		)
   _snake_case							:		Union[str, Any]								=  torch.from_numpy(__UpperCAmelCase		).to(device=__UpperCAmelCase,      dtype=__UpperCAmelCase		)
   _snake_case							:		Union[str, Any]								=  {
       """prompt""": """a photograph of an astronaut riding a horse""",
       """latents""": latents,
       """generator""": generator,
       """num_inference_steps""": 50,
       """guidance_scale""": 7.5,
       """output_type""": """numpy""",
   }
   return inputs


 def  UpperCamelCase_   (				self:		Any		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d"""		).to(__UpperCAmelCase		)
   ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

   _snake_case							:		Any								=  self.get_inputs(__UpperCAmelCase		)
   _snake_case							:		Optional[int]								=  ldmad_pipe(**__UpperCAmelCase		)
   _snake_case		,					_snake_case							:		Dict								=  output.rgb, output.depth

   _snake_case							:		List[str]								=  0.495_586
   _snake_case							:		Tuple								=  0.33_795_515
   _snake_case							:		Optional[Any]								=  112.48_518
   _snake_case							:		Optional[int]								=  98.489_746
   assert np.abs(expected_rgb_mean - rgb.mean()		) < 1E-3
   assert np.abs(expected_rgb_std - rgb.std()		) < 1E-3
   assert np.abs(expected_depth_mean - depth.mean()		) < 1E-3
   assert np.abs(expected_depth_std - depth.std()		) < 1E-3


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d-4c"""		).to(__UpperCAmelCase		)
   ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

   _snake_case							:		str								=  self.get_inputs(__UpperCAmelCase		)
   _snake_case							:		List[Any]								=  ldmad_pipe(**__UpperCAmelCase		)
   _snake_case		,					_snake_case							:		Dict								=  output.rgb, output.depth

   _snake_case							:		int								=  0.4_194_127
   _snake_case							:		List[Any]								=  0.35_375_586
   _snake_case							:		Tuple								=  0.5_638_502
   _snake_case							:		Dict								=  0.34_686_103

   assert rgb.shape == (1, 512, 512, 3)
   assert depth.shape == (1, 512, 512, 1)
   assert np.abs(expected_rgb_mean - rgb.mean()		) < 1E-3
   assert np.abs(expected_rgb_std - rgb.std()		) < 1E-3
   assert np.abs(expected_depth_mean - depth.mean()		) < 1E-3
   assert np.abs(expected_depth_std - depth.std()		) < 1E-3



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

import numpy as np

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


UpperCamelCase__											=					logging.get_logger(__name__)





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : int      =			['input_values', 'attention_mask']


   def __init__(self     :						Any       ,  __UpperCAmelCase     :						int = 1       ,  __UpperCAmelCase     :						int = 1_6_0_0_0       ,  __UpperCAmelCase     :						float = 0.0       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						int = 8_0       ,  __UpperCAmelCase     :						int = 1_6       ,  __UpperCAmelCase     :						int = 6_4       ,  __UpperCAmelCase     :						str = "hann_window"       ,  __UpperCAmelCase     :						float = 1.0       ,  __UpperCAmelCase     :						float = 8_0       ,  __UpperCAmelCase     :						float = 7_6_0_0       ,  __UpperCAmelCase     :						float = 1E-10       ,  __UpperCAmelCase     :						int = 2       ,  __UpperCAmelCase     :						bool = True       ,  **__UpperCAmelCase     :						Any       ,  )						->				str:
         """simple docstring"""



         super().__init__(feature_size=__UpperCAmelCase       ,  sampling_rate=__UpperCAmelCase       ,  padding_value=__UpperCAmelCase       ,  **__UpperCAmelCase		)
         UpperCAmelCase__								=  do_normalize
         UpperCAmelCase__								=  return_attention_mask

         UpperCAmelCase__								=  num_mel_bins
         UpperCAmelCase__								=  hop_length
         UpperCAmelCase__								=  win_length
         UpperCAmelCase__								=  win_function
         UpperCAmelCase__								=  frame_signal_scale
         UpperCAmelCase__								=  fmin
         UpperCAmelCase__								=  fmax
         UpperCAmelCase__								=  mel_floor
         UpperCAmelCase__								=  reduction_factor

         UpperCAmelCase__								=  win_length * sampling_rate // 1_0_0_0
         UpperCAmelCase__								=  hop_length * sampling_rate // 1_0_0_0
         UpperCAmelCase__								=  optimal_fft_length(self.sample_size		)
         UpperCAmelCase__								=  (self.n_fft // 2) + 1

         UpperCAmelCase__								=  window_function(window_length=self.sample_size       ,  name=self.win_function       ,  periodic=__UpperCAmelCase		)

         UpperCAmelCase__								=  mel_filter_bank(
             num_frequency_bins=self.n_freqs       ,  num_mel_filters=self.num_mel_bins       ,  min_frequency=self.fmin       ,  max_frequency=self.fmax       ,  sampling_rate=self.sampling_rate       ,  norm="slaney"       ,  mel_scale="slaney"       ,  )

         if frame_signal_scale != 1.0:
               warnings.warn(
                   "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers"       ,  __UpperCAmelCase       ,  )
         if reduction_factor != 2.0:
               warnings.warn(
                   "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"       ,  __UpperCAmelCase       ,  )


   @staticmethod
   # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
   def 			lowercase_      (__UpperCAmelCase     :						List[np.ndarray]       ,  __UpperCAmelCase     :						List[np.ndarray]       ,  __UpperCAmelCase     :						float = 0.0		)						->				List[np.ndarray]:
         """simple docstring"""



         if attention_mask is not None:
               UpperCAmelCase__								=  np.array(__UpperCAmelCase       ,  np.intaa		)
               UpperCAmelCase__								=  []

               for vector, length in zip(__UpperCAmelCase       ,  attention_mask.sum(-1		)		):
                     UpperCAmelCase__								=  (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7		)
                     if length < normed_slice.shape[0]:
                           UpperCAmelCase__								=  padding_value

                     normed_input_values.append(__UpperCAmelCase		)
         else:
               UpperCAmelCase__								=  [(x - x.mean()) / np.sqrt(x.var() + 1E-7		) for x in input_values]

         return normed_input_values


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						np.ndarray       ,  )						->				np.ndarray:
         """simple docstring"""



         UpperCAmelCase__								=  spectrogram(
             __UpperCAmelCase       ,  window=self.window       ,  frame_length=self.sample_size       ,  hop_length=self.sample_stride       ,  fft_length=self.n_fft       ,  mel_filters=self.mel_filters       ,  mel_floor=self.mel_floor       ,  log_mel="log10"       ,  )
         return log_mel_spec.T


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



         if audio is None and audio_target is None:
               raise ValueError("You must provide either `audio` or `audio_target` values."		)

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

         if audio is not None:
               UpperCAmelCase__								=  self._process_audio(
                   __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  **__UpperCAmelCase       ,  )
         else:
               UpperCAmelCase__								=  None

         if audio_target is not None:
               UpperCAmelCase__								=  self._process_audio(
                   __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  **__UpperCAmelCase       ,  )

               if inputs is None:
                     return inputs_target
               else:
                     UpperCAmelCase__								=  inputs_target["input_values"]
                     UpperCAmelCase__								=  inputs_target.get("attention_mask"		)
                     if decoder_attention_mask is not None:
                           UpperCAmelCase__								=  decoder_attention_mask

         return inputs


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Union[bool, str, PaddingStrategy] = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						Optional[bool] = None       ,  __UpperCAmelCase     :						Optional[Union[str, TensorType]] = None       ,  **__UpperCAmelCase     :						Any       ,  )						->				BatchFeature:
         """simple docstring"""



         UpperCAmelCase__								=  isinstance(__UpperCAmelCase       ,  np.ndarray		) and len(speech.shape		) > 1
         if is_batched_numpy and len(speech.shape		) > 2:
               raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""		)
         UpperCAmelCase__								=  is_batched_numpy or (
             isinstance(__UpperCAmelCase       ,  (list, tuple)		) and (isinstance(speech[0]       ,  (np.ndarray, tuple, list)		))
         )

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

         # always return batch
         if not is_batched:
               UpperCAmelCase__								=  [speech]

         # needed to make pad() work on spectrogram inputs
         UpperCAmelCase__								=  self.feature_size

         # convert into correct format for padding
         if is_target:
               UpperCAmelCase__								=  [self._extract_mel_features(__UpperCAmelCase		) for waveform in speech]
               UpperCAmelCase__								=  BatchFeature({"input_values": features}		)
               UpperCAmelCase__								=  self.num_mel_bins
         else:
               UpperCAmelCase__								=  BatchFeature({"input_values": speech}		)

         UpperCAmelCase__								=  self.pad(
             __UpperCAmelCase       ,  padding=__UpperCAmelCase       ,  max_length=__UpperCAmelCase       ,  truncation=__UpperCAmelCase       ,  pad_to_multiple_of=__UpperCAmelCase       ,  return_attention_mask=__UpperCAmelCase       ,  **__UpperCAmelCase       ,  )

         UpperCAmelCase__								=  feature_size_hack

         # convert input values to correct format
         UpperCAmelCase__								=  padded_inputs["input_values"]
         if not isinstance(input_values[0]       ,  np.ndarray		):
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		) for array in input_values]
         elif (
             not isinstance(__UpperCAmelCase       ,  np.ndarray		)
             and isinstance(input_values[0]       ,  np.ndarray		)
             and input_values[0].dtype is np.dtype(np.floataa		)
         ):
               UpperCAmelCase__								=  [array.astype(np.floataa		) for array in input_values]
         elif isinstance(__UpperCAmelCase       ,  np.ndarray		) and input_values.dtype is np.dtype(np.floataa		):
               UpperCAmelCase__								=  input_values.astype(np.floataa		)

         # convert attention_mask to correct format
         UpperCAmelCase__								=  padded_inputs.get("attention_mask"		)
         if attention_mask is not None:
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.intaa		) for array in attention_mask]

         # zero-mean and unit-variance normalization
         if not is_target and self.do_normalize:
               UpperCAmelCase__								=  (
                   attention_mask
                   if self._get_padding_strategies(__UpperCAmelCase       ,  max_length=__UpperCAmelCase		) is not PaddingStrategy.DO_NOT_PAD
                   else None
               )
               UpperCAmelCase__								=  self.zero_mean_unit_var_norm(
                   padded_inputs["input_values"]       ,  attention_mask=__UpperCAmelCase       ,  padding_value=self.padding_value		)

         if return_tensors is not None:
               UpperCAmelCase__								=  padded_inputs.convert_to_tensors(__UpperCAmelCase		)

         return padded_inputs





   def 			lowercase_      (self     :						Tuple		)						->				Dict[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  super().to_dict()

         # Don't serialize these as they are derived from the other properties.
         UpperCAmelCase__								=  ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"]
         for name in names:
               if name in output:
                     del output[name]

         return output



