




"""simple docstring"""





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

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
					import PIL

if is_torch_available():
					import torch


A   =				logging.get_logger(__name__)



class      a__				(	__magic_name__   ):
			lowercase_    =	["pixel_values"]


			def __init__(      self      :    Any      ,  UpperCamelCase_      :    bool = True      ,  UpperCamelCase_      :    Dict[str, int] = None      ,  UpperCamelCase_      :    PILImageResampling = PILImageResampling.BILINEAR      ,  UpperCamelCase_      :    bool = True      ,  UpperCamelCase_      :    Union[int, float] = 1 / 255      ,  UpperCamelCase_      :    bool = True      ,  UpperCamelCase_      :    Dict[str, int] = None      ,  UpperCamelCase_      :    bool = True      ,  **UpperCamelCase_      :    int      ,  ):


						"""simple docstring"""




						super().__init__(**UpperCamelCase_)
						__UpperCAmelCase	: List[str]		=					size if size is not None else {"shortest_edge": 224}
						__UpperCAmelCase	: Optional[int]		=					get_size_dict(UpperCamelCase_      ,  default_to_square=UpperCamelCase_)
						__UpperCAmelCase	: Union[str, Any]		=					crop_size if crop_size is not None else {"height": 256, "width": 256}
						__UpperCAmelCase	: str		=					get_size_dict(UpperCamelCase_      ,  param_name="crop_size")

						__UpperCAmelCase	: Optional[Any]		=					do_resize
						__UpperCAmelCase	: int		=					size
						__UpperCAmelCase	: Dict		=					resample
						__UpperCAmelCase	: str		=					do_rescale
						__UpperCAmelCase	: str		=					rescale_factor
						__UpperCAmelCase	: Dict		=					do_center_crop
						__UpperCAmelCase	: List[str]		=					crop_size
						__UpperCAmelCase	: Tuple		=					do_flip_channel_order


			def       a_     (      self      :    Optional[int]      ,  UpperCamelCase_      :    np.ndarray      ,  UpperCamelCase_      :    Dict[str, int]      ,  UpperCamelCase_      :    PILImageResampling = PIL.Image.BILINEAR      ,  UpperCamelCase_      :    Optional[Union[str, ChannelDimension]] = None      ,  **UpperCamelCase_      :    int      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: Union[str, Any]		=					get_size_dict(UpperCamelCase_      ,  default_to_square=UpperCamelCase_)
						if "shortest_edge" not in size:
									raise ValueError(F"The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}")
						__UpperCAmelCase	: int		=					get_resize_output_image_size(UpperCamelCase_      ,  size=size["shortest_edge"]      ,  default_to_square=UpperCamelCase_)
						return resize(UpperCamelCase_      ,  size=UpperCamelCase_      ,  resample=UpperCamelCase_      ,  data_format=UpperCamelCase_      ,  **UpperCamelCase_)


			def       a_     (      self      :    Union[str, Any]      ,  UpperCamelCase_      :    np.ndarray      ,  UpperCamelCase_      :    Dict[str, int]      ,  UpperCamelCase_      :    Optional[Union[str, ChannelDimension]] = None      ,  **UpperCamelCase_      :    List[Any]      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: Any		=					get_size_dict(UpperCamelCase_)
						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()}")
						return center_crop(UpperCamelCase_      ,  size=(size["height"], size["width"])      ,  data_format=UpperCamelCase_      ,  **UpperCamelCase_)


			def       a_     (      self      :    str      ,  UpperCamelCase_      :    np.ndarray      ,  UpperCamelCase_      :    Union[int, float]      ,  UpperCamelCase_      :    Optional[Union[str, ChannelDimension]] = None      ,  **UpperCamelCase_      :    Any      ,  ):


						"""simple docstring"""




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


			def       a_     (      self      :    Optional[int]      ,  UpperCamelCase_      :    np.ndarray      ,  UpperCamelCase_      :    Optional[Union[str, ChannelDimension]] = None):


						"""simple docstring"""




						return flip_channel_order(UpperCamelCase_      ,  data_format=UpperCamelCase_)


			def       a_     (      self      :    Any      ,  UpperCamelCase_      :    ImageInput      ,  UpperCamelCase_      :    bool = None      ,  UpperCamelCase_      :    Dict[str, int] = None      ,  UpperCamelCase_      :    PILImageResampling = None      ,  UpperCamelCase_      :    bool = None      ,  UpperCamelCase_      :    float = None      ,  UpperCamelCase_      :    bool = None      ,  UpperCamelCase_      :    Dict[str, int] = None      ,  UpperCamelCase_      :    bool = None      ,  UpperCamelCase_      :    Optional[Union[str, TensorType]] = None      ,  UpperCamelCase_      :    ChannelDimension = ChannelDimension.FIRST      ,  **UpperCamelCase_      :    Tuple      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[int]		=					do_resize if do_resize is not None else self.do_resize
						__UpperCAmelCase	: Optional[Any]		=					resample if resample is not None else self.resample
						__UpperCAmelCase	: Tuple		=					do_rescale if do_rescale is not None else self.do_rescale
						__UpperCAmelCase	: int		=					rescale_factor if rescale_factor is not None else self.rescale_factor
						__UpperCAmelCase	: List[str]		=					do_center_crop if do_center_crop is not None else self.do_center_crop
						__UpperCAmelCase	: List[str]		=					(
						    do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
						)

						__UpperCAmelCase	: Tuple		=					size if size is not None else self.size
						__UpperCAmelCase	: List[str]		=					get_size_dict(UpperCamelCase_      ,  default_to_square=UpperCamelCase_)
						__UpperCAmelCase	: Union[str, Any]		=					crop_size if crop_size is not None else self.crop_size
						__UpperCAmelCase	: Optional[int]		=					get_size_dict(UpperCamelCase_      ,  param_name="crop_size")

						__UpperCAmelCase	: Tuple		=					make_list_of_images(UpperCamelCase_)

						if not valid_images(UpperCamelCase_):
									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:
									raise ValueError("Size 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_center_crop and crop_size is None:
									raise ValueError("Crop size must be specified if do_center_crop is True.")

						# All transformations expect numpy arrays.
						__UpperCAmelCase	: Tuple		=					[to_numpy_array(UpperCamelCase_) for image in images]

						if do_resize:
									__UpperCAmelCase	: Any		=					[self.resize(image=UpperCamelCase_      ,  size=UpperCamelCase_      ,  resample=UpperCamelCase_) for image in images]

						if do_center_crop:
									__UpperCAmelCase	: List[Any]		=					[self.center_crop(image=UpperCamelCase_      ,  size=UpperCamelCase_) for image in images]

						if do_rescale:
									__UpperCAmelCase	: List[str]		=					[self.rescale(image=UpperCamelCase_      ,  scale=UpperCamelCase_) for image in images]

						# the pretrained checkpoints assume images are BGR, not RGB
						if do_flip_channel_order:
									__UpperCAmelCase	: Any		=					[self.flip_channel_order(image=UpperCamelCase_) for image in images]

						__UpperCAmelCase	: Tuple		=					[to_channel_dimension_format(UpperCamelCase_      ,  UpperCamelCase_) for image in images]

						__UpperCAmelCase	: List[str]		=					{"pixel_values": images}
						return BatchFeature(data=UpperCamelCase_      ,  tensor_type=UpperCamelCase_)


			def       a_     (      self      :    str      ,  UpperCamelCase_      :    Union[str, Any]      ,  UpperCamelCase_      :    List[Tuple] = None):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					outputs.logits

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

									if is_torch_tensor(UpperCamelCase_):
												__UpperCAmelCase	: str		=					target_sizes.numpy()

									__UpperCAmelCase	: Tuple		=					[]

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

						return semantic_segmentation








"""simple docstring"""





import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class      a__				(	__magic_name__							,    unittest.TestCase   ):
			lowercase_    =	LDMTextToImagePipeline
			lowercase_    =	TEXT_TO_IMAGE_PARAMS - {
			    "negative_prompt",
			    "negative_prompt_embeds",
			    "cross_attention_kwargs",
			    "prompt_embeds",
			}
			lowercase_    =	PipelineTesterMixin.required_optional_params - {
			    "num_images_per_prompt",
			    "callback",
			    "callback_steps",
			}
			lowercase_    =	TEXT_TO_IMAGE_BATCH_PARAMS
			lowercase_    =	False


			def       a_     (      self      :    Union[str, Any]):


						"""simple docstring"""




						torch.manual_seed(0)
						__UpperCAmelCase	: str		=					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	: Dict		=					DDIMScheduler(
						    beta_start=0.00085      ,  beta_end=0.012      ,  beta_schedule="scaled_linear"      ,  clip_sample=UpperCamelCase_      ,  set_alpha_to_one=UpperCamelCase_      ,  )
						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      ,  )
						torch.manual_seed(0)
						__UpperCAmelCase	: List[str]		=					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      ,  )
						__UpperCAmelCase	: List[str]		=					CLIPTextModel(UpperCamelCase_)
						__UpperCAmelCase	: Union[str, Any]		=					CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

						__UpperCAmelCase	: Optional[int]		=					{
						    "unet": unet,
						    "scheduler": scheduler,
						    "vqvae": vae,
						    "bert": text_encoder,
						    "tokenizer": tokenizer,
						}
						return components


			def       a_     (      self      :    Tuple      ,  UpperCamelCase_      :    Optional[Any]      ,  UpperCamelCase_      :    Tuple=0):


						"""simple docstring"""




						if str(UpperCamelCase_).startswith("mps"):
									__UpperCAmelCase	: str		=					torch.manual_seed(UpperCamelCase_)
						else:
									__UpperCAmelCase	: Tuple		=					torch.Generator(device=UpperCamelCase_).manual_seed(UpperCamelCase_)
						__UpperCAmelCase	: Tuple		=					{
						    "prompt": "A painting of a squirrel eating a burger",
						    "generator": generator,
						    "num_inference_steps": 2,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs


			def       a_     (      self      :    Tuple):


						"""simple docstring"""




						__UpperCAmelCase	: Any		=					"cpu"  # ensure determinism for the device-dependent torch.Generator

						__UpperCAmelCase	: Union[str, Any]		=					self.get_dummy_components()
						__UpperCAmelCase	: Union[str, Any]		=					LDMTextToImagePipeline(**UpperCamelCase_)
						pipe.to(UpperCamelCase_)
						pipe.set_progress_bar_config(disable=UpperCamelCase_)

						__UpperCAmelCase	: int		=					self.get_dummy_inputs(UpperCamelCase_)
						__UpperCAmelCase	: Dict		=					pipe(**UpperCamelCase_).images
						__UpperCAmelCase	: List[Any]		=					image[0, -3:, -3:, -1]

						assert image.shape == (1, 16, 16, 3)
						__UpperCAmelCase	: List[str]		=					np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014])

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






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


			def       a_     (      self      :    Optional[int]):


						"""simple docstring"""




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


			def       a_     (      self      :    List[str]      ,  UpperCamelCase_      :    str      ,  UpperCamelCase_      :    int=torch.floataa      ,  UpperCamelCase_      :    Dict=0):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					torch.manual_seed(UpperCamelCase_)
						__UpperCAmelCase	: Optional[Any]		=					np.random.RandomState(UpperCamelCase_).standard_normal((1, 4, 32, 32))
						__UpperCAmelCase	: str		=					torch.from_numpy(UpperCamelCase_).to(device=UpperCamelCase_      ,  dtype=UpperCamelCase_)
						__UpperCAmelCase	: Tuple		=					{
						    "prompt": "A painting of a squirrel eating a burger",
						    "latents": latents,
						    "generator": generator,
						    "num_inference_steps": 3,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs


			def       a_     (      self      :    Optional[int]):


						"""simple docstring"""




						__UpperCAmelCase	: str		=					LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256").to(UpperCamelCase_)
						pipe.set_progress_bar_config(disable=UpperCamelCase_)

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

						assert image.shape == (1, 256, 256, 3)
						__UpperCAmelCase	: List[Any]		=					np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878])
						__UpperCAmelCase	: List[Any]		=					np.abs(expected_slice - image_slice).max()
						assert max_diff < 1e-3






@nightly
@require_torch_gpu
class      a__				(	unittest.TestCase   ):


			def       a_     (      self      :    Optional[Any]):


						"""simple docstring"""




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


			def       a_     (      self      :    Tuple      ,  UpperCamelCase_      :    Tuple      ,  UpperCamelCase_      :    int=torch.floataa      ,  UpperCamelCase_      :    Optional[int]=0):


						"""simple docstring"""




						__UpperCAmelCase	: str		=					torch.manual_seed(UpperCamelCase_)
						__UpperCAmelCase	: Tuple		=					np.random.RandomState(UpperCamelCase_).standard_normal((1, 4, 32, 32))
						__UpperCAmelCase	: Optional[Any]		=					torch.from_numpy(UpperCamelCase_).to(device=UpperCamelCase_      ,  dtype=UpperCamelCase_)
						__UpperCAmelCase	: Dict		=					{
						    "prompt": "A painting of a squirrel eating a burger",
						    "latents": latents,
						    "generator": generator,
						    "num_inference_steps": 50,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs


			def       a_     (      self      :    Dict):


						"""simple docstring"""




						__UpperCAmelCase	: str		=					LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256").to(UpperCamelCase_)
						pipe.set_progress_bar_config(disable=UpperCamelCase_)

						__UpperCAmelCase	: Union[str, Any]		=					self.get_inputs(UpperCamelCase_)
						__UpperCAmelCase	: List[str]		=					pipe(**UpperCamelCase_).images[0]

						__UpperCAmelCase	: int		=					load_numpy(
						    "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy")
						__UpperCAmelCase	: int		=					np.abs(expected_image - image).max()
						assert max_diff < 1e-3


