




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


__A			:		Any   				=     logging.get_logger(__name__)
class 				lowerCamelCase		(			a__					):
   lowercase							:	Any  =					['input_features', 'attention_mask']







   def __init__(				self     ,   SCREAMING_SNAKE_CASE_=80     ,   SCREAMING_SNAKE_CASE_=1_6000     ,   SCREAMING_SNAKE_CASE_=80     ,   SCREAMING_SNAKE_CASE_=0.0     ,   SCREAMING_SNAKE_CASE_=True     ,   SCREAMING_SNAKE_CASE_=True     ,   SCREAMING_SNAKE_CASE_=True     ,   **SCREAMING_SNAKE_CASE_     ,   ):
       super().__init__(feature_size=_snake_case     ,   sampling_rate=_snake_case     ,   padding_value=_snake_case     ,   **_snake_case			)
       UpperCamelCase					: Optional[int] 							=				num_mel_bins
       UpperCamelCase					: Optional[Any] 							=				do_ceptral_normalize
       UpperCamelCase					: Tuple 							=				normalize_means
       UpperCamelCase					: Optional[Any] 							=				normalize_vars
       UpperCamelCase					: Union[str, Any] 							=				True







   def    a_				(				self     ,   SCREAMING_SNAKE_CASE_     ,   ):
       UpperCamelCase					: Optional[Any] 							=				waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
       UpperCamelCase					: List[str] 							=				torch.from_numpy(_snake_case			).unsqueeze(0			)
       UpperCamelCase					: Dict 							=				ta_kaldi.fbank(_snake_case     ,   num_mel_bins=self.num_mel_bins     ,   sample_frequency=self.sampling_rate			)
       return features.numpy()







   @staticmethod
   def    a_				(				SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_ = True     ,   SCREAMING_SNAKE_CASE_ = True     ,   SCREAMING_SNAKE_CASE_ = 0.0     ,   ):






       if normalize_means:
           UpperCamelCase					: List[Any] 							=				x[:input_length].mean(axis=0			)
           UpperCamelCase					: int 							=				np.subtract(_snake_case     ,   _snake_case			)
       if normalize_vars:
           UpperCamelCase					: Union[str, Any] 							=				x[:input_length].std(axis=0			)
           UpperCamelCase					: Dict 							=				np.divide(_snake_case     ,   _snake_case			)

       if input_length < x.shape[0]:
           UpperCamelCase					: Optional[int] 							=				padding_value

       # make sure array is in float32
       UpperCamelCase					: Optional[Any] 							=				x.astype(np.floataa			)

       return x







   def    a_				(				self     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_ = None			):
       UpperCamelCase					: Dict 							=				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     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_ = False     ,   SCREAMING_SNAKE_CASE_ = None     ,   SCREAMING_SNAKE_CASE_ = False     ,   SCREAMING_SNAKE_CASE_ = None     ,   SCREAMING_SNAKE_CASE_ = None     ,   SCREAMING_SNAKE_CASE_ = None     ,   SCREAMING_SNAKE_CASE_ = None     ,   **SCREAMING_SNAKE_CASE_     ,   ):






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

       if is_batched:
           UpperCamelCase					: Any 							=				[np.asarray(_snake_case     ,   dtype=np.floataa			) for speech in raw_speech]
       elif not is_batched and not isinstance(_snake_case     ,   np.ndarray			):
           UpperCamelCase					: int 							=				np.asarray(_snake_case     ,   dtype=np.floataa			)
       elif isinstance(_snake_case     ,   np.ndarray			) and raw_speech.dtype is np.dtype(np.floataa			):
           UpperCamelCase					: Optional[int] 							=				raw_speech.astype(np.floataa			)

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

       # extract fbank features
       UpperCamelCase					: Dict 							=				[self._extract_fbank_features(_snake_case			) for waveform in raw_speech]

       # convert into correct format for padding
       UpperCamelCase					: Dict 							=				BatchFeature({"""input_features""": features}			)

       UpperCamelCase					: Optional[int] 							=				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					: Any 							=				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					: List[str] 							=				padded_inputs.get("""attention_mask"""			)
       if attention_mask is not None:
           UpperCamelCase					: Union[str, Any] 							=				[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					: Tuple 							=				(
               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[Any] 							=				self.normalize(
               padded_inputs["""input_features"""]     ,   attention_mask=_snake_case			)

       if return_tensors is not None:
           UpperCamelCase					: Optional[Any] 							=				padded_inputs.convert_to_tensors(_snake_case			)

       return padded_inputs











"""simple docstring"""
import random
import unittest

import torch

from diffusers import IFInpaintingPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin







@skip_mps
class       a							(   a__   , a__   , unittest.TestCase  ):
 snake_case__             =       IFInpaintingPipeline
 snake_case__             =       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''}
 snake_case__             =       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
 snake_case__             =       PipelineTesterMixin.required_optional_params - {'''latents'''}



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return self._get_dummy_components()



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case=0     ):







  """simple docstring"""






  if str(_snake_case     ).startswith('mps'     ):
   lowerCAmelCase    				= torch.manual_seed(_snake_case     )
  else:
   lowerCAmelCase    				= torch.Generator(device=_snake_case     ).manual_seed(_snake_case     )

  lowerCAmelCase    				= floats_tensor((1, 3, 32, 32)				,       rng=random.Random(_snake_case     )     ).to(_snake_case     )
  lowerCAmelCase    				= floats_tensor((1, 3, 32, 32)				,       rng=random.Random(_snake_case     )     ).to(_snake_case     )

  lowerCAmelCase    				= {
      'prompt': 'A painting of a squirrel eating a burger',
      'image': image,
      'mask_image': mask_image,
      'generator': generator,
      'num_inference_steps': 2,
      'output_type': 'numpy',
  }

  return inputs



 @unittest.skipIf(
     torch_device != 'cuda' or not is_xformers_available()				,       reason='XFormers attention is only available with CUDA and `xformers` installed'				,       )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_save_load_optional_components()



 @unittest.skipIf(torch_device != 'cuda'				,       reason='float16 requires CUDA'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  super().test_save_load_floataa(expected_max_diff=1E-1     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_attention_slicing_forward_pass(expected_max_diff=1E-2     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_save_load_local()



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_inference_batch_single_identical(
      expected_max_diff=1E-2				,       )





