






import gc
import random
import unittest

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

from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
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, skip_mps

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 						snake_case  (  a__       ,			a__       ,			unittest.TestCase	):
    __magic_name__   					=					CycleDiffusionPipeline
    __magic_name__   					=					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
        """negative_prompt""",
        """height""",
        """width""",
        """negative_prompt_embeds""",
    }
    __magic_name__   					=					PipelineTesterMixin.required_optional_params - {"""latents"""}
    __magic_name__   					=					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''}	)
    __magic_name__   					=					IMAGE_TO_IMAGE_IMAGE_PARAMS
    __magic_name__   					=					IMAGE_TO_IMAGE_IMAGE_PARAMS





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      torch.manual_seed(0      )
      a					:      List[Any]    =       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    ,		)
      a					:      Tuple    =       DDIMScheduler(
          beta_start=0.0_00_85    ,		beta_end=0.0_12    ,		beta_schedule='scaled_linear'    ,		num_train_timesteps=1_0_0_0    ,		clip_sample=lowerCAmelCase__    ,		set_alpha_to_one=lowerCAmelCase__    ,		)
      torch.manual_seed(0      )
      a					:      Any    =       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    ,		)
      torch.manual_seed(0      )
      a					:      Optional[Any]    =       CLIPTextConfig(
          bos_token_id=0    ,		eos_token_id=2    ,		hidden_size=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=1_0_0_0    ,		)
      a					:      str    =       CLIPTextModel(lowerCAmelCase__      )
      a					:      Dict    =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

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





    def     lowerCamelCase__				(							self     : Optional[Any]    ,		A     : Tuple    ,		A     : Tuple=0      ):


      '''simple docstring'''




      a					:      int    =       floats_tensor((1, 3, 3_2, 3_2)    ,		rng=random.Random(lowerCAmelCase__      )      ).to(lowerCAmelCase__      )
      a					:      Any    =       image / 2 + 0.5
      if str(lowerCAmelCase__      ).startswith('mps'      ):
        a					:      Optional[Any]    =       torch.manual_seed(lowerCAmelCase__      )
      else:
        a					:      Any    =       torch.Generator(device=lowerCAmelCase__      ).manual_seed(lowerCAmelCase__      )
      a					:      Optional[Any]    =       {
          "prompt": "An astronaut riding an elephant",
          "source_prompt": "An astronaut riding a horse",
          "image": image,
          "generator": generator,
          "num_inference_steps": 2,
          "eta": 0.1,
          "strength": 0.8,
          "guidance_scale": 3,
          "source_guidance_scale": 1,
          "output_type": "numpy",
      }
      return inputs





    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       "cpu"  # ensure determinism for the device-dependent torch.Generator

      a					:      Tuple    =       self.get_dummy_components()
      a					:      int    =       CycleDiffusionPipeline(**lowerCAmelCase__      )
      a					:      str    =       pipe.to(lowerCAmelCase__      )
      pipe.set_progress_bar_config(disable=lowerCAmelCase__      )

      a					:      List[str]    =       self.get_dummy_inputs(lowerCAmelCase__      )
      a					:      List[str]    =       pipe(**lowerCAmelCase__      )
      a					:      int    =       output.images

      a					:      List[Any]    =       images[0, -3:, -3:, -1]

      assert images.shape == (1, 3_2, 3_2, 3)
      a					:      Any    =       np.array([0.44_59, 0.49_43, 0.45_44, 0.66_43, 0.54_74, 0.43_27, 0.57_01, 0.59_59, 0.51_79]      )

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





    @unittest.skipIf(torch_device != 'cuda'    ,		'This test requires a GPU'      )
    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       self.get_dummy_components()
      for name, module in components.items():
        if hasattr(lowerCAmelCase__    ,		'half'      ):
          a					:      Optional[int]    =       module.half()
      a					:      List[str]    =       CycleDiffusionPipeline(**lowerCAmelCase__      )
      a					:      Dict    =       pipe.to(lowerCAmelCase__      )
      pipe.set_progress_bar_config(disable=lowerCAmelCase__      )

      a					:      List[Any]    =       self.get_dummy_inputs(lowerCAmelCase__      )
      a					:      Tuple    =       pipe(**lowerCAmelCase__      )
      a					:      List[Any]    =       output.images

      a					:      Optional[Any]    =       images[0, -3:, -3:, -1]

      assert images.shape == (1, 3_2, 3_2, 3)
      a					:      str    =       np.array([0.35_06, 0.45_43, 0.4_46, 0.45_75, 0.51_95, 0.41_55, 0.52_73, 0.5_18, 0.41_16]      )

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





    @skip_mps
    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      return super().test_save_load_local()





    @unittest.skip('non-deterministic pipeline'      )
    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




      return super().test_inference_batch_single_identical()





    @skip_mps
    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      return super().test_dict_tuple_outputs_equivalent()





    @skip_mps
    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      return super().test_save_load_optional_components()





    @skip_mps
    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      return super().test_attention_slicing_forward_pass()






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





    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      a					:      List[Any]    =       load_image(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
          '/cycle-diffusion/black_colored_car.png'      )
      a					:      Any    =       load_numpy(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy'      )
      a					:      Union[str, Any]    =       init_image.resize((5_1_2, 5_1_2)      )

      a					:      Union[str, Any]    =       "CompVis/stable-diffusion-v1-4"
      a					:      Optional[Any]    =       DDIMScheduler.from_pretrained(lowerCAmelCase__    ,		subfolder='scheduler'      )
      a					:      str    =       CycleDiffusionPipeline.from_pretrained(
          lowerCAmelCase__    ,		scheduler=lowerCAmelCase__    ,		safety_checker=lowerCAmelCase__    ,		torch_dtype=torch.floataa    ,		revision='fp16'      )

      pipe.to(lowerCAmelCase__      )
      pipe.set_progress_bar_config(disable=lowerCAmelCase__      )
      pipe.enable_attention_slicing()

      a					:      Dict    =       "A black colored car"
      a					:      Optional[int]    =       "A blue colored car"

      a					:      Optional[int]    =       torch.manual_seed(0      )
      a					:      Tuple    =       pipe(
          prompt=lowerCAmelCase__    ,		source_prompt=lowerCAmelCase__    ,		image=lowerCAmelCase__    ,		num_inference_steps=1_0_0    ,		eta=0.1    ,		strength=0.85    ,		guidance_scale=3    ,		source_guidance_scale=1    ,		generator=lowerCAmelCase__    ,		output_type='np'    ,		)
      a					:      str    =       output.images

      # the values aren't exactly equal, but the images look the same visually
      assert np.abs(image - expected_image      ).max() < 5E-1





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      a					:      Dict    =       load_image(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
          '/cycle-diffusion/black_colored_car.png'      )
      a					:      str    =       load_numpy(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy'      )
      a					:      Union[str, Any]    =       init_image.resize((5_1_2, 5_1_2)      )

      a					:      List[Any]    =       "CompVis/stable-diffusion-v1-4"
      a					:      Union[str, Any]    =       DDIMScheduler.from_pretrained(lowerCAmelCase__    ,		subfolder='scheduler'      )
      a					:      List[str]    =       CycleDiffusionPipeline.from_pretrained(lowerCAmelCase__    ,		scheduler=lowerCAmelCase__    ,		safety_checker=lowerCAmelCase__      )

      pipe.to(lowerCAmelCase__      )
      pipe.set_progress_bar_config(disable=lowerCAmelCase__      )
      pipe.enable_attention_slicing()

      a					:      List[str]    =       "A black colored car"
      a					:      List[Any]    =       "A blue colored car"

      a					:      Optional[int]    =       torch.manual_seed(0      )
      a					:      Union[str, Any]    =       pipe(
          prompt=lowerCAmelCase__    ,		source_prompt=lowerCAmelCase__    ,		image=lowerCAmelCase__    ,		num_inference_steps=1_0_0    ,		eta=0.1    ,		strength=0.85    ,		guidance_scale=3    ,		source_guidance_scale=1    ,		generator=lowerCAmelCase__    ,		output_type='np'    ,		)
      a					:      int    =       output.images

      assert np.abs(image - expected_image      ).max() < 2E-2












"""simple docstring"""


from typing import 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 ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


_UpperCamelCase    :   int   			=						logging.get_logger(__name__)






class 						snake_case  (  UpperCAmelCase	):
    __magic_name__   					=					['''input_features''', '''attention_mask''']





    def __init__(							self     : Optional[int]    ,		A     : Optional[Any]=8_0    ,		A     : str=1_6_0_0_0    ,		A     : List[str]=0.0    ,		A     : Any=1_0    ,		A     : Union[str, Any]=2_5    ,		A     : str="hamming_window"    ,		A     : str=3_27_68.0    ,		A     : Union[str, Any]=0.97    ,		A     : Dict=1.0    ,		A     : Any=True    ,		A     : Union[str, Any]=True    ,		A     : List[Any]=False    ,		**A     : Tuple    ,		):


      '''simple docstring'''




      super().__init__(feature_size=A    ,		sampling_rate=A    ,		padding_value=A    ,		**A      )

      a					:      Any    =       feature_size
      a					:      List[Any]    =       sampling_rate
      a					:      Any    =       padding_value
      a					:      str    =       hop_length
      a					:      Any    =       win_length
      a					:      List[Any]    =       frame_signal_scale
      a					:      Tuple    =       preemphasis_coeff
      a					:      Dict    =       mel_floor
      a					:      Optional[int]    =       normalize_means
      a					:      List[str]    =       normalize_vars
      a					:      Dict    =       win_function
      a					:      Union[str, Any]    =       return_attention_mask

      a					:      List[Any]    =       win_length * sampling_rate // 1_0_0_0
      a					:      Tuple    =       hop_length * sampling_rate // 1_0_0_0

      a					:      List[Any]    =       optimal_fft_length(self.sample_size      )
      a					:      Any    =       (self.n_fft // 2) + 1





    def     lowerCamelCase__				(							self     : List[Any]    ,		A     : np.array      ):


      '''simple docstring'''




      if self.win_function == "hamming_window":
        a					:      List[str]    =       window_function(window_length=self.sample_size    ,		name=self.win_function    ,		periodic=A      )
      else:
        a					:      Dict    =       window_function(window_length=self.sample_size    ,		name=self.win_function      )

      a					:      str    =       mel_filter_bank(
          num_frequency_bins=self.n_freqs    ,		num_mel_filters=self.feature_size    ,		min_frequency=0.0    ,		max_frequency=self.sampling_rate / 2.0    ,		sampling_rate=self.sampling_rate    ,		)

      a					:      List[Any]    =       spectrogram(
          one_waveform * self.frame_signal_scale    ,		window=A    ,		frame_length=self.sample_size    ,		hop_length=self.sample_stride    ,		fft_length=self.n_fft    ,		center=A    ,		preemphasis=self.preemphasis_coeff    ,		mel_filters=A    ,		mel_floor=self.mel_floor    ,		log_mel='log'    ,		)
      return msfc_features.T





    def     lowerCamelCase__				(							self     : int    ,		A     : Tuple    ,		A     : int    ,		A     : Optional[int]      ):


      '''simple docstring'''




      if self.normalize_means:
        a					:      Any    =       x[:input_length].mean(axis=0      )
        a					:      Dict    =       np.subtract(A    ,		A      )
      if self.normalize_vars:
        a					:      Dict    =       x[:input_length].std(axis=0      )
        a					:      Dict    =       np.divide(A    ,		A      )

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

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

      return x





    def     lowerCamelCase__				(							self     : str    ,		A     : List[np.ndarray]    ,		A     : Optional[np.ndarray] = None      ):


      '''simple docstring'''




      a					:      str    =       attention_mask.sum(-1      ) if attention_mask is not None else [x.shape[0] for x in input_features]
      return [self._normalize_one(A    ,		A    ,		self.padding_value      ) for x, n in zip(A    ,		A      )]





    def __call__(							self     : Dict    ,		A     : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]    ,		A     : Union[bool, str, PaddingStrategy] = False    ,		A     : Optional[int] = None    ,		A     : bool = False    ,		A     : Optional[int] = None    ,		A     : Optional[bool] = None    ,		A     : Optional[Union[str, TensorType]] = None    ,		A     : Optional[int] = None    ,		**A     : Union[str, Any]    ,		):


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

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

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

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

      # extract fbank features
      a					:      str    =       [self._extract_mfsc_features(A      ) for one_waveform in raw_speech]

      # convert into correct format for padding
      a					:      int    =       BatchFeature({'input_features': features}      )

      a					:      Union[str, Any]    =       self.pad(
          A    ,		padding=A    ,		max_length=A    ,		truncation=A    ,		pad_to_multiple_of=A    ,		return_attention_mask=A    ,		**A    ,		)
      # make sure list is in array format
      a					:      Optional[Any]    =       padded_inputs.get('input_features'      )
      if isinstance(input_features[0]    ,		A      ):
        a					:      List[str]    =       [np.asarray(A    ,		dtype=np.floataa      ) for feature in input_features]

      a					:      List[Any]    =       padded_inputs.get('attention_mask'      )
      if attention_mask is not None:
        a					:      int    =       [np.asarray(A    ,		dtype=np.intaa      ) for array in attention_mask]

      if self.normalize_means or self.normalize_vars:
        a					:      Any    =       (
            np.array(A    ,		dtype=np.intaa      )
            if self._get_padding_strategies(A    ,		max_length=A      ) is not PaddingStrategy.DO_NOT_PAD
            and padding
            else None
        )
        a					:      List[str]    =       self.normalize(
            padded_inputs['input_features']    ,		attention_mask=A      )

      if return_tensors is not None:
        a					:      Optional[int]    =       padded_inputs.convert_to_tensors(A      )

      return padded_inputs




