
"""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 			lowerCAmelCase_		(__UpperCAmelCase				,      __UpperCAmelCase				,      unittest.TestCase						):


				"""simple docstring"""



				__UpperCamelCase   :		str       =     CycleDiffusionPipeline
				__UpperCamelCase   :		Tuple       =     TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
				    '''negative_prompt''',
				    '''height''',
				    '''width''',
				    '''negative_prompt_embeds''',
				}
				__UpperCamelCase   :		Dict       =     PipelineTesterMixin.required_optional_params - {'''latents'''}
				__UpperCamelCase   :		Union[str, Any]       =     TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''}						)
				__UpperCamelCase   :		int       =     IMAGE_TO_IMAGE_IMAGE_PARAMS
				__UpperCamelCase   :		Optional[Any]       =     IMAGE_TO_IMAGE_IMAGE_PARAMS



				def 			__magic_name__					(self					)      ->	List[Any]:



											"""simple docstring"""




											torch.manual_seed(0					)
											SCREAMING_SNAKE_CASE__		: Optional[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     , )
											SCREAMING_SNAKE_CASE__		: List[str]     =     DDIMScheduler(
											    beta_start=0.00085     , beta_end=0.012     , beta_schedule="""scaled_linear"""     , num_train_timesteps=10_00     , clip_sample=__SCREAMING_SNAKE_CASE     , set_alpha_to_one=__SCREAMING_SNAKE_CASE     , )
											torch.manual_seed(0					)
											SCREAMING_SNAKE_CASE__		: Union[str, 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					)
											SCREAMING_SNAKE_CASE__		: Optional[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=10_00     , )
											SCREAMING_SNAKE_CASE__		: int     =     CLIPTextModel(__SCREAMING_SNAKE_CASE					)
											SCREAMING_SNAKE_CASE__		: List[str]     =     CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""					)

											SCREAMING_SNAKE_CASE__		: Optional[int]     =     {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vae""": vae,
											    """text_encoder""": text_encoder,
											    """tokenizer""": tokenizer,
											    """safety_checker""": None,
											    """feature_extractor""": None,
											}
											return components



				def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__=0					)      ->	List[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     floats_tensor((1, 3, 32, 32)     , rng=random.Random(__SCREAMING_SNAKE_CASE					)					).to(__SCREAMING_SNAKE_CASE					)
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     image / 2 + 0.5
											if str(__SCREAMING_SNAKE_CASE					).startswith("""mps"""					):
																		SCREAMING_SNAKE_CASE__		: Any     =     torch.manual_seed(__SCREAMING_SNAKE_CASE					)
											else:
																		SCREAMING_SNAKE_CASE__		: Tuple     =     torch.Generator(device=__SCREAMING_SNAKE_CASE					).manual_seed(__SCREAMING_SNAKE_CASE					)
											SCREAMING_SNAKE_CASE__		: int     =     {
											    """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 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Dict     =     """cpu"""  # ensure determinism for the device-dependent torch.Generator

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

											SCREAMING_SNAKE_CASE__		: Tuple     =     self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					)
											SCREAMING_SNAKE_CASE__		: Any     =     pipe(**__SCREAMING_SNAKE_CASE					)
											SCREAMING_SNAKE_CASE__		: Dict     =     output.images

											SCREAMING_SNAKE_CASE__		: Optional[int]     =     images[0, -3:, -3:, -1]

											assert images.shape == (1, 32, 32, 3)
											SCREAMING_SNAKE_CASE__		: Optional[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 			__magic_name__					(self					)      ->	int:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Tuple     =     self.get_dummy_components()
											for name, module in components.items():
																		if hasattr(__SCREAMING_SNAKE_CASE     , """half"""					):
																									SCREAMING_SNAKE_CASE__		: Any     =     module.half()
											SCREAMING_SNAKE_CASE__		: Dict     =     CycleDiffusionPipeline(**__SCREAMING_SNAKE_CASE					)
											SCREAMING_SNAKE_CASE__		: Any     =     pipe.to(__SCREAMING_SNAKE_CASE					)
											pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE					)

											SCREAMING_SNAKE_CASE__		: List[Any]     =     self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					)
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     pipe(**__SCREAMING_SNAKE_CASE					)
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     output.images

											SCREAMING_SNAKE_CASE__		: Optional[int]     =     images[0, -3:, -3:, -1]

											assert images.shape == (1, 32, 32, 3)
											SCREAMING_SNAKE_CASE__		: str     =     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 			__magic_name__					(self					)      ->	Optional[int]:



											"""simple docstring"""




											return super().test_save_load_local()



				@unittest.skip("""non-deterministic pipeline"""					)
				def 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											return super().test_inference_batch_single_identical()



				@skip_mps
				def 			__magic_name__					(self					)      ->	List[Any]:



											"""simple docstring"""




											return super().test_dict_tuple_outputs_equivalent()



				@skip_mps
				def 			__magic_name__					(self					)      ->	Dict:



											"""simple docstring"""




											return super().test_save_load_optional_components()



				@skip_mps
				def 			__magic_name__					(self					)      ->	int:



											"""simple docstring"""




											return super().test_attention_slicing_forward_pass()






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


				"""simple docstring"""



				def 			__magic_name__					(self					)      ->	str:



											"""simple docstring"""




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



				def 			__magic_name__					(self					)      ->	Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Dict     =     load_image(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
											    """/cycle-diffusion/black_colored_car.png"""					)
											SCREAMING_SNAKE_CASE__		: int     =     load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy"""					)
											SCREAMING_SNAKE_CASE__		: Dict     =     init_image.resize((5_12, 5_12)					)

											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     """CompVis/stable-diffusion-v1-4"""
											SCREAMING_SNAKE_CASE__		: int     =     DDIMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE     , subfolder="""scheduler"""					)
											SCREAMING_SNAKE_CASE__		: List[Any]     =     CycleDiffusionPipeline.from_pretrained(
											    __SCREAMING_SNAKE_CASE     , scheduler=__SCREAMING_SNAKE_CASE     , safety_checker=__SCREAMING_SNAKE_CASE     , torch_dtype=torch.floataa     , revision="""fp16"""					)

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

											SCREAMING_SNAKE_CASE__		: str     =     """A black colored car"""
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     """A blue colored car"""

											SCREAMING_SNAKE_CASE__		: Any     =     torch.manual_seed(0					)
											SCREAMING_SNAKE_CASE__		: Any     =     pipe(
											    prompt=__SCREAMING_SNAKE_CASE     , source_prompt=__SCREAMING_SNAKE_CASE     , image=__SCREAMING_SNAKE_CASE     , num_inference_steps=1_00     , eta=0.1     , strength=0.85     , guidance_scale=3     , source_guidance_scale=1     , generator=__SCREAMING_SNAKE_CASE     , output_type="""np"""     , )
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     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 			__magic_name__					(self					)      ->	Optional[Any]:



											"""simple docstring"""




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

											SCREAMING_SNAKE_CASE__		: str     =     """CompVis/stable-diffusion-v1-4"""
											SCREAMING_SNAKE_CASE__		: List[str]     =     DDIMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE     , subfolder="""scheduler"""					)
											SCREAMING_SNAKE_CASE__		: Dict     =     CycleDiffusionPipeline.from_pretrained(__SCREAMING_SNAKE_CASE     , scheduler=__SCREAMING_SNAKE_CASE     , safety_checker=__SCREAMING_SNAKE_CASE					)

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

											SCREAMING_SNAKE_CASE__		: Dict     =     """A black colored car"""
											SCREAMING_SNAKE_CASE__		: List[str]     =     """A blue colored car"""

											SCREAMING_SNAKE_CASE__		: Optional[int]     =     torch.manual_seed(0					)
											SCREAMING_SNAKE_CASE__		: Tuple     =     pipe(
											    prompt=__SCREAMING_SNAKE_CASE     , source_prompt=__SCREAMING_SNAKE_CASE     , image=__SCREAMING_SNAKE_CASE     , num_inference_steps=1_00     , eta=0.1     , strength=0.85     , guidance_scale=3     , source_guidance_scale=1     , generator=__SCREAMING_SNAKE_CASE     , output_type="""np"""     , )
											SCREAMING_SNAKE_CASE__		: Any     =     output.images

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






"""simple docstring"""




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
					import torch

if is_vision_available():
					from PIL import Image

					from transformers import MobileViTImageProcessor



class 			lowerCAmelCase_		(unittest.TestCase						):


				"""simple docstring"""



				def __init__(self     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__=7     , SCREAMING_SNAKE_CASE__=3     , SCREAMING_SNAKE_CASE__=18     , SCREAMING_SNAKE_CASE__=30     , SCREAMING_SNAKE_CASE__=4_00     , SCREAMING_SNAKE_CASE__=True     , SCREAMING_SNAKE_CASE__=None     , SCREAMING_SNAKE_CASE__=True     , SCREAMING_SNAKE_CASE__=None     , SCREAMING_SNAKE_CASE__=True     , )      ->	List[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: List[str]     =     size if size is not None else {"""shortest_edge""": 20}
											SCREAMING_SNAKE_CASE__		: List[Any]     =     crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
											SCREAMING_SNAKE_CASE__		: Any     =     parent
											SCREAMING_SNAKE_CASE__		: List[str]     =     batch_size
											SCREAMING_SNAKE_CASE__		: Dict     =     num_channels
											SCREAMING_SNAKE_CASE__		: List[Any]     =     image_size
											SCREAMING_SNAKE_CASE__		: Dict     =     min_resolution
											SCREAMING_SNAKE_CASE__		: Dict     =     max_resolution
											SCREAMING_SNAKE_CASE__		: Optional[int]     =     do_resize
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     size
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     do_center_crop
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     crop_size
											SCREAMING_SNAKE_CASE__		: List[str]     =     do_flip_channel_order



				def 			__magic_name__					(self					)      ->	int:



											"""simple docstring"""




											return {
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "do_center_crop": self.do_center_crop,
											    "crop_size": self.crop_size,
											    "do_flip_channel_order": self.do_flip_channel_order,
											}






@require_torch
@require_vision
class 			lowerCAmelCase_		(a__				,      unittest.TestCase						):


				"""simple docstring"""



				__UpperCamelCase   :		str       =     MobileViTImageProcessor if is_vision_available() else None



				def 			__magic_name__					(self					)      ->	int:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     MobileViTImageProcessingTester(self					)



				@property
				def 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											return self.image_processor_tester.prepare_image_processor_dict()



				def 			__magic_name__					(self					)      ->	Optional[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     self.image_processing_class(**self.image_processor_dict					)
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__     , """do_resize"""					)					)
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__     , """size"""					)					)
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__     , """do_center_crop"""					)					)
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__     , """center_crop"""					)					)
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__     , """do_flip_channel_order"""					)					)



				def 			__magic_name__					(self					)      ->	Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Dict     =     self.image_processing_class.from_dict(self.image_processor_dict					)
											self.assertEqual(image_processor.size     , {"""shortest_edge""": 20}					)
											self.assertEqual(image_processor.crop_size     , {"""height""": 18, """width""": 18}					)

											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     self.image_processing_class.from_dict(self.image_processor_dict     , size=42     , crop_size=84					)
											self.assertEqual(image_processor.size     , {"""shortest_edge""": 42}					)
											self.assertEqual(image_processor.crop_size     , {"""height""": 84, """width""": 84}					)



				def 			__magic_name__					(self					)      ->	Union[str, Any]:



											"""simple docstring"""




											pass



				def 			__magic_name__					(self					)      ->	Optional[int]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: List[str]     =     self.image_processing_class(**self.image_processor_dict					)
											# create random PIL images
											SCREAMING_SNAKE_CASE__		: List[str]     =     prepare_image_inputs(self.image_processor_tester     , equal_resolution=SCREAMING_SNAKE_CASE__					)
											for image in image_inputs:
																		self.assertIsInstance(SCREAMING_SNAKE_CASE__     , Image.Image					)

											# Test not batched input
											SCREAMING_SNAKE_CASE__		: Dict     =     image_processing(image_inputs[0]     , return_tensors="""pt"""					).pixel_values
											self.assertEqual(
											    encoded_images.shape     , (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )     , )

											# Test batched
											SCREAMING_SNAKE_CASE__		: List[str]     =     image_processing(SCREAMING_SNAKE_CASE__     , return_tensors="""pt"""					).pixel_values
											self.assertEqual(
											    encoded_images.shape     , (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )     , )



				def 			__magic_name__					(self					)      ->	int:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[int]     =     self.image_processing_class(**self.image_processor_dict					)
											# create random numpy tensors
											SCREAMING_SNAKE_CASE__		: Tuple     =     prepare_image_inputs(self.image_processor_tester     , equal_resolution=SCREAMING_SNAKE_CASE__     , numpify=SCREAMING_SNAKE_CASE__					)
											for image in image_inputs:
																		self.assertIsInstance(SCREAMING_SNAKE_CASE__     , np.ndarray					)

											# Test not batched input
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     image_processing(image_inputs[0]     , return_tensors="""pt"""					).pixel_values
											self.assertEqual(
											    encoded_images.shape     , (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )     , )

											# Test batched
											SCREAMING_SNAKE_CASE__		: Optional[int]     =     image_processing(SCREAMING_SNAKE_CASE__     , return_tensors="""pt"""					).pixel_values
											self.assertEqual(
											    encoded_images.shape     , (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )     , )



				def 			__magic_name__					(self					)      ->	Optional[int]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: List[Any]     =     self.image_processing_class(**self.image_processor_dict					)
											# create random PyTorch tensors
											SCREAMING_SNAKE_CASE__		: Any     =     prepare_image_inputs(self.image_processor_tester     , equal_resolution=SCREAMING_SNAKE_CASE__     , torchify=SCREAMING_SNAKE_CASE__					)
											for image in image_inputs:
																		self.assertIsInstance(SCREAMING_SNAKE_CASE__     , torch.Tensor					)

											# Test not batched input
											SCREAMING_SNAKE_CASE__		: List[str]     =     image_processing(image_inputs[0]     , return_tensors="""pt"""					).pixel_values
											self.assertEqual(
											    encoded_images.shape     , (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )     , )

											# Test batched
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     image_processing(SCREAMING_SNAKE_CASE__     , return_tensors="""pt"""					).pixel_values
											self.assertEqual(
											    encoded_images.shape     , (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )     , )




