






import math
from typing import Dict, Iterable, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
  import torch

if is_vision_available():
  import PIL


SCREAMING_SNAKE_CASE 							=						logging.get_logger(__name__)

def      _lowerCamelCase	(						__A    :							np.ndarray		,		__A    :							Union[int, Iterable[int]]		,		__A    :							bool		,		__A    :							int )      ->					Tuple[int, int]:
    def constraint_to_multiple_of(__A    :							Dict		,		__A    :							Optional[Any]		,		__A    :							List[Any]=0		,		__A    :							Tuple=None ):
        _UpperCAmelCase				:      List[Any]			  =				round(val / multiple ) * multiple

        if max_val is not None and x > max_val:
            _UpperCAmelCase				:      Dict			  =				math.floor(val / multiple ) * multiple

        if x < min_val:
            _UpperCAmelCase				:      Optional[Any]			  =				math.ceil(val / multiple ) * multiple

        return x

    _UpperCAmelCase				:      Tuple			  =				(output_size, output_size) if isinstance(__A		,		__A ) else output_size

    _UpperCAmelCase  , _UpperCAmelCase				:      List[str]			  =				get_image_size(__A )
    _UpperCAmelCase  , _UpperCAmelCase				:      List[str]			  =				output_size

    # determine new height and width
    _UpperCAmelCase				:      Dict			  =				output_height / input_height
    _UpperCAmelCase				:      int			  =				output_width / input_width

    if keep_aspect_ratio:
        # scale as little as possible
        if abs(1 - scale_width ) < abs(1 - scale_height ):
            # fit width
            _UpperCAmelCase				:      Optional[Any]			  =				scale_width
        else:
            # fit height
            _UpperCAmelCase				:      Tuple			  =				scale_height

    _UpperCAmelCase				:      Dict			  =				constraint_to_multiple_of(scale_height * input_height		,		multiple=__A )
    _UpperCAmelCase				:      Dict			  =				constraint_to_multiple_of(scale_width * input_width		,		multiple=__A )

    return (new_height, new_width)


class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Any =					["pixel_values"]


 def __init__(	self							,  _A = True							,  _A = None							,  _A = PILImageResampling.BILINEAR							,  _A = False							,  _A = 1							,  _A = True							,  _A = 1 / 255							,  _A = True							,  _A = None							,  _A = None							,  **_A							,  ) ->		None:

     """simple docstring"""



     super().__init__(**_A)
     _UpperCAmelCase				:      str			  =				size if size is not None else {'''height''': 384, '''width''': 384}
     _UpperCAmelCase				:      Optional[int]			  =				get_size_dict(_A)
     _UpperCAmelCase				:      int			  =				do_resize
     _UpperCAmelCase				:      Any			  =				size
     _UpperCAmelCase				:      List[Any]			  =				keep_aspect_ratio
     _UpperCAmelCase				:      List[Any]			  =				ensure_multiple_of
     _UpperCAmelCase				:      List[Any]			  =				resample
     _UpperCAmelCase				:      Optional[Any]			  =				do_rescale
     _UpperCAmelCase				:      Dict			  =				rescale_factor
     _UpperCAmelCase				:      str			  =				do_normalize
     _UpperCAmelCase				:      Dict			  =				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     _UpperCAmelCase				:      Optional[Any]			  =				image_std if image_std is not None else IMAGENET_STANDARD_STD


 def  snake_case__				(	self							,  _A							,  _A							,  _A = False							,  _A = 1							,  _A = PILImageResampling.BICUBIC							,  _A = None							,  **_A							,  ) ->		np.ndarray:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				get_size_dict(_A)
     if "height" not in size or "width" not in size:
         raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''')
     _UpperCAmelCase				:      Optional[Any]			  =				get_resize_output_image_size(
         _A							,  output_size=(size['''height'''], size['''width'''])							,  keep_aspect_ratio=_A							,  multiple=_A							,  )
     return resize(_A							,  size=_A							,  resample=_A							,  data_format=_A							,  **_A)


 def  snake_case__				(	self							,  _A							,  _A							,  _A = None							,  **_A							,  ) ->		List[str]:

     """simple docstring"""



     return rescale(_A							,  scale=_A							,  data_format=_A							,  **_A)


 def  snake_case__				(	self							,  _A							,  _A							,  _A							,  _A = None							,  **_A							,  ) ->		np.ndarray:

     """simple docstring"""



     return normalize(_A							,  mean=_A							,  std=_A							,  data_format=_A							,  **_A)


 def  snake_case__				(	self							,  _A							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = ChannelDimension.FIRST							,  **_A							,  ) ->		PIL.Image.Image:

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				do_resize if do_resize is not None else self.do_resize
     _UpperCAmelCase				:      Any			  =				size if size is not None else self.size
     _UpperCAmelCase				:      str			  =				get_size_dict(_A)
     _UpperCAmelCase				:      str			  =				keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
     _UpperCAmelCase				:      Tuple			  =				ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
     _UpperCAmelCase				:      int			  =				resample if resample is not None else self.resample
     _UpperCAmelCase				:      str			  =				do_rescale if do_rescale is not None else self.do_rescale
     _UpperCAmelCase				:      Union[str, Any]			  =				rescale_factor if rescale_factor is not None else self.rescale_factor
     _UpperCAmelCase				:      int			  =				do_normalize if do_normalize is not None else self.do_normalize
     _UpperCAmelCase				:      Any			  =				image_mean if image_mean is not None else self.image_mean
     _UpperCAmelCase				:      Any			  =				image_std if image_std is not None else self.image_std

     _UpperCAmelCase				:      int			  =				make_list_of_images(_A)

     if not valid_images(_A):
         raise ValueError(
             '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
             '''torch.Tensor, tf.Tensor or jax.ndarray.''')

     if do_resize and size is None or resample is None:
         raise ValueError('''Size and resample must be specified if do_resize is True.''')

     if do_rescale and rescale_factor is None:
         raise ValueError('''Rescale factor must be specified if do_rescale is True.''')

     if do_normalize and (image_mean is None or image_std is None):
         raise ValueError('''Image mean and std must be specified if do_normalize is True.''')

     # All transformations expect numpy arrays.
     _UpperCAmelCase				:      List[str]			  =				[to_numpy_array(_A) for image in images]

     if do_resize:
         _UpperCAmelCase				:      Dict			  =				[self.resize(image=_A							,  size=_A							,  resample=_A) for image in images]

     if do_rescale:
         _UpperCAmelCase				:      Tuple			  =				[self.rescale(image=_A							,  scale=_A) for image in images]

     if do_normalize:
         _UpperCAmelCase				:      int			  =				[self.normalize(image=_A							,  mean=_A							,  std=_A) for image in images]

     _UpperCAmelCase				:      Tuple			  =				[to_channel_dimension_format(_A							,  _A) for image in images]

     _UpperCAmelCase				:      Optional[Any]			  =				{'''pixel_values''': images}
     return BatchFeature(data=_A							,  tensor_type=_A)


 def  snake_case__				(	self							,  _A							,  _A = None) ->		str:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				outputs.logits

     # Resize logits and compute semantic segmentation maps
     if target_sizes is not None:
         if len(_A) != len(_A):
             raise ValueError(
                 '''Make sure that you pass in as many target sizes as the batch dimension of the logits''')

         if is_torch_tensor(_A):
             _UpperCAmelCase				:      int			  =				target_sizes.numpy()

         _UpperCAmelCase				:      List[str]			  =				[]

         for idx in range(len(_A)):
             _UpperCAmelCase				:      Any			  =				torch.nn.functional.interpolate(
                 logits[idx].unsqueeze(dim=0)							,  size=target_sizes[idx]							,  mode='''bilinear'''							,  align_corners=_A)
             _UpperCAmelCase				:      Any			  =				resized_logits[0].argmax(dim=0)
             semantic_segmentation.append(_A)
     else:
         _UpperCAmelCase				:      Tuple			  =				logits.argmax(dim=1)
         _UpperCAmelCase				:      Optional[Any]			  =				[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]

     return semantic_segmentation












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_    (						__lowercase ,   __lowercase ,   unittest.TestCase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Dict =					StableDiffusionXLImgaImgPipeline
 _SCREAMING_SNAKE_CASE							:			Any =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
 _SCREAMING_SNAKE_CASE							:			List[Any] =					PipelineTesterMixin.required_optional_params - {"latents"}
 _SCREAMING_SNAKE_CASE							:			Dict =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
 _SCREAMING_SNAKE_CASE							:			List[Any] =					IMAGE_TO_IMAGE_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE							:			Dict =					IMAGE_TO_IMAGE_IMAGE_PARAMS


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     torch.manual_seed(0)
     _UpperCAmelCase				:      Tuple			  =				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=_A							,  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							,  )
     _UpperCAmelCase				:      int			  =				EulerDiscreteScheduler(
         beta_start=0.00085							,  beta_end=0.012							,  steps_offset=1							,  beta_schedule='''scaled_linear'''							,  timestep_spacing='''leading'''							,  )
     torch.manual_seed(0)
     _UpperCAmelCase				:      Optional[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)
     _UpperCAmelCase				:      Tuple			  =				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							,  )
     _UpperCAmelCase				:      int			  =				CLIPTextModel(_A)
     _UpperCAmelCase				:      Tuple			  =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							,  local_files_only=_A)

     _UpperCAmelCase				:      int			  =				CLIPTextModelWithProjection(_A)
     _UpperCAmelCase				:      Optional[int]			  =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							,  local_files_only=_A)

     _UpperCAmelCase				:      Any			  =				{
         '''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							,  _A							,  _A=0) ->		List[Any]:

     """simple docstring"""



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

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     _UpperCAmelCase				:      Optional[Any]			  =				self.get_dummy_components()
     _UpperCAmelCase				:      Any			  =				StableDiffusionXLImgaImgPipeline(**_A)
     _UpperCAmelCase				:      List[str]			  =				sd_pipe.to(_A)
     sd_pipe.set_progress_bar_config(disable=_A)

     _UpperCAmelCase				:      Tuple			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Any			  =				sd_pipe(**_A).images
     _UpperCAmelCase				:      Any			  =				image[0, -3:, -3:, -1]

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

     _UpperCAmelCase				:      Optional[Any]			  =				np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165])

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


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

     """simple docstring"""



     super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)


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

     """simple docstring"""



     super().test_inference_batch_single_identical(expected_max_diff=3e-3)


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

     """simple docstring"""



     pass


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

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				self.get_dummy_components()
     _UpperCAmelCase				:      str			  =				StableDiffusionXLImgaImgPipeline(**_A)
     _UpperCAmelCase				:      Any			  =				sd_pipe.to(_A)
     _UpperCAmelCase				:      Tuple			  =				sd_pipe.to(_A)
     sd_pipe.set_progress_bar_config(disable=_A)

     # forward without prompt embeds
     _UpperCAmelCase				:      str			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Optional[Any]			  =				3 * ['''this is a negative prompt''']
     _UpperCAmelCase				:      Optional[int]			  =				negative_prompt
     _UpperCAmelCase				:      Optional[int]			  =				3 * [inputs['''prompt''']]

     _UpperCAmelCase				:      Optional[Any]			  =				sd_pipe(**_A)
     _UpperCAmelCase				:      Any			  =				output.images[0, -3:, -3:, -1]

     # forward with prompt embeds
     _UpperCAmelCase				:      Dict			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Optional[Any]			  =				3 * ['''this is a negative prompt''']
     _UpperCAmelCase				:      Dict			  =				3 * [inputs.pop('''prompt''')]

     (
         (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , 
     )				:      str			  =				sd_pipe.encode_prompt(_A							,  negative_prompt=_A)

     _UpperCAmelCase				:      str			  =				sd_pipe(
         **_A							,  prompt_embeds=_A							,  negative_prompt_embeds=_A							,  pooled_prompt_embeds=_A							,  negative_pooled_prompt_embeds=_A							,  )
     _UpperCAmelCase				:      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) ->		List[str]:

     """simple docstring"""



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


 def  snake_case__				(	self							,  _A							,  _A="cpu"							,  _A=torch.floataa							,  _A=0) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				torch.Generator(device=_A).manual_seed(_A)
     _UpperCAmelCase				:      Any			  =				np.random.RandomState(_A).standard_normal((1, 4, 64, 64))
     _UpperCAmelCase				:      Dict			  =				torch.from_numpy(_A).to(device=_A							,  dtype=_A)
     _UpperCAmelCase				:      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) ->		Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''')
     pipe.to(_A)
     pipe.set_progress_bar_config(disable=_A)

     _UpperCAmelCase				:      str			  =				self.get_inputs(_A)
     _UpperCAmelCase				:      Union[str, Any]			  =				pipe(**_A).images
     _UpperCAmelCase				:      Optional[int]			  =				image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 512, 3)
     _UpperCAmelCase				:      int			  =				np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506])
     assert np.abs(image_slice - expected_slice).max() < 7e-3




