






"""simple docstring"""







import gc
import unittest

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

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

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


enable_full_determinism()







class  lowerCamelCase__ (	__SCREAMING_SNAKE_CASE   ,					__SCREAMING_SNAKE_CASE   ,					unittest.TestCase			):
    SCREAMING_SNAKE_CASE		=      StableDiffusionSAGPipeline
    SCREAMING_SNAKE_CASE		=      TEXT_TO_IMAGE_PARAMS
    SCREAMING_SNAKE_CASE		=      TEXT_TO_IMAGE_BATCH_PARAMS
    SCREAMING_SNAKE_CASE		=      TEXT_TO_IMAGE_IMAGE_PARAMS
    SCREAMING_SNAKE_CASE		=      TEXT_TO_IMAGE_IMAGE_PARAMS
    SCREAMING_SNAKE_CASE		=      False






    def     _UpperCamelCase							(			self ):
          torch.manual_seed(0 )
          UpperCAmelCase          =	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          =	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          =	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          =	CLIPTextConfig(
              bos_token_id=0     ,eos_token_id=2     ,hidden_size=32     ,intermediate_size=37     ,layer_norm_eps=1e-0_5     ,num_attention_heads=4     ,num_hidden_layers=5     ,pad_token_id=1     ,vocab_size=1_000     ,)
          UpperCAmelCase          =	CLIPTextModel(__UpperCAmelCase )
          UpperCAmelCase          =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )

          UpperCAmelCase          =	{
              """unet""": unet,
              """scheduler""": scheduler,
              """vae""": vae,
              """text_encoder""": text_encoder,
              """tokenizer""": tokenizer,
              """safety_checker""": None,
              """feature_extractor""": None,
          }
          return components






    def     _UpperCamelCase							(			self     ,A     ,A=0 ):
          if str(__UpperCAmelCase ).startswith("""mps""" ):
                UpperCAmelCase          =	torch.manual_seed(__UpperCAmelCase )
          else:
                UpperCAmelCase          =	torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase )
          UpperCAmelCase          =	{
              """prompt""": """.""",
              """generator""": generator,
              """num_inference_steps""": 2,
              """guidance_scale""": 1.0,
              """sag_scale""": 1.0,
              """output_type""": """numpy""",
          }
          return inputs






    def     _UpperCamelCase							(			self ):
          super().test_inference_batch_single_identical(expected_max_diff=3e-3 )







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






    def     _UpperCamelCase							(			self ):
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






    def     _UpperCamelCase							(			self ):
          UpperCAmelCase          =	StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" )
          UpperCAmelCase          =	sag_pipe.to(__UpperCAmelCase )
          sag_pipe.set_progress_bar_config(disable=__UpperCAmelCase )

          UpperCAmelCase          =	"""."""
          UpperCAmelCase          =	torch.manual_seed(0 )
          UpperCAmelCase          =	sag_pipe(
              [prompt]     ,generator=__UpperCAmelCase     ,guidance_scale=7.5     ,sag_scale=1.0     ,num_inference_steps=20     ,output_type="""np""" )

          UpperCAmelCase          =	output.images

          UpperCAmelCase          =	image[0, -3:, -3:, -1]

          assert image.shape == (1, 512, 512, 3)
          UpperCAmelCase          =	np.array([0.1568, 0.1738, 0.1695, 0.1693, 0.1507, 0.1705, 0.1547, 0.1751, 0.1949] )

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






    def     _UpperCamelCase							(			self ):
          UpperCAmelCase          =	StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" )
          UpperCAmelCase          =	sag_pipe.to(__UpperCAmelCase )
          sag_pipe.set_progress_bar_config(disable=__UpperCAmelCase )

          UpperCAmelCase          =	"""."""
          UpperCAmelCase          =	torch.manual_seed(0 )
          UpperCAmelCase          =	sag_pipe(
              [prompt]     ,generator=__UpperCAmelCase     ,guidance_scale=7.5     ,sag_scale=1.0     ,num_inference_steps=20     ,output_type="""np""" )

          UpperCAmelCase          =	output.images

          UpperCAmelCase          =	image[0, -3:, -3:, -1]

          assert image.shape == (1, 512, 512, 3)
          UpperCAmelCase          =	np.array([0.3459, 0.2876, 0.2537, 0.3002, 0.2671, 0.2160, 0.3026, 0.2262, 0.2371] )

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






    def     _UpperCamelCase							(			self ):
          UpperCAmelCase          =	StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" )
          UpperCAmelCase          =	sag_pipe.to(__UpperCAmelCase )
          sag_pipe.set_progress_bar_config(disable=__UpperCAmelCase )

          UpperCAmelCase          =	"""."""
          UpperCAmelCase          =	torch.manual_seed(0 )
          UpperCAmelCase          =	sag_pipe(
              [prompt]     ,width=768     ,height=512     ,generator=__UpperCAmelCase     ,guidance_scale=7.5     ,sag_scale=1.0     ,num_inference_steps=20     ,output_type="""np"""     ,)

          UpperCAmelCase          =	output.images

          assert image.shape == (1, 512, 768, 3)











"""simple docstring"""







from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
  import PIL

_UpperCamelCase					      =  logging.get_logger(__name__)

def _a			(		_snake_case							):







      """simple docstring"""






      if isinstance(_snake_case				,	(list, tuple)							) and isinstance(videos[0]				,	(list, tuple)							) and is_valid_image(videos[0][0]							):
            return videos

      elif isinstance(_snake_case				,	(list, tuple)							) and is_valid_image(videos[0]							):
            return [videos]

      elif is_valid_image(_snake_case							):
            return [[videos]]

      raise ValueError(F'''Could not make batched video from {videos}'''							)







class  lowerCamelCase__ (	snake_case			):
    SCREAMING_SNAKE_CASE		=      ['''pixel_values''']






    def __init__(			self     ,A = True     ,A = None     ,A = PILImageResampling.BILINEAR     ,A = True     ,A = None     ,A = True     ,A = 1 / 255     ,A = True     ,A = True     ,A = None     ,A = None     ,**A     ,):
          super().__init__(**A )
          UpperCAmelCase          =	size if size is not None else {"""shortest_edge""": 256}
          UpperCAmelCase          =	get_size_dict(A     ,default_to_square=A )
          UpperCAmelCase          =	crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
          UpperCAmelCase          =	get_size_dict(A     ,param_name="""crop_size""" )

          UpperCAmelCase          =	do_resize
          UpperCAmelCase          =	size
          UpperCAmelCase          =	do_center_crop
          UpperCAmelCase          =	crop_size
          UpperCAmelCase          =	resample
          UpperCAmelCase          =	do_rescale
          UpperCAmelCase          =	rescale_factor
          UpperCAmelCase          =	offset
          UpperCAmelCase          =	do_normalize
          UpperCAmelCase          =	image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
          UpperCAmelCase          =	image_std if image_std is not None else IMAGENET_STANDARD_STD






    def     _UpperCamelCase							(			self     ,A     ,A     ,A = PILImageResampling.BILINEAR     ,A = None     ,**A     ,):
          UpperCAmelCase          =	get_size_dict(A     ,default_to_square=A )
          if "shortest_edge" in size:
                UpperCAmelCase          =	get_resize_output_image_size(A     ,size["""shortest_edge"""]     ,default_to_square=A )
          elif "height" in size and "width" in size:
                UpperCAmelCase          =	(size["""height"""], size["""width"""])
          else:
                raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' )
          return resize(A     ,size=A     ,resample=A     ,data_format=A     ,**A )






    def     _UpperCamelCase							(			self     ,A     ,A     ,A = None     ,**A     ,):
          UpperCAmelCase          =	get_size_dict(A )
          if "height" not in size or "width" not in size:
                raise ValueError(F'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' )
          return center_crop(A     ,size=(size["""height"""], size["""width"""])     ,data_format=A     ,**A )






    def     _UpperCamelCase							(			self     ,A     ,A     ,A = True     ,A = None     ,**A     ,):
          UpperCAmelCase          =	image.astype(np.floataa )
          if offset:
                UpperCAmelCase          =	image - (scale / 2)
          return rescale(A     ,scale=A     ,data_format=A     ,**A )






    def     _UpperCamelCase							(			self     ,A     ,A     ,A     ,A = None     ,**A     ,):
          return normalize(A     ,mean=A     ,std=A     ,data_format=A     ,**A )






    def     _UpperCamelCase							(			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     ,):
          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_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.""" )

          if offset and not do_rescale:
                raise ValueError("""For offset, do_rescale must also be set to True.""" )

          # All transformations expect numpy arrays.
          UpperCAmelCase          =	to_numpy_array(A )

          if do_resize:
                UpperCAmelCase          =	self.resize(image=A     ,size=A     ,resample=A )

          if do_center_crop:
                UpperCAmelCase          =	self.center_crop(A     ,size=A )

          if do_rescale:
                UpperCAmelCase          =	self.rescale(image=A     ,scale=A     ,offset=A )

          if do_normalize:
                UpperCAmelCase          =	self.normalize(image=A     ,mean=A     ,std=A )

          UpperCAmelCase          =	to_channel_dimension_format(A     ,A )
          return image






    def     _UpperCamelCase							(			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 = None     ,A = ChannelDimension.FIRST     ,**A     ,):
          UpperCAmelCase          =	do_resize if do_resize is not None else self.do_resize
          UpperCAmelCase          =	resample if resample is not None else self.resample
          UpperCAmelCase          =	do_center_crop if do_center_crop is not None else self.do_center_crop
          UpperCAmelCase          =	do_rescale if do_rescale is not None else self.do_rescale
          UpperCAmelCase          =	rescale_factor if rescale_factor is not None else self.rescale_factor
          UpperCAmelCase          =	offset if offset is not None else self.offset
          UpperCAmelCase          =	do_normalize if do_normalize is not None else self.do_normalize
          UpperCAmelCase          =	image_mean if image_mean is not None else self.image_mean
          UpperCAmelCase          =	image_std if image_std is not None else self.image_std

          UpperCAmelCase          =	size if size is not None else self.size
          UpperCAmelCase          =	get_size_dict(A     ,default_to_square=A )
          UpperCAmelCase          =	crop_size if crop_size is not None else self.crop_size
          UpperCAmelCase          =	get_size_dict(A     ,param_name="""crop_size""" )

          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.""" )

          UpperCAmelCase          =	make_batched(A )

          UpperCAmelCase          =	[
              [
                  self._preprocess_image(
                      image=A     ,do_resize=A     ,size=A     ,resample=A     ,do_center_crop=A     ,crop_size=A     ,do_rescale=A     ,rescale_factor=A     ,offset=A     ,do_normalize=A     ,image_mean=A     ,image_std=A     ,data_format=A     ,)
                  for img in video
              ]
              for video in videos
          ]

          UpperCAmelCase          =	{"""pixel_values""": videos}
          return BatchFeature(data=A     ,tensor_type=A )



