






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


UpperCamelCase    							=      logging.get_logger(__name__)


if is_vision_available():
       import PIL







class 		_A						( UpperCAmelCase_ ):
  lowercase_						:			Tuple						=					['''pixel_values''']

  def __init__(    self						:	List[str]   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Dict[str, int] = None   ,				lowerCamelCase__						:	PILImageResampling = PILImageResampling.BICUBIC   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Dict[str, int] = None   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Union[int, float] = 1 / 2_55   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Optional[Union[float, List[float]]] = None   ,				lowerCamelCase__						:	Optional[Union[float, List[float]]] = None   ,				lowerCamelCase__						:	bool = True   ,				**lowerCamelCase__						:	List[str]   ,				):
     """simple docstring"""

     super().__init__(**lowerCamelCase__			)
     __UpperCamelCase	:			int					=					size if size is not None else {"""shortest_edge""": 2_24}
     __UpperCamelCase	:			Tuple					=					get_size_dict(lowerCamelCase__   ,				default_to_square=lowerCamelCase__			)
     __UpperCamelCase	:			Any					=					crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24}
     __UpperCamelCase	:			Tuple					=					get_size_dict(lowerCamelCase__   ,				default_to_square=lowerCamelCase__   ,				param_name="""crop_size"""			)

     __UpperCamelCase	:			str					=					do_resize
     __UpperCamelCase	:			Dict					=					size
     __UpperCamelCase	:			Dict					=					resample
     __UpperCamelCase	:			Union[str, Any]					=					do_center_crop
     __UpperCamelCase	:			str					=					crop_size
     __UpperCamelCase	:			Optional[Any]					=					do_rescale
     __UpperCamelCase	:			Any					=					rescale_factor
     __UpperCamelCase	:			Optional[Any]					=					do_normalize
     __UpperCamelCase	:			str					=					image_mean if image_mean is not None else OPENAI_CLIP_MEAN
     __UpperCamelCase	:			int					=					image_std if image_std is not None else OPENAI_CLIP_STD
     __UpperCamelCase	:			Dict					=					do_convert_rgb

  def    a					(    self						:	Union[str, Any]   ,				lowerCamelCase__						:	np.ndarray   ,				lowerCamelCase__						:	Dict[str, int]   ,				lowerCamelCase__						:	PILImageResampling = PILImageResampling.BICUBIC   ,				lowerCamelCase__						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowerCamelCase__						:	Any   ,				):
     """simple docstring"""

     __UpperCamelCase	:			Optional[int]					=					get_size_dict(lowerCamelCase__   ,				default_to_square=lowerCamelCase__			)
     if "shortest_edge" not in size:
        raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'			)
     __UpperCamelCase	:			Any					=					get_resize_output_image_size(lowerCamelCase__   ,				size=size["""shortest_edge"""]   ,				default_to_square=lowerCamelCase__			)
     return resize(lowerCamelCase__   ,				size=lowerCamelCase__   ,				resample=lowerCamelCase__   ,				data_format=lowerCamelCase__   ,				**lowerCamelCase__			)

  def    a					(    self						:	List[Any]   ,				lowerCamelCase__						:	np.ndarray   ,				lowerCamelCase__						:	Dict[str, int]   ,				lowerCamelCase__						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowerCamelCase__						:	Union[str, Any]   ,				):
     """simple docstring"""

     __UpperCamelCase	:			Any					=					get_size_dict(lowerCamelCase__			)
     if "height" not in size or "width" not in size:
        raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}'			)
     return center_crop(lowerCamelCase__   ,				size=(size["""height"""], size["""width"""])   ,				data_format=lowerCamelCase__   ,				**lowerCamelCase__			)

  def    a					(    self						:	int   ,				lowerCamelCase__						:	np.ndarray   ,				lowerCamelCase__						:	Union[int, float]   ,				lowerCamelCase__						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowerCamelCase__						:	List[str]   ,				):
     """simple docstring"""

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

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	np.ndarray   ,				lowerCamelCase__						:	Union[float, List[float]]   ,				lowerCamelCase__						:	Union[float, List[float]]   ,				lowerCamelCase__						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowerCamelCase__						:	Optional[Any]   ,				):
     """simple docstring"""

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

  def    a					(    self						:	str   ,				lowerCamelCase__						:	ImageInput   ,				lowerCamelCase__						:	bool = None   ,				lowerCamelCase__						:	Dict[str, int] = None   ,				lowerCamelCase__						:	PILImageResampling = None   ,				lowerCamelCase__						:	bool = None   ,				lowerCamelCase__						:	int = None   ,				lowerCamelCase__						:	bool = None   ,				lowerCamelCase__						:	float = None   ,				lowerCamelCase__						:	bool = None   ,				lowerCamelCase__						:	Optional[Union[float, List[float]]] = None   ,				lowerCamelCase__						:	Optional[Union[float, List[float]]] = None   ,				lowerCamelCase__						:	bool = None   ,				lowerCamelCase__						:	Optional[Union[str, TensorType]] = None   ,				lowerCamelCase__						:	Optional[ChannelDimension] = ChannelDimension.FIRST   ,				**lowerCamelCase__						:	Optional[Any]   ,				):
     """simple docstring"""

     __UpperCamelCase	:			Any					=					do_resize if do_resize is not None else self.do_resize
     __UpperCamelCase	:			List[str]					=					size if size is not None else self.size
     __UpperCamelCase	:			Optional[int]					=					get_size_dict(lowerCamelCase__   ,				param_name="""size"""   ,				default_to_square=lowerCamelCase__			)
     __UpperCamelCase	:			str					=					resample if resample is not None else self.resample
     __UpperCamelCase	:			Union[str, Any]					=					do_center_crop if do_center_crop is not None else self.do_center_crop
     __UpperCamelCase	:			List[Any]					=					crop_size if crop_size is not None else self.crop_size
     __UpperCamelCase	:			str					=					get_size_dict(lowerCamelCase__   ,				param_name="""crop_size"""   ,				default_to_square=lowerCamelCase__			)
     __UpperCamelCase	:			List[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	:			Dict					=					do_normalize if do_normalize is not None else self.do_normalize
     __UpperCamelCase	:			Optional[Any]					=					image_mean if image_mean is not None else self.image_mean
     __UpperCamelCase	:			Optional[Any]					=					image_std if image_std is not None else self.image_std
     __UpperCamelCase	:			Optional[int]					=					do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

     __UpperCamelCase	:			List[Any]					=					make_list_of_images(lowerCamelCase__			)

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

     # PIL RGBA images are converted to RGB
     if do_convert_rgb:
        __UpperCamelCase	:			Dict					=					[convert_to_rgb(lowerCamelCase__			) for image in images]

     # All transformations expect numpy arrays.
     __UpperCamelCase	:			Dict					=					[to_numpy_array(lowerCamelCase__			) for image in images]

     if do_resize:
        __UpperCamelCase	:			Optional[int]					=					[self.resize(image=lowerCamelCase__   ,				size=lowerCamelCase__   ,				resample=lowerCamelCase__			) for image in images]

     if do_center_crop:
        __UpperCamelCase	:			Optional[int]					=					[self.center_crop(image=lowerCamelCase__   ,				size=lowerCamelCase__			) for image in images]

     if do_rescale:
        __UpperCamelCase	:			List[Any]					=					[self.rescale(image=lowerCamelCase__   ,				scale=lowerCamelCase__			) for image in images]

     if do_normalize:
        __UpperCamelCase	:			Optional[Any]					=					[self.normalize(image=lowerCamelCase__   ,				mean=lowerCamelCase__   ,				std=lowerCamelCase__			) for image in images]

     __UpperCamelCase	:			List[str]					=					[to_channel_dimension_format(lowerCamelCase__   ,				lowerCamelCase__			) for image in images]

     __UpperCamelCase	:			Optional[int]					=					{"""pixel_values""": images}
     return BatchFeature(data=lowerCamelCase__   ,				tensor_type=lowerCamelCase__			)











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						( UpperCAmelCase_	,				unittest.TestCase ):
  lowercase_						:			Union[str, Any]						=					LDMTextToImagePipeline
  lowercase_						:			Tuple						=					TEXT_TO_IMAGE_PARAMS - {
      '''negative_prompt''',
      '''negative_prompt_embeds''',
      '''cross_attention_kwargs''',
      '''prompt_embeds''',
  }
  lowercase_						:			Optional[Any]						=					PipelineTesterMixin.required_optional_params - {
      '''num_images_per_prompt''',
      '''callback''',
      '''callback_steps''',
  }
  lowercase_						:			Dict						=					TEXT_TO_IMAGE_BATCH_PARAMS
  lowercase_						:			Tuple						=					False

  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

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

     __UpperCamelCase	:			Any					=					{
         """unet""": unet,
         """scheduler""": scheduler,
         """vqvae""": vae,
         """bert""": text_encoder,
         """tokenizer""": tokenizer,
     }
     return components

  def    a					(    self						:	Tuple   ,				lowerCamelCase__						:	str   ,				lowerCamelCase__						:	List[str]=0			):
     """simple docstring"""

     if str(lowerCamelCase__			).startswith("""mps"""			):
        __UpperCamelCase	:			str					=					torch.manual_seed(lowerCamelCase__			)
     else:
        __UpperCamelCase	:			Optional[Any]					=					torch.Generator(device=lowerCamelCase__			).manual_seed(lowerCamelCase__			)
     __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	:			Dict					=					"""cpu"""  # ensure determinism for the device-dependent torch.Generator

     __UpperCamelCase	:			List[str]					=					self.get_dummy_components()
     __UpperCamelCase	:			Optional[int]					=					LDMTextToImagePipeline(**lowerCamelCase__			)
     pipe.to(lowerCamelCase__			)
     pipe.set_progress_bar_config(disable=lowerCamelCase__			)

     __UpperCamelCase	:			List[Any]					=					self.get_dummy_inputs(lowerCamelCase__			)
     __UpperCamelCase	:			List[Any]					=					pipe(**lowerCamelCase__			).images
     __UpperCamelCase	:			Tuple					=					image[0, -3:, -3:, -1]

     assert image.shape == (1, 16, 16, 3)
     __UpperCamelCase	:			int					=					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						:	Any			):
     """simple docstring"""

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

  def    a					(    self						:	Dict   ,				lowerCamelCase__						:	List[Any]   ,				lowerCamelCase__						:	Tuple=torch.floataa   ,				lowerCamelCase__						:	List[Any]=0			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					torch.manual_seed(lowerCamelCase__			)
     __UpperCamelCase	:			Tuple					=					np.random.RandomState(lowerCamelCase__			).standard_normal((1, 4, 32, 32)			)
     __UpperCamelCase	:			Any					=					torch.from_numpy(lowerCamelCase__			).to(device=lowerCamelCase__   ,				dtype=lowerCamelCase__			)
     __UpperCamelCase	:			Optional[int]					=					{
         """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	:			Any					=					LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""			).to(lowerCamelCase__			)
     pipe.set_progress_bar_config(disable=lowerCamelCase__			)

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

     assert image.shape == (1, 2_56, 2_56, 3)
     __UpperCamelCase	:			Optional[Any]					=					np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878]			)
     __UpperCamelCase	:			Union[str, 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   ,				lowerCamelCase__						:	str   ,				lowerCamelCase__						:	Union[str, Any]=torch.floataa   ,				lowerCamelCase__						:	Tuple=0			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					torch.manual_seed(lowerCamelCase__			)
     __UpperCamelCase	:			Optional[Any]					=					np.random.RandomState(lowerCamelCase__			).standard_normal((1, 4, 32, 32)			)
     __UpperCamelCase	:			List[Any]					=					torch.from_numpy(lowerCamelCase__			).to(device=lowerCamelCase__   ,				dtype=lowerCamelCase__			)
     __UpperCamelCase	:			Union[str, Any]					=					{
         """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						:	Tuple			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""			).to(lowerCamelCase__			)
     pipe.set_progress_bar_config(disable=lowerCamelCase__			)

     __UpperCamelCase	:			Dict					=					self.get_inputs(lowerCamelCase__			)
     __UpperCamelCase	:			List[Any]					=					pipe(**lowerCamelCase__			).images[0]

     __UpperCamelCase	:			Optional[Any]					=					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



