


import unittest
from typing import Dict, List, Optional, Union

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 BridgeTowerImageProcessor

class        a	(unittest.TestCase   ):




							"""simple docstring"""


							def __init__(							self :						str					,			lowerCamelCase :						str					,			lowerCamelCase :						bool = True					,			lowerCamelCase :						Dict[str, int] = None					,			lowerCamelCase :						int = 32					,			lowerCamelCase :						bool = True					,			lowerCamelCase :						Union[int, float] = 1 / 255					,			lowerCamelCase :						bool = True					,			lowerCamelCase :						bool = True					,			lowerCamelCase :						Optional[Union[float, List[float]]] = [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]					,			lowerCamelCase :						Optional[Union[float, List[float]]] = [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]					,			lowerCamelCase :						bool = True					,			lowerCamelCase :						Optional[int]=7					,			lowerCamelCase :						str=30					,			lowerCamelCase :						int=400					,			lowerCamelCase :						Optional[Any]=3					,			)			->					List[str]:
														__snake_case	:    Optional[int]											=     parent
														__snake_case	:    Optional[Any]											=     do_resize
														__snake_case	:    Dict											=     size if size is not None else {"shortest_edge": 288}
														__snake_case	:    Any											=     size_divisor
														__snake_case	:    Tuple											=     do_rescale
														__snake_case	:    Optional[Any]											=     rescale_factor
														__snake_case	:    Tuple											=     do_normalize
														__snake_case	:    Dict											=     do_center_crop
														__snake_case	:    int											=     image_mean
														__snake_case	:    Tuple											=     image_std
														__snake_case	:    Tuple											=     do_pad
														__snake_case	:    Union[str, Any]											=     batch_size
														__snake_case	:    List[str]											=     num_channels
														__snake_case	:    Optional[int]											=     min_resolution
														__snake_case	:    Optional[int]											=     max_resolution

							def 					__snake_case      (							self :						List[Any]       )			->					Union[str, Any]:
														return {
														    "image_mean": self.image_mean,
														    "image_std": self.image_std,
														    "do_normalize": self.do_normalize,
														    "do_resize": self.do_resize,
														    "size": self.size,
														    "size_divisor": self.size_divisor,
														}






							def 					__snake_case      (							self :						int					,			lowerCamelCase :						Optional[Any]					,			lowerCamelCase :						int=False       )			->					List[str]:
														if not batched:
																					__snake_case	:    List[Any]											=     self.size["shortest_edge"]
																					__snake_case	:    int											=     image_inputs[0]
																					if isinstance(lowerCamelCase					,			Image.Image       ):
																												__snake_case				,    __snake_case	:    List[Any]											=     image.size
																					else:
																												__snake_case				,    __snake_case	:    int											=     image.shape[1], image.shape[2]
																					__snake_case	:    Any											=     size / min(lowerCamelCase					,			lowerCamelCase       )
																					if h < w:
																												__snake_case				,    __snake_case	:    List[str]											=     size, scale * w
																					else:
																												__snake_case				,    __snake_case	:    Union[str, Any]											=     scale * h, size

																					__snake_case	:    int											=     int((1333 / 800) * size       )
																					if max(lowerCamelCase					,			lowerCamelCase       ) > max_size:
																												__snake_case	:    Union[str, Any]											=     max_size / max(lowerCamelCase					,			lowerCamelCase       )
																												__snake_case	:    int											=     newh * scale
																												__snake_case	:    Tuple											=     neww * scale

																					__snake_case				,    __snake_case	:    int											=     int(newh + 0.5       ), int(neww + 0.5       )
																					__snake_case				,    __snake_case	:    str											=     (
																					    newh // self.size_divisor * self.size_divisor,
																					    neww // self.size_divisor * self.size_divisor,
																					)

														else:
																					__snake_case	:    Optional[Any]											=     []
																					for image in image_inputs:
																												__snake_case				,    __snake_case	:    Dict											=     self.get_expected_values([image]       )
																												expected_values.append((expected_height, expected_width)       )
																					__snake_case	:    Any											=     max(lowerCamelCase					,			key=lambda lowerCamelCase       : item[0]       )[0]
																					__snake_case	:    Union[str, Any]											=     max(lowerCamelCase					,			key=lambda lowerCamelCase       : item[1]       )[1]

														return expected_height, expected_width

@require_torch
@require_vision
class        a	(_lowerCAmelCase  ,       unittest.TestCase   ):




							"""simple docstring"""


							__UpperCAmelCase					:							Optional[Any]  						=						BridgeTowerImageProcessor if is_vision_available() else None

							def 					__snake_case      (							self :						List[Any]       )			->					List[str]:
														__snake_case	:    Dict											=     BridgeTowerImageProcessingTester(self       )

							@property
							def 					__snake_case      (							self :						List[str]       )			->					Dict:
														return self.image_processor_tester.prepare_image_processor_dict()

							def 					__snake_case      (							self :						Any       )			->					Union[str, Any]:
														__snake_case	:    Union[str, Any]											=     self.image_processing_class(**self.image_processor_dict       )
														self.assertTrue(hasattr(lowerCamelCase					,			"image_mean"       )       )
														self.assertTrue(hasattr(lowerCamelCase					,			"image_std"       )       )
														self.assertTrue(hasattr(lowerCamelCase					,			"do_normalize"       )       )
														self.assertTrue(hasattr(lowerCamelCase					,			"do_resize"       )       )
														self.assertTrue(hasattr(lowerCamelCase					,			"size"       )       )
														self.assertTrue(hasattr(lowerCamelCase					,			"size_divisor"       )       )

							def 					__snake_case      (							self :						Tuple       )			->					int:
														pass

							def 					__snake_case      (							self :						str       )			->					Optional[int]:
														# Initialize image processor
														__snake_case	:    Tuple											=     self.image_processing_class(**self.image_processor_dict       )
														# create random PIL images
														__snake_case	:    Optional[Any]											=     prepare_image_inputs(self.image_processor_tester					,			equal_resolution=lowerCamelCase       )
														for image in image_inputs:
																					self.assertIsInstance(lowerCamelCase					,			Image.Image       )

														# Test not batched input
														__snake_case	:    int											=     image_processing(image_inputs[0]					,			return_tensors="pt"       ).pixel_values

														__snake_case				,    __snake_case	:    Union[str, Any]											=     self.image_processor_tester.get_expected_values(lowerCamelCase       )
														self.assertEqual(
														    encoded_images.shape					,			(1, self.image_processor_tester.num_channels, expected_height, expected_width)					,			)

														# Test batched
														__snake_case	:    Optional[int]											=     image_processing(lowerCamelCase					,			return_tensors="pt"       ).pixel_values

														__snake_case				,    __snake_case	:    Dict											=     self.image_processor_tester.get_expected_values(lowerCamelCase					,			batched=lowerCamelCase       )
														self.assertEqual(
														    encoded_images.shape					,			(
														        self.image_processor_tester.batch_size,
														        self.image_processor_tester.num_channels,
														        expected_height,
														        expected_width,
														    )					,			)

							def 					__snake_case      (							self :						Union[str, Any]       )			->					Any:
														# Initialize image processor
														__snake_case	:    Dict											=     self.image_processing_class(**self.image_processor_dict       )
														# create random numpy tensors
														__snake_case	:    List[Any]											=     prepare_image_inputs(self.image_processor_tester					,			equal_resolution=lowerCamelCase					,			numpify=lowerCamelCase       )
														for image in image_inputs:
																					self.assertIsInstance(lowerCamelCase					,			np.ndarray       )

														# Test not batched input
														__snake_case	:    int											=     image_processing(image_inputs[0]					,			return_tensors="pt"       ).pixel_values

														__snake_case				,    __snake_case	:    int											=     self.image_processor_tester.get_expected_values(lowerCamelCase       )
														self.assertEqual(
														    encoded_images.shape					,			(1, self.image_processor_tester.num_channels, expected_height, expected_width)					,			)

														# Test batched
														__snake_case	:    Optional[int]											=     image_processing(lowerCamelCase					,			return_tensors="pt"       ).pixel_values

														__snake_case				,    __snake_case	:    List[Any]											=     self.image_processor_tester.get_expected_values(lowerCamelCase					,			batched=lowerCamelCase       )
														self.assertEqual(
														    encoded_images.shape					,			(
														        self.image_processor_tester.batch_size,
														        self.image_processor_tester.num_channels,
														        expected_height,
														        expected_width,
														    )					,			)






							def 					__snake_case      (							self :						Any       )			->					Optional[Any]:
														# Initialize image processor
														__snake_case	:    str											=     self.image_processing_class(**self.image_processor_dict       )
														# create random PyTorch tensors
														__snake_case	:    Any											=     prepare_image_inputs(self.image_processor_tester					,			equal_resolution=lowerCamelCase					,			torchify=lowerCamelCase       )
														for image in image_inputs:
																					self.assertIsInstance(lowerCamelCase					,			torch.Tensor       )

														# Test not batched input
														__snake_case	:    str											=     image_processing(image_inputs[0]					,			return_tensors="pt"       ).pixel_values

														__snake_case				,    __snake_case	:    Dict											=     self.image_processor_tester.get_expected_values(lowerCamelCase       )
														self.assertEqual(
														    encoded_images.shape					,			(1, self.image_processor_tester.num_channels, expected_height, expected_width)					,			)

														# Test batched
														__snake_case	:    List[Any]											=     image_processing(lowerCamelCase					,			return_tensors="pt"       ).pixel_values

														__snake_case				,    __snake_case	:    Dict											=     self.image_processor_tester.get_expected_values(lowerCamelCase					,			batched=lowerCamelCase       )
														self.assertEqual(
														    encoded_images.shape					,			(
														        self.image_processor_tester.batch_size,
														        self.image_processor_tester.num_channels,
														        expected_height,
														        expected_width,
														    )					,			)





import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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        a	(_lowerCAmelCase  ,       _lowerCAmelCase  ,       unittest.TestCase   ):




							"""simple docstring"""


							__UpperCAmelCase					:							Optional[Any]  						=						StableDiffusionXLImgaImgPipeline
							__UpperCAmelCase					:							Any  						=						TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
							__UpperCAmelCase					:							Dict  						=						PipelineTesterMixin.required_optional_params - {"latents"}
							__UpperCAmelCase					:							Union[str, Any]  						=						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							__UpperCAmelCase					:							Tuple  						=						IMAGE_TO_IMAGE_IMAGE_PARAMS
							__UpperCAmelCase					:							str  						=						IMAGE_TO_IMAGE_IMAGE_PARAMS

							def 					__snake_case      (							self :						Optional[Any]       )			->					Tuple:
														torch.manual_seed(0       )
														__snake_case	:    Optional[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")					,			attention_head_dim=(2, 4)					,			use_linear_projection=lowerCamelCase					,			addition_embed_type="text_time"					,			addition_time_embed_dim=8					,			transformer_layers_per_block=(1, 2)					,			projection_class_embeddings_input_dim=80					,			cross_attention_dim=64					,			)
														__snake_case	:    Tuple											=     EulerDiscreteScheduler(
														    beta_start=0.0_00_85					,			beta_end=0.0_12					,			steps_offset=1					,			beta_schedule="scaled_linear"					,			timestep_spacing="leading"					,			)
														torch.manual_seed(0       )
														__snake_case	:    int											=     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					,			sample_size=128					,			)
														torch.manual_seed(0       )
														__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=1000					,			hidden_act="gelu"					,			projection_dim=32					,			)
														__snake_case	:    List[str]											=     CLIPTextModel(lowerCamelCase       )
														__snake_case	:    Any											=     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					,			local_files_only=lowerCamelCase       )

														__snake_case	:    List[str]											=     CLIPTextModelWithProjection(lowerCamelCase       )
														__snake_case	:    List[Any]											=     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					,			local_files_only=lowerCamelCase       )

														__snake_case	:    Optional[int]											=     {
														    "unet": unet,
														    "scheduler": scheduler,
														    "vae": vae,
														    "text_encoder": text_encoder,
														    "tokenizer": tokenizer,
														    "text_encoder_2": text_encoder_a,
														    "tokenizer_2": tokenizer_a,
														    # "safety_checker": None,
														    # "feature_extractor": None,
														}
														return components

							def 					__snake_case      (							self :						Optional[Any]					,			lowerCamelCase :						List[Any]					,			lowerCamelCase :						List[Any]=0       )			->					Union[str, Any]:
														__snake_case	:    int											=     floats_tensor((1, 3, 32, 32)					,			rng=random.Random(lowerCamelCase       )       ).to(lowerCamelCase       )
														__snake_case	:    Any											=     image / 2 + 0.5
														if str(lowerCamelCase       ).startswith("mps"       ):
																					__snake_case	:    Dict											=     torch.manual_seed(lowerCamelCase       )
														else:
																					__snake_case	:    int											=     torch.Generator(device=lowerCamelCase       ).manual_seed(lowerCamelCase       )
														__snake_case	:    Optional[Any]											=     {
														    "prompt": "A painting of a squirrel eating a burger",
														    "image": image,
														    "generator": generator,
														    "num_inference_steps": 2,
														    "guidance_scale": 5.0,
														    "output_type": "numpy",
														    "strength": 0.75,
														}
														return inputs

							def 					__snake_case      (							self :						Dict       )			->					Any:
														__snake_case	:    Dict											=     "cpu"  # ensure determinism for the device-dependent torch.Generator
														__snake_case	:    Any											=     self.get_dummy_components()
														__snake_case	:    int											=     StableDiffusionXLImgaImgPipeline(**lowerCamelCase       )
														__snake_case	:    List[str]											=     sd_pipe.to(lowerCamelCase       )
														sd_pipe.set_progress_bar_config(disable=lowerCamelCase       )

														__snake_case	:    Tuple											=     self.get_dummy_inputs(lowerCamelCase       )
														__snake_case	:    Dict											=     sd_pipe(**lowerCamelCase       ).images
														__snake_case	:    Dict											=     image[0, -3:, -3:, -1]

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

														__snake_case	:    str											=     np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65]       )

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

							def 					__snake_case      (							self :						str       )			->					Optional[Any]:
														super().test_attention_slicing_forward_pass(expected_max_diff=3E-3       )

							def 					__snake_case      (							self :						Any       )			->					Dict:
														super().test_inference_batch_single_identical(expected_max_diff=3E-3       )

							def 					__snake_case      (							self :						str       )			->					Optional[int]:
														pass






							def 					__snake_case      (							self :						Tuple       )			->					Union[str, Any]:
														__snake_case	:    str											=     self.get_dummy_components()
														__snake_case	:    List[Any]											=     StableDiffusionXLImgaImgPipeline(**lowerCamelCase       )
														__snake_case	:    Optional[Any]											=     sd_pipe.to(lowerCamelCase       )
														__snake_case	:    int											=     sd_pipe.to(lowerCamelCase       )
														sd_pipe.set_progress_bar_config(disable=lowerCamelCase       )

														# forward without prompt embeds
														__snake_case	:    List[str]											=     self.get_dummy_inputs(lowerCamelCase       )
														__snake_case	:    str											=     3 * ["this is a negative prompt"]
														__snake_case	:    Any											=     negative_prompt
														__snake_case	:    Optional[Any]											=     3 * [inputs["prompt"]]

														__snake_case	:    int											=     sd_pipe(**lowerCamelCase       )
														__snake_case	:    List[Any]											=     output.images[0, -3:, -3:, -1]

														# forward with prompt embeds
														__snake_case	:    List[Any]											=     self.get_dummy_inputs(lowerCamelCase       )
														__snake_case	:    Optional[Any]											=     3 * ["this is a negative prompt"]
														__snake_case	:    int											=     3 * [inputs.pop("prompt"       )]

														(
														    (
														    __snake_case
														)				,    (
														    __snake_case
														)				,    (
														    __snake_case
														)				,    (
														    __snake_case
														)				,    
														)	:    Dict											=     sd_pipe.encode_prompt(lowerCamelCase					,			negative_prompt=lowerCamelCase       )

														__snake_case	:    Tuple											=     sd_pipe(
														    **lowerCamelCase					,			prompt_embeds=lowerCamelCase					,			negative_prompt_embeds=lowerCamelCase					,			pooled_prompt_embeds=lowerCamelCase					,			negative_pooled_prompt_embeds=lowerCamelCase					,			)
														__snake_case	:    List[str]											=     output.images[0, -3:, -3:, -1]

														# make sure that it's equal
														assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()       ).max() < 1E-4

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




							"""simple docstring"""


							def 					__snake_case      (							self :						Optional[int]       )			->					Dict:
														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()

							def 					__snake_case      (							self :						Optional[Any]					,			lowerCamelCase :						Any					,			lowerCamelCase :						Optional[Any]="cpu"					,			lowerCamelCase :						str=torch.floataa					,			lowerCamelCase :						int=0       )			->					Dict:
														__snake_case	:    int											=     torch.Generator(device=lowerCamelCase       ).manual_seed(lowerCamelCase       )
														__snake_case	:    Optional[Any]											=     np.random.RandomState(lowerCamelCase       ).standard_normal((1, 4, 64, 64)       )
														__snake_case	:    Optional[Any]											=     torch.from_numpy(lowerCamelCase       ).to(device=lowerCamelCase					,			dtype=lowerCamelCase       )
														__snake_case	:    List[str]											=     {
														    "prompt": "a photograph of an astronaut riding a horse",
														    "latents": latents,
														    "generator": generator,
														    "num_inference_steps": 3,
														    "guidance_scale": 7.5,
														    "output_type": "numpy",
														}
														return inputs






							def 					__snake_case      (							self :						str       )			->					Any:
														__snake_case	:    List[str]											=     DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base"       )
														pipe.to(lowerCamelCase       )
														pipe.set_progress_bar_config(disable=lowerCamelCase       )

														__snake_case	:    int											=     self.get_inputs(lowerCamelCase       )
														__snake_case	:    Optional[Any]											=     pipe(**lowerCamelCase       ).images
														__snake_case	:    Any											=     image[0, -3:, -3:, -1].flatten()

														assert image.shape == (1, 512, 512, 3)
														__snake_case	:    Optional[int]											=     np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]       )
														assert np.abs(image_slice - expected_slice       ).max() < 7E-3

