

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


UpperCAmelCase__ :     Tuple				    =    logging.get_logger(__name__)







class        a__       (   UpperCAmelCase       ):







  """simple docstring"""




  UpperCAmelCase__      : Optional[int]			       =["""input_features""", """attention_mask"""]


  def __init__(			self    : List[str]				,				UpperCAmelCase__    : Optional[Any]=8_0				,				UpperCAmelCase__    : List[str]=1_6_0_0_0				,				UpperCAmelCase__    : Optional[int]=8_0				,				UpperCAmelCase__    : List[str]=0.0				,				UpperCAmelCase__    : List[Any]=True				,				UpperCAmelCase__    : Tuple=True				,				UpperCAmelCase__    : Tuple=True				,				**UpperCAmelCase__    : Optional[int]				,				)					->Optional[int]:
        """simple docstring"""







        super().__init__(feature_size=UpperCAmelCase__				,				sampling_rate=UpperCAmelCase__				,				padding_value=UpperCAmelCase__				,				**UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Optional[int]       =   num_mel_bins
        SCREAMING_SNAKE_CASE :      Dict       =   do_ceptral_normalize
        SCREAMING_SNAKE_CASE :      Optional[int]       =   normalize_means
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   normalize_vars
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   True


  def  _lowercase      (			self    : Tuple				,				UpperCAmelCase__    : np.ndarray				,				)					->np.ndarray:
        """simple docstring"""







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


  @staticmethod
  def  _lowercase      (			UpperCAmelCase__    : np.ndarray				,				UpperCAmelCase__    : int				,				UpperCAmelCase__    : Optional[bool] = True				,				UpperCAmelCase__    : Optional[bool] = True				,				UpperCAmelCase__    : float = 0.0				,				)					->np.ndarray:
        """simple docstring"""







        if normalize_means:
              SCREAMING_SNAKE_CASE :      Tuple       =   x[:input_length].mean(axis=0		)
              SCREAMING_SNAKE_CASE :      List[Any]       =   np.subtract(UpperCAmelCase__				,				UpperCAmelCase__		)
        if normalize_vars:
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   x[:input_length].std(axis=0		)
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   np.divide(UpperCAmelCase__				,				UpperCAmelCase__		)

        if input_length < x.shape[0]:
              SCREAMING_SNAKE_CASE :      Tuple       =   padding_value

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

        return x


  def  _lowercase      (			self    : List[str]				,				UpperCAmelCase__    : List[np.ndarray]				,				UpperCAmelCase__    : Optional[np.ndarray] = None		)					->List[np.ndarray]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      str       =   attention_mask.sum(-1		) if attention_mask is not None else [x.shape[0] for x in input_features]
        return [
            self.utterance_cmvn(UpperCAmelCase__				,				UpperCAmelCase__				,				self.normalize_means				,				self.normalize_vars				,				self.padding_value		)
            for x, n in zip(UpperCAmelCase__				,				UpperCAmelCase__		)
        ]




  def __call__(			self    : str				,				UpperCAmelCase__    : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]				,				UpperCAmelCase__    : Union[bool, str, PaddingStrategy] = False				,				UpperCAmelCase__    : Optional[int] = None				,				UpperCAmelCase__    : bool = False				,				UpperCAmelCase__    : Optional[int] = None				,				UpperCAmelCase__    : Optional[Union[str, TensorType]] = None				,				UpperCAmelCase__    : Optional[int] = None				,				UpperCAmelCase__    : Optional[bool] = None				,				**UpperCAmelCase__    : Optional[int]				,				)					->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."""		)

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

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

        # always return batch
        if not is_batched:
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   [raw_speech]

        # extract fbank features
        SCREAMING_SNAKE_CASE :      Tuple       =   [self._extract_fbank_features(UpperCAmelCase__		) for waveform in raw_speech]

        # convert into correct format for padding
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   BatchFeature({"""input_features""": features}		)

        SCREAMING_SNAKE_CASE :      str       =   self.pad(
            UpperCAmelCase__				,				padding=UpperCAmelCase__				,				max_length=UpperCAmelCase__				,				truncation=UpperCAmelCase__				,				pad_to_multiple_of=UpperCAmelCase__				,				return_attention_mask=UpperCAmelCase__				,				**UpperCAmelCase__				,				)

        # make sure list is in array format
        SCREAMING_SNAKE_CASE :      Dict       =   padded_inputs.get("""input_features"""		)
        if isinstance(input_features[0]				,				UpperCAmelCase__		):
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   [np.asarray(UpperCAmelCase__				,				dtype=np.floataa		) for feature in input_features]

        SCREAMING_SNAKE_CASE :      Dict       =   padded_inputs.get("""attention_mask"""		)
        if attention_mask is not None:
              SCREAMING_SNAKE_CASE :      int       =   [np.asarray(UpperCAmelCase__				,				dtype=np.intaa		) for array in attention_mask]

        # Utterance-level cepstral mean and variance normalization
        if self.do_ceptral_normalize:
              SCREAMING_SNAKE_CASE :      Tuple       =   (
                  np.array(UpperCAmelCase__				,				dtype=np.intaa		)
                  if self._get_padding_strategies(UpperCAmelCase__				,				max_length=UpperCAmelCase__		) is not PaddingStrategy.DO_NOT_PAD
                  else None
              )
              SCREAMING_SNAKE_CASE :      str       =   self.normalize(
                  padded_inputs["""input_features"""]				,				attention_mask=UpperCAmelCase__		)

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

        return padded_inputs







import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()







class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  def  _lowercase      (			self    : Union[str, Any]		)					->List[Any]:
        """simple docstring"""







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


  @property
  def  _lowercase      (			self    : str		)					->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   1
        SCREAMING_SNAKE_CASE :      Dict       =   3
        SCREAMING_SNAKE_CASE :      List[Any]       =   (3_2, 3_2)

        SCREAMING_SNAKE_CASE :      Any       =   floats_tensor((batch_size, num_channels) + sizes				,				rng=random.Random(0		)		).to(UpperCAmelCase__		)
        return image


  @property
  def  _lowercase      (			self    : Tuple		)					->List[Any]:
        """simple docstring"""







        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      str       =   UNetaDConditionModel(
            block_out_channels=(3_2, 6_4)				,				layers_per_block=2				,				sample_size=3_2				,				in_channels=4				,				out_channels=4				,				down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,				up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")				,				cross_attention_dim=3_2				,				)
        return model


  @property
  def  _lowercase      (			self    : str		)					->int:
        """simple docstring"""







        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Tuple       =   AutoencoderKL(
            block_out_channels=[3_2, 6_4]				,				in_channels=3				,				out_channels=3				,				down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]				,				up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]				,				latent_channels=4				,				)
        return model


  @property
  def  _lowercase      (			self    : Tuple		)					->Union[str, Any]:
        """simple docstring"""







        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      str       =   RobertaSeriesConfig(
            hidden_size=3_2				,				project_dim=3_2				,				intermediate_size=3_7				,				layer_norm_eps=1e-05				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=5_0_0_6				,				)
        return RobertaSeriesModelWithTransformation(UpperCAmelCase__		)


  @property
  def  _lowercase      (			self    : Union[str, Any]		)					->List[str]:
        """simple docstring"""







        def extract(*UpperCAmelCase__    : List[Any]				,				**UpperCAmelCase__    : Tuple		):







              class        a__       :







                """simple docstring"""




                def __init__(			self    : Tuple		)					->Dict:
                      """simple docstring"""







                      SCREAMING_SNAKE_CASE :      Union[str, Any]       =   torch.ones([0]		)




                def  _lowercase      (			self    : Optional[int]				,				UpperCAmelCase__    : Dict		)					->Optional[Any]:
                      """simple docstring"""







                      self.pixel_values.to(UpperCAmelCase__		)
                      return self


              return Out()

        return extract


  def  _lowercase      (			self    : List[str]		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   """cpu"""  # ensure determinism for the device-dependent torch.Generator
        SCREAMING_SNAKE_CASE :      Optional[int]       =   self.dummy_cond_unet
        SCREAMING_SNAKE_CASE :      str       =   PNDMScheduler(skip_prk_steps=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   self.dummy_vae
        SCREAMING_SNAKE_CASE :      str       =   self.dummy_text_encoder
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   7_7

        SCREAMING_SNAKE_CASE :      str       =   self.dummy_image.to(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   init_image / 2 + 0.5

        # make sure here that pndm scheduler skips prk
        SCREAMING_SNAKE_CASE :      List[str]       =   AltDiffusionImgaImgPipeline(
            unet=UpperCAmelCase__				,				scheduler=UpperCAmelCase__				,				vae=UpperCAmelCase__				,				text_encoder=UpperCAmelCase__				,				tokenizer=UpperCAmelCase__				,				safety_checker=UpperCAmelCase__				,				feature_extractor=self.dummy_extractor				,				)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,				do_normalize=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Tuple       =   alt_pipe.to(UpperCAmelCase__		)
        alt_pipe.set_progress_bar_config(disable=UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      str       =   """A painting of a squirrel eating a burger"""
        SCREAMING_SNAKE_CASE :      Tuple       =   torch.Generator(device=UpperCAmelCase__		).manual_seed(0		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   alt_pipe(
            [prompt]				,				generator=UpperCAmelCase__				,				guidance_scale=6.0				,				num_inference_steps=2				,				output_type="""np"""				,				image=UpperCAmelCase__				,				)

        SCREAMING_SNAKE_CASE :      List[str]       =   output.images

        SCREAMING_SNAKE_CASE :      List[Any]       =   torch.Generator(device=UpperCAmelCase__		).manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Any       =   alt_pipe(
            [prompt]				,				generator=UpperCAmelCase__				,				guidance_scale=6.0				,				num_inference_steps=2				,				output_type="""np"""				,				image=UpperCAmelCase__				,				return_dict=UpperCAmelCase__				,				)[0]

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   image[0, -3:, -3:, -1]
        SCREAMING_SNAKE_CASE :      int       =   image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 3_2, 3_2, 3)
        SCREAMING_SNAKE_CASE :      str       =   np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99]		)

        assert np.abs(image_slice.flatten() - expected_slice		).max() < 5e-3
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice		).max() < 5e-3


  @unittest.skipIf(torch_device != """cuda"""				,				"""This test requires a GPU"""		)
  def  _lowercase      (			self    : Optional[int]		)					->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.dummy_cond_unet
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   PNDMScheduler(skip_prk_steps=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      List[str]       =   self.dummy_vae
        SCREAMING_SNAKE_CASE :      int       =   self.dummy_text_encoder
        SCREAMING_SNAKE_CASE :      List[Any]       =   XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""		)
        SCREAMING_SNAKE_CASE :      Tuple       =   7_7

        SCREAMING_SNAKE_CASE :      Optional[int]       =   self.dummy_image.to(UpperCAmelCase__		)

        # put models in fp16
        SCREAMING_SNAKE_CASE :      List[Any]       =   unet.half()
        SCREAMING_SNAKE_CASE :      Tuple       =   vae.half()
        SCREAMING_SNAKE_CASE :      str       =   bert.half()

        # make sure here that pndm scheduler skips prk
        SCREAMING_SNAKE_CASE :      str       =   AltDiffusionImgaImgPipeline(
            unet=UpperCAmelCase__				,				scheduler=UpperCAmelCase__				,				vae=UpperCAmelCase__				,				text_encoder=UpperCAmelCase__				,				tokenizer=UpperCAmelCase__				,				safety_checker=UpperCAmelCase__				,				feature_extractor=self.dummy_extractor				,				)
        SCREAMING_SNAKE_CASE :      Optional[int]       =   VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,				do_normalize=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      str       =   alt_pipe.to(UpperCAmelCase__		)
        alt_pipe.set_progress_bar_config(disable=UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      int       =   """A painting of a squirrel eating a burger"""
        SCREAMING_SNAKE_CASE :      List[str]       =   torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Any       =   alt_pipe(
            [prompt]				,				generator=UpperCAmelCase__				,				num_inference_steps=2				,				output_type="""np"""				,				image=UpperCAmelCase__				,				).images

        assert image.shape == (1, 3_2, 3_2, 3)




  @unittest.skipIf(torch_device != """cuda"""				,				"""This test requires a GPU"""		)
  def  _lowercase      (			self    : Dict		)					->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
            """/img2img/sketch-mountains-input.jpg"""		)
        # resize to resolution that is divisible by 8 but not 16 or 32
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   init_image.resize((7_6_0, 5_0_4)		)

        SCREAMING_SNAKE_CASE :      int       =   """BAAI/AltDiffusion"""
        SCREAMING_SNAKE_CASE :      List[str]       =   AltDiffusionImgaImgPipeline.from_pretrained(
            UpperCAmelCase__				,				safety_checker=UpperCAmelCase__				,				)
        pipe.to(UpperCAmelCase__		)
        pipe.set_progress_bar_config(disable=UpperCAmelCase__		)
        pipe.enable_attention_slicing()

        SCREAMING_SNAKE_CASE :      int       =   """A fantasy landscape, trending on artstation"""

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   pipe(
            prompt=UpperCAmelCase__				,				image=UpperCAmelCase__				,				strength=0.75				,				guidance_scale=7.5				,				generator=UpperCAmelCase__				,				output_type="""np"""				,				)
        SCREAMING_SNAKE_CASE :      Tuple       =   output.images[0]

        SCREAMING_SNAKE_CASE :      Tuple       =   image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

        assert image.shape == (5_0_4, 7_6_0, 3)
        SCREAMING_SNAKE_CASE :      List[str]       =   np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00]		)

        assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-2







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







  """simple docstring"""




  def  _lowercase      (			self    : Any		)					->List[str]:
        """simple docstring"""







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




  def  _lowercase      (			self    : Optional[Any]		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Any       =   load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
            """/img2img/sketch-mountains-input.jpg"""		)
        SCREAMING_SNAKE_CASE :      str       =   init_image.resize((7_6_8, 5_1_2)		)
        SCREAMING_SNAKE_CASE :      int       =   load_numpy(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""		)

        SCREAMING_SNAKE_CASE :      Tuple       =   """BAAI/AltDiffusion"""
        SCREAMING_SNAKE_CASE :      str       =   AltDiffusionImgaImgPipeline.from_pretrained(
            UpperCAmelCase__				,				safety_checker=UpperCAmelCase__				,				)
        pipe.to(UpperCAmelCase__		)
        pipe.set_progress_bar_config(disable=UpperCAmelCase__		)
        pipe.enable_attention_slicing()

        SCREAMING_SNAKE_CASE :      Dict       =   """A fantasy landscape, trending on artstation"""

        SCREAMING_SNAKE_CASE :      Optional[int]       =   torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   pipe(
            prompt=UpperCAmelCase__				,				image=UpperCAmelCase__				,				strength=0.75				,				guidance_scale=7.5				,				generator=UpperCAmelCase__				,				output_type="""np"""				,				)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   output.images[0]

        assert image.shape == (5_1_2, 7_6_8, 3)
        # img2img is flaky across GPUs even in fp32, so using MAE here
        assert np.abs(expected_image - image		).max() < 1e-2




