


'''simple docstring'''



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	):
					lowerCAmelCase      :Optional[int]   =					CycleDiffusionPipeline
					lowerCAmelCase      :Optional[int]   =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
					    '''negative_prompt''',
					    '''height''',
					    '''width''',
					    '''negative_prompt_embeds''',
					}
					lowerCAmelCase      :Tuple   =					PipelineTesterMixin.required_optional_params - {'''latents'''}
					lowerCAmelCase      :Optional[int]   =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''}	)
					lowerCAmelCase      :int   =					IMAGE_TO_IMAGE_IMAGE_PARAMS
					lowerCAmelCase      :List[Any]   =					IMAGE_TO_IMAGE_IMAGE_PARAMS




					def 				snake_case__						(      self):
								torch.manual_seed(0)
								UpperCAmelCase__  :					int        =     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							,							)
								UpperCAmelCase__  :					Tuple        =     DDIMScheduler(
								    beta_start=0.00085							,							beta_end=0.012							,							beta_schedule="""scaled_linear"""							,							num_train_timesteps=1000							,							clip_sample=_lowerCamelCase							,							set_alpha_to_one=_lowerCamelCase							,							)
								torch.manual_seed(0)
								UpperCAmelCase__  :					Any        =     AutoencoderKL(
								    block_out_channels=[32, 64]							,							in_channels=3							,							out_channels=3							,							down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]							,							up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]							,							latent_channels=4							,							)
								torch.manual_seed(0)
								UpperCAmelCase__  :					Dict        =     CLIPTextConfig(
								    bos_token_id=0							,							eos_token_id=2							,							hidden_size=32							,							intermediate_size=37							,							layer_norm_eps=1e-0_5							,							num_attention_heads=4							,							num_hidden_layers=5							,							pad_token_id=1							,							vocab_size=1000							,							)
								UpperCAmelCase__  :					Optional[int]        =     CLIPTextModel(_lowerCamelCase)
								UpperCAmelCase__  :					Optional[Any]        =     CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

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




					def 				snake_case__						(      self							,							_lowerCamelCase							,							_lowerCamelCase=0):
								UpperCAmelCase__  :					Optional[Any]        =     floats_tensor((1, 3, 32, 32)							,							rng=random.Random(_lowerCamelCase)).to(_lowerCamelCase)
								UpperCAmelCase__  :					Optional[int]        =     image / 2 + 0.5
								if str(_lowerCamelCase).startswith("""mps"""):
											UpperCAmelCase__  :					Dict        =     torch.manual_seed(_lowerCamelCase)
								else:
											UpperCAmelCase__  :					Tuple        =     torch.Generator(device=_lowerCamelCase).manual_seed(_lowerCamelCase)
								UpperCAmelCase__  :					List[str]        =     {
								    """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 				snake_case__						(      self):
								UpperCAmelCase__  :					Dict        =     """cpu"""  # ensure determinism for the device-dependent torch.Generator

								UpperCAmelCase__  :					Dict        =     self.get_dummy_components()
								UpperCAmelCase__  :					Any        =     CycleDiffusionPipeline(**_lowerCamelCase)
								UpperCAmelCase__  :					Optional[Any]        =     pipe.to(_lowerCamelCase)
								pipe.set_progress_bar_config(disable=_lowerCamelCase)

								UpperCAmelCase__  :					Dict        =     self.get_dummy_inputs(_lowerCamelCase)
								UpperCAmelCase__  :					Optional[Any]        =     pipe(**_lowerCamelCase)
								UpperCAmelCase__  :					Any        =     output.images

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

								assert images.shape == (1, 32, 32, 3)
								UpperCAmelCase__  :					Union[str, Any]        =     np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179])

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




					@unittest.skipIf(torch_device != """cuda"""							,							"""This test requires a GPU""")
					def 				snake_case__						(      self):
								UpperCAmelCase__  :					Any        =     self.get_dummy_components()
								for name, module in components.items():
											if hasattr(_lowerCamelCase							,							"""half"""):
														UpperCAmelCase__  :					str        =     module.half()
								UpperCAmelCase__  :					Dict        =     CycleDiffusionPipeline(**_lowerCamelCase)
								UpperCAmelCase__  :					Tuple        =     pipe.to(_lowerCamelCase)
								pipe.set_progress_bar_config(disable=_lowerCamelCase)

								UpperCAmelCase__  :					Optional[int]        =     self.get_dummy_inputs(_lowerCamelCase)
								UpperCAmelCase__  :					List[Any]        =     pipe(**_lowerCamelCase)
								UpperCAmelCase__  :					Tuple        =     output.images

								UpperCAmelCase__  :					List[str]        =     images[0, -3:, -3:, -1]

								assert images.shape == (1, 32, 32, 3)
								UpperCAmelCase__  :					int        =     np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116])

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




					@skip_mps
					def 				snake_case__						(      self):
								return super().test_save_load_local()




					@unittest.skip("""non-deterministic pipeline""")
					def 				snake_case__						(      self):
								return super().test_inference_batch_single_identical()




					@skip_mps
					def 				snake_case__						(      self):
								return super().test_dict_tuple_outputs_equivalent()




					@skip_mps
					def 				snake_case__						(      self):
								return super().test_save_load_optional_components()




					@skip_mps
					def 				snake_case__						(      self):
								return super().test_attention_slicing_forward_pass()


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




					def 				snake_case__						(      self):
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()




					def 				snake_case__						(      self):
								UpperCAmelCase__  :					List[str]        =     load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
								    """/cycle-diffusion/black_colored_car.png""")
								UpperCAmelCase__  :					str        =     load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy""")
								UpperCAmelCase__  :					Any        =     init_image.resize((512, 512))

								UpperCAmelCase__  :					Union[str, Any]        =     """CompVis/stable-diffusion-v1-4"""
								UpperCAmelCase__  :					Tuple        =     DDIMScheduler.from_pretrained(_lowerCamelCase							,							subfolder="""scheduler""")
								UpperCAmelCase__  :					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()

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

								UpperCAmelCase__  :					Optional[Any]        =     torch.manual_seed(0)
								UpperCAmelCase__  :					List[str]        =     pipe(
								    prompt=_lowerCamelCase							,							source_prompt=_lowerCamelCase							,							image=_lowerCamelCase							,							num_inference_steps=100							,							eta=0.1							,							strength=0.85							,							guidance_scale=3							,							source_guidance_scale=1							,							generator=_lowerCamelCase							,							output_type="""np"""							,							)
								UpperCAmelCase__  :					Dict        =     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 				snake_case__						(      self):
								UpperCAmelCase__  :					List[str]        =     load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
								    """/cycle-diffusion/black_colored_car.png""")
								UpperCAmelCase__  :					Any        =     load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy""")
								UpperCAmelCase__  :					Tuple        =     init_image.resize((512, 512))

								UpperCAmelCase__  :					Optional[int]        =     """CompVis/stable-diffusion-v1-4"""
								UpperCAmelCase__  :					str        =     DDIMScheduler.from_pretrained(_lowerCamelCase							,							subfolder="""scheduler""")
								UpperCAmelCase__  :					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()

								UpperCAmelCase__  :					Optional[Any]        =     """A black colored car"""
								UpperCAmelCase__  :					Optional[Any]        =     """A blue colored car"""

								UpperCAmelCase__  :					Union[str, Any]        =     torch.manual_seed(0)
								UpperCAmelCase__  :					Optional[Any]        =     pipe(
								    prompt=_lowerCamelCase							,							source_prompt=_lowerCamelCase							,							image=_lowerCamelCase							,							num_inference_steps=100							,							eta=0.1							,							strength=0.85							,							guidance_scale=3							,							source_guidance_scale=1							,							generator=_lowerCamelCase							,							output_type="""np"""							,							)
								UpperCAmelCase__  :					Dict        =     output.images

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



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


__A	=logging.get_logger(__name__)


class 		_snake_case					(     a__	):
					lowerCAmelCase      :int   =					['''input_features''', '''is_longer''']




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




					def 				snake_case__						(      self):
								UpperCAmelCase__  :					List[Any]        =     copy.deepcopy(self.__dict__)
								UpperCAmelCase__  :					Optional[int]        =     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 				snake_case__						(      self							,							_lowerCamelCase							,							_lowerCamelCase = None):
								UpperCAmelCase__  :					str        =     spectrogram(
								    _lowerCamelCase							,							window_function(self.fft_window_size							,							"""hann""")							,							frame_length=self.fft_window_size							,							hop_length=self.hop_length							,							power=2.0							,							mel_filters=_lowerCamelCase							,							log_mel="""dB"""							,							)
								return log_mel_spectrogram.T




					def 				snake_case__						(      self							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase):
								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__  :					List[Any]        =     [0]
								if len(ranges[2]) == 0:
											# if the audio is too short, we just use the first chunk
											UpperCAmelCase__  :					Union[str, Any]        =     [0]
								# randomly choose index for each part
								UpperCAmelCase__  :					List[str]        =     np.random.choice(ranges[0])
								UpperCAmelCase__  :					Optional[int]        =     np.random.choice(ranges[1])
								UpperCAmelCase__  :					List[str]        =     np.random.choice(ranges[2])

								UpperCAmelCase__  :					str        =     mel[idx_front : idx_front + chunk_frames, :]
								UpperCAmelCase__  :					Optional[int]        =     mel[idx_middle : idx_middle + chunk_frames, :]
								UpperCAmelCase__  :					Tuple        =     mel[idx_back : idx_back + chunk_frames, :]

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




					def 				snake_case__						(      self							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase):
								if waveform.shape[0] > max_length:
											if truncation == "rand_trunc":
														UpperCAmelCase__  :					List[str]        =     True
														# random crop to max_length (for compatibility) -> this should be handled by self.pad
														UpperCAmelCase__  :					List[Any]        =     len(_lowerCamelCase) - max_length
														UpperCAmelCase__  :					Optional[Any]        =     np.random.randint(0							,							overflow + 1)
														UpperCAmelCase__  :					int        =     waveform[idx : idx + max_length]
														UpperCAmelCase__  :					Tuple        =     self._np_extract_fbank_features(_lowerCamelCase							,							self.mel_filters_slaney)[None, :]
											elif truncation == "fusion":
														UpperCAmelCase__  :					Any        =     self._np_extract_fbank_features(_lowerCamelCase							,							self.mel_filters)
														UpperCAmelCase__  :					int        =     max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
														UpperCAmelCase__  :					int        =     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__  :					Optional[Any]        =     np.stack([mel, mel, mel, mel]							,							axis=0)
																	UpperCAmelCase__  :					List[Any]        =     False
														else:
																	UpperCAmelCase__  :					Tuple        =     self._random_mel_fusion(_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase)
																	UpperCAmelCase__  :					str        =     True
											else:
														raise NotImplementedError(f'''data_truncating {truncation} not implemented''')

								else:
											UpperCAmelCase__  :					str        =     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__  :					int        =     int(max_length / len(_lowerCamelCase))
																	UpperCAmelCase__  :					int        =     np.stack(np.tile(_lowerCamelCase							,							n_repeat + 1))[:max_length]
														if padding == "repeatpad":
																	UpperCAmelCase__  :					str        =     int(max_length / len(_lowerCamelCase))
																	UpperCAmelCase__  :					str        =     np.stack(np.tile(_lowerCamelCase							,							_lowerCamelCase))
														UpperCAmelCase__  :					Optional[Any]        =     np.pad(_lowerCamelCase							,							(0, max_length - waveform.shape[0])							,							mode="""constant"""							,							constant_values=0)

											if truncation == "fusion":
														UpperCAmelCase__  :					List[Any]        =     self._np_extract_fbank_features(_lowerCamelCase							,							self.mel_filters)
														UpperCAmelCase__  :					Dict        =     np.stack([input_mel, input_mel, input_mel, input_mel]							,							axis=0)
											else:
														UpperCAmelCase__  :					int        =     self._np_extract_fbank_features(_lowerCamelCase							,							self.mel_filters_slaney)[None, :]

								return input_mel, longer




					def __call__(      self							,							_lowerCamelCase							,							_lowerCamelCase = None							,							_lowerCamelCase = None							,							_lowerCamelCase = None							,							_lowerCamelCase = None							,							_lowerCamelCase = None							,							**_lowerCamelCase							,							):
								UpperCAmelCase__  :					Dict        =     truncation if truncation is not None else self.truncation
								UpperCAmelCase__  :					List[Any]        =     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__  :					int        =     isinstance(_lowerCamelCase							,							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__  :					List[str]        =     is_batched_numpy or (
								    isinstance(_lowerCamelCase							,							(list, tuple)) and (isinstance(raw_speech[0]							,							(np.ndarray, tuple, list)))
								)

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

								# always return batch
								if not is_batched:
											UpperCAmelCase__  :					int        =     [np.asarray(_lowerCamelCase)]

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

								UpperCAmelCase__  :					int        =     []
								UpperCAmelCase__  :					List[str]        =     []
								for mel, longer in padded_inputs:
											input_mel.append(_lowerCamelCase)
											is_longer.append(_lowerCamelCase)

								if truncation == "fusion" and sum(_lowerCamelCase) == 0:
											# if no audio is longer than 10s, then randomly select one audio to be longer
											UpperCAmelCase__  :					Optional[int]        =     np.random.randint(0							,							len(_lowerCamelCase))
											UpperCAmelCase__  :					Tuple        =     True

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

								# is_longer is a list of bool
								UpperCAmelCase__  :					str        =     [[longer] for longer in is_longer]

								UpperCAmelCase__  :					Optional[int]        =     {"""input_features""": input_mel, """is_longer""": is_longer}
								UpperCAmelCase__  :					Optional[int]        =     BatchFeature(_lowerCamelCase)

								if return_tensors is not None:
											UpperCAmelCase__  :					str        =     input_features.convert_to_tensors(_lowerCamelCase)

								return input_features