






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  _lowercase   (   lowercase__						,				unittest.TestCase						):

      '''simple docstring'''





      _a							:						Tuple										=							LDMTextToImagePipeline
      _a							:						Tuple										=							TEXT_TO_IMAGE_PARAMS - {
          'negative_prompt',
          'negative_prompt_embeds',
          'cross_attention_kwargs',
          'prompt_embeds',
      }
      _a							:						Tuple										=							PipelineTesterMixin.required_optional_params - {
          'num_images_per_prompt',
          'callback',
          'callback_steps',
      }
      _a							:						Union[str, Any]										=							TEXT_TO_IMAGE_BATCH_PARAMS
      _a							:						Optional[int]										=							False
      def 						lowercase__					(     self   ):
       torch.manual_seed(0   )
       snake_case__  :    List[Any]							       =UNetaDConditionModel(
           block_out_channels=(3_2, 6_4)				,			layers_per_block=2				,			sample_size=3_2				,			in_channels=4				,			out_channels=4				,			down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,			up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")				,			cross_attention_dim=3_2				,			)
       snake_case__  :    Any							       =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   )
       snake_case__  :    Dict							       =AutoencoderKL(
           block_out_channels=(3_2, 6_4)				,			in_channels=3				,			out_channels=3				,			down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")				,			up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")				,			latent_channels=4				,			)
       torch.manual_seed(0   )
       snake_case__  :    List[Any]							       =CLIPTextConfig(
           bos_token_id=0				,			eos_token_id=2				,			hidden_size=3_2				,			intermediate_size=3_7				,			layer_norm_eps=1e-05				,			num_attention_heads=4				,			num_hidden_layers=5				,			pad_token_id=1				,			vocab_size=1_0_0_0				,			)
       snake_case__  :    Tuple							       =CLIPTextModel(UpperCAmelCase__   )
       snake_case__  :    Tuple							       =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

       snake_case__  :    str							       ={
           '''unet''': unet,
           '''scheduler''': scheduler,
           '''vqvae''': vae,
           '''bert''': text_encoder,
           '''tokenizer''': tokenizer,
       }
       return components
      def 						lowercase__					(     self				,			a				,			a=0   ):
       if str(UpperCAmelCase__   ).startswith("""mps"""   ):
        snake_case__  :    Optional[Any]							       =torch.manual_seed(UpperCAmelCase__   )
       else:
        snake_case__  :    Tuple							       =torch.Generator(device=UpperCAmelCase__   ).manual_seed(UpperCAmelCase__   )
       snake_case__  :    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 						lowercase__					(     self   ):
       snake_case__  :    str							       ='''cpu'''  # ensure determinism for the device-dependent torch.Generator

       snake_case__  :    Dict							       =self.get_dummy_components()
       snake_case__  :    Optional[Any]							       =LDMTextToImagePipeline(**UpperCAmelCase__   )
       pipe.to(UpperCAmelCase__   )
       pipe.set_progress_bar_config(disable=UpperCAmelCase__   )

       snake_case__  :    Optional[Any]							       =self.get_dummy_inputs(UpperCAmelCase__   )
       snake_case__  :    str							       =pipe(**UpperCAmelCase__   ).images
       snake_case__  :    Union[str, Any]							       =image[0, -3:, -3:, -1]

       assert image.shape == (1, 1_6, 1_6, 3)
       snake_case__  :    Tuple							       =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  _lowercase   (   unittest.TestCase						):

      '''simple docstring'''





      def 						lowercase__					(     self   ):
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()
      def 						lowercase__					(     self				,			a				,			a=torch.floataa				,			a=0   ):
       snake_case__  :    str							       =torch.manual_seed(UpperCAmelCase__   )
       snake_case__  :    Union[str, Any]							       =np.random.RandomState(UpperCAmelCase__   ).standard_normal((1, 4, 3_2, 3_2)   )
       snake_case__  :    str							       =torch.from_numpy(UpperCAmelCase__   ).to(device=UpperCAmelCase__				,			dtype=UpperCAmelCase__   )
       snake_case__  :    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 						lowercase__					(     self   ):
       snake_case__  :    Optional[int]							       =LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""   ).to(UpperCAmelCase__   )
       pipe.set_progress_bar_config(disable=UpperCAmelCase__   )

       snake_case__  :    int							       =self.get_inputs(UpperCAmelCase__   )
       snake_case__  :    Tuple							       =pipe(**UpperCAmelCase__   ).images
       snake_case__  :    Tuple							       =image[0, -3:, -3:, -1].flatten()

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







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

      '''simple docstring'''





      def 						lowercase__					(     self   ):
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()
      def 						lowercase__					(     self				,			a				,			a=torch.floataa				,			a=0   ):
       snake_case__  :    Optional[Any]							       =torch.manual_seed(UpperCAmelCase__   )
       snake_case__  :    str							       =np.random.RandomState(UpperCAmelCase__   ).standard_normal((1, 4, 3_2, 3_2)   )
       snake_case__  :    Union[str, Any]							       =torch.from_numpy(UpperCAmelCase__   ).to(device=UpperCAmelCase__				,			dtype=UpperCAmelCase__   )
       snake_case__  :    Union[str, Any]							       ={
           '''prompt''': '''A painting of a squirrel eating a burger''',
           '''latents''': latents,
           '''generator''': generator,
           '''num_inference_steps''': 5_0,
           '''guidance_scale''': 6.0,
           '''output_type''': '''numpy''',
       }
       return inputs



      def 						lowercase__					(     self   ):
       snake_case__  :    Tuple							       =LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""   ).to(UpperCAmelCase__   )
       pipe.set_progress_bar_config(disable=UpperCAmelCase__   )

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

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













from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__lowerCamelCase	:		Tuple										=   logging.get_logger(__name__)







class  _lowercase   (   _A						):
      _a							:						Optional[int]										=							['pixel_values']
      def __init__(     self				,			a = True				,			a = 3_2				,			a=PILImageResampling.BILINEAR				,			a = True				,			**a				,			):
       snake_case__  :    Any							       =do_resize
       snake_case__  :    Optional[int]							       =do_rescale
       snake_case__  :    Optional[Any]							       =size_divisor
       snake_case__  :    Optional[int]							       =resample
       super().__init__(**a   )
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a = None				,			**a   ):
       snake_case__       ,   snake_case__  :    List[str]							       =get_image_size(a   )
       # Rounds the height and width down to the closest multiple of size_divisor
       snake_case__  :    str							       =height // size_divisor * size_divisor
       snake_case__  :    List[str]							       =width // size_divisor * size_divisor
       snake_case__  :    int							       =resize(a				,			(new_h, new_w)				,			resample=a				,			data_format=a				,			**a   )
       return image
      def 						lowercase__					(     self				,			a				,			a				,			a = None				,			**a   ):
       return rescale(image=a				,			scale=a				,			data_format=a				,			**a   )



      def 						lowercase__					(     self				,			a				,			a = None				,			a = None				,			a=None				,			a = None				,			a = None				,			a = ChannelDimension.FIRST				,			**a				,			):
       snake_case__  :    Optional[Any]							       =do_resize if do_resize is not None else self.do_resize
       snake_case__  :    str							       =do_rescale if do_rescale is not None else self.do_rescale
       snake_case__  :    List[Any]							       =size_divisor if size_divisor is not None else self.size_divisor
       snake_case__  :    Optional[int]							       =resample if resample is not None else self.resample

       if do_resize and size_divisor is None:
        raise ValueError("""size_divisor is required for resizing"""   )

       snake_case__  :    Optional[int]							       =make_list_of_images(a   )

       if not valid_images(a   ):
        raise ValueError("""Invalid image(s)"""   )

       # All transformations expect numpy arrays.
       snake_case__  :    str							       =[to_numpy_array(a   ) for img in images]

       if do_resize:
        snake_case__  :    str							       =[self.resize(a				,			size_divisor=a				,			resample=a   ) for image in images]

       if do_rescale:
        snake_case__  :    Union[str, Any]							       =[self.rescale(a				,			scale=1 / 2_5_5   ) for image in images]

       snake_case__  :    int							       =[to_channel_dimension_format(a				,			a   ) for image in images]

       snake_case__  :    Tuple							       ={"""pixel_values""": images}
       return BatchFeature(data=a				,			tensor_type=a   )





