

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__ :     str				    =    logging.get_logger(__name__)






def 					__lowercase      (     _A			)     ->						List[List[ImageInput]]:
      if isinstance(_A						,    (list, tuple)			) and isinstance(videos[0]						,    (list, tuple)			) and is_valid_image(videos[0][0]			):
            return videos

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

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

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







class        a__       (   UpperCAmelCase       ):







  """simple docstring"""




  UpperCAmelCase__      : Dict			       =["""pixel_values"""]


  def __init__(			self    : Union[str, Any]				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : PILImageResampling = PILImageResampling.BILINEAR				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Union[int, float] = 1 / 2_5_5				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Optional[Union[float, List[float]]] = None				,				UpperCAmelCase__    : Optional[Union[float, List[float]]] = None				,				**UpperCAmelCase__    : Tuple				,				)					->None:
        """simple docstring"""







        super().__init__(**UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   size if size is not None else {"""shortest_edge""": 2_5_6}
        SCREAMING_SNAKE_CASE :      List[Any]       =   get_size_dict(UpperCAmelCase__				,				default_to_square=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   crop_size if crop_size is not None else {"""height""": 2_2_4, """width""": 2_2_4}
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   get_size_dict(UpperCAmelCase__				,				param_name="""crop_size"""		)

        SCREAMING_SNAKE_CASE :      List[Any]       =   do_resize
        SCREAMING_SNAKE_CASE :      Tuple       =   size
        SCREAMING_SNAKE_CASE :      str       =   do_center_crop
        SCREAMING_SNAKE_CASE :      List[str]       =   crop_size
        SCREAMING_SNAKE_CASE :      List[Any]       =   resample
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   do_rescale
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   rescale_factor
        SCREAMING_SNAKE_CASE :      Dict       =   offset
        SCREAMING_SNAKE_CASE :      str       =   do_normalize
        SCREAMING_SNAKE_CASE :      Optional[int]       =   image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
        SCREAMING_SNAKE_CASE :      Tuple       =   image_std if image_std is not None else IMAGENET_STANDARD_STD


  def  _lowercase      (			self    : Dict				,				UpperCAmelCase__    : np.ndarray				,				UpperCAmelCase__    : Dict[str, int]				,				UpperCAmelCase__    : PILImageResampling = PILImageResampling.BILINEAR				,				UpperCAmelCase__    : Optional[Union[str, ChannelDimension]] = None				,				**UpperCAmelCase__    : Optional[Any]				,				)					->np.ndarray:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Tuple       =   get_size_dict(UpperCAmelCase__				,				default_to_square=UpperCAmelCase__		)
        if "shortest_edge" in size:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   get_resize_output_image_size(UpperCAmelCase__				,				size["""shortest_edge"""]				,				default_to_square=UpperCAmelCase__		)
        elif "height" in size and "width" in size:
              SCREAMING_SNAKE_CASE :      Any       =   (size["""height"""], size["""width"""])
        else:
              raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}"		)
        return resize(UpperCAmelCase__				,				size=UpperCAmelCase__				,				resample=UpperCAmelCase__				,				data_format=UpperCAmelCase__				,				**UpperCAmelCase__		)


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







        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   get_size_dict(UpperCAmelCase__		)
        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(UpperCAmelCase__				,				size=(size["""height"""], size["""width"""])				,				data_format=UpperCAmelCase__				,				**UpperCAmelCase__		)


  def  _lowercase      (			self    : List[str]				,				UpperCAmelCase__    : np.ndarray				,				UpperCAmelCase__    : Union[int, float]				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Optional[Union[str, ChannelDimension]] = None				,				**UpperCAmelCase__    : Optional[int]				,				)					->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   image.astype(np.floataa		)
        if offset:
              SCREAMING_SNAKE_CASE :      int       =   image - (scale / 2)
        return rescale(UpperCAmelCase__				,				scale=UpperCAmelCase__				,				data_format=UpperCAmelCase__				,				**UpperCAmelCase__		)


  def  _lowercase      (			self    : Union[str, Any]				,				UpperCAmelCase__    : np.ndarray				,				UpperCAmelCase__    : Union[float, List[float]]				,				UpperCAmelCase__    : Union[float, List[float]]				,				UpperCAmelCase__    : Optional[Union[str, ChannelDimension]] = None				,				**UpperCAmelCase__    : str				,				)					->np.ndarray:
        """simple docstring"""







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


  def  _lowercase      (			self    : Optional[int]				,				UpperCAmelCase__    : ImageInput				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : PILImageResampling = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : float = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : Optional[Union[float, List[float]]] = None				,				UpperCAmelCase__    : Optional[Union[float, List[float]]] = None				,				UpperCAmelCase__    : Optional[ChannelDimension] = ChannelDimension.FIRST				,				)					->np.ndarray:
        """simple docstring"""







        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.
        SCREAMING_SNAKE_CASE :      List[str]       =   to_numpy_array(UpperCAmelCase__		)

        if do_resize:
              SCREAMING_SNAKE_CASE :      Tuple       =   self.resize(image=UpperCAmelCase__				,				size=UpperCAmelCase__				,				resample=UpperCAmelCase__		)

        if do_center_crop:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   self.center_crop(UpperCAmelCase__				,				size=UpperCAmelCase__		)

        if do_rescale:
              SCREAMING_SNAKE_CASE :      Dict       =   self.rescale(image=UpperCAmelCase__				,				scale=UpperCAmelCase__				,				offset=UpperCAmelCase__		)

        if do_normalize:
              SCREAMING_SNAKE_CASE :      Tuple       =   self.normalize(image=UpperCAmelCase__				,				mean=UpperCAmelCase__				,				std=UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      Tuple       =   to_channel_dimension_format(UpperCAmelCase__				,				UpperCAmelCase__		)
        return image




  def  _lowercase      (			self    : Dict				,				UpperCAmelCase__    : ImageInput				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : PILImageResampling = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : float = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : Optional[Union[float, List[float]]] = None				,				UpperCAmelCase__    : Optional[Union[float, List[float]]] = None				,				UpperCAmelCase__    : Optional[Union[str, TensorType]] = None				,				UpperCAmelCase__    : ChannelDimension = ChannelDimension.FIRST				,				**UpperCAmelCase__    : Dict				,				)					->PIL.Image.Image:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Tuple       =   do_resize if do_resize is not None else self.do_resize
        SCREAMING_SNAKE_CASE :      str       =   resample if resample is not None else self.resample
        SCREAMING_SNAKE_CASE :      List[str]       =   do_center_crop if do_center_crop is not None else self.do_center_crop
        SCREAMING_SNAKE_CASE :      List[str]       =   do_rescale if do_rescale is not None else self.do_rescale
        SCREAMING_SNAKE_CASE :      List[str]       =   rescale_factor if rescale_factor is not None else self.rescale_factor
        SCREAMING_SNAKE_CASE :      List[Any]       =   offset if offset is not None else self.offset
        SCREAMING_SNAKE_CASE :      List[str]       =   do_normalize if do_normalize is not None else self.do_normalize
        SCREAMING_SNAKE_CASE :      Optional[int]       =   image_mean if image_mean is not None else self.image_mean
        SCREAMING_SNAKE_CASE :      Tuple       =   image_std if image_std is not None else self.image_std

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

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

        SCREAMING_SNAKE_CASE :      Dict       =   make_batched(UpperCAmelCase__		)

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

        SCREAMING_SNAKE_CASE :      Optional[int]       =   {"""pixel_values""": videos}
        return BatchFeature(data=UpperCAmelCase__				,				tensor_type=UpperCAmelCase__		)







import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()







class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  def  _lowercase      (			self    : Union[str, Any]		)					->List[Any]:
        """simple docstring"""







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


  @property
  def  _lowercase      (			self    : str		)					->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   1
        SCREAMING_SNAKE_CASE :      Dict       =   3
        SCREAMING_SNAKE_CASE :      List[Any]       =   (3_2, 3_2)

        SCREAMING_SNAKE_CASE :      Any       =   floats_tensor((batch_size, num_channels) + sizes				,				rng=random.Random(0		)		).to(UpperCAmelCase__		)
        return image


  @property
  def  _lowercase      (			self    : Tuple		)					->List[Any]:
        """simple docstring"""







        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      str       =   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				,				)
        return model


  @property
  def  _lowercase      (			self    : str		)					->int:
        """simple docstring"""







        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Tuple       =   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				,				)
        return model


  @property
  def  _lowercase      (			self    : Tuple		)					->Union[str, Any]:
        """simple docstring"""







        torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      str       =   RobertaSeriesConfig(
            hidden_size=3_2				,				project_dim=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=5_0_0_6				,				)
        return RobertaSeriesModelWithTransformation(UpperCAmelCase__		)


  @property
  def  _lowercase      (			self    : Union[str, Any]		)					->List[str]:
        """simple docstring"""







        def extract(*UpperCAmelCase__    : List[Any]				,				**UpperCAmelCase__    : Tuple		):







              class        a__       :







                """simple docstring"""




                def __init__(			self    : Tuple		)					->Dict:
                      """simple docstring"""







                      SCREAMING_SNAKE_CASE :      Union[str, Any]       =   torch.ones([0]		)




                def  _lowercase      (			self    : Optional[int]				,				UpperCAmelCase__    : Dict		)					->Optional[Any]:
                      """simple docstring"""







                      self.pixel_values.to(UpperCAmelCase__		)
                      return self


              return Out()

        return extract


  def  _lowercase      (			self    : List[str]		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   """cpu"""  # ensure determinism for the device-dependent torch.Generator
        SCREAMING_SNAKE_CASE :      Optional[int]       =   self.dummy_cond_unet
        SCREAMING_SNAKE_CASE :      str       =   PNDMScheduler(skip_prk_steps=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   self.dummy_vae
        SCREAMING_SNAKE_CASE :      str       =   self.dummy_text_encoder
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   7_7

        SCREAMING_SNAKE_CASE :      str       =   self.dummy_image.to(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   init_image / 2 + 0.5

        # make sure here that pndm scheduler skips prk
        SCREAMING_SNAKE_CASE :      List[str]       =   AltDiffusionImgaImgPipeline(
            unet=UpperCAmelCase__				,				scheduler=UpperCAmelCase__				,				vae=UpperCAmelCase__				,				text_encoder=UpperCAmelCase__				,				tokenizer=UpperCAmelCase__				,				safety_checker=UpperCAmelCase__				,				feature_extractor=self.dummy_extractor				,				)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,				do_normalize=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Tuple       =   alt_pipe.to(UpperCAmelCase__		)
        alt_pipe.set_progress_bar_config(disable=UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      str       =   """A painting of a squirrel eating a burger"""
        SCREAMING_SNAKE_CASE :      Tuple       =   torch.Generator(device=UpperCAmelCase__		).manual_seed(0		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   alt_pipe(
            [prompt]				,				generator=UpperCAmelCase__				,				guidance_scale=6.0				,				num_inference_steps=2				,				output_type="""np"""				,				image=UpperCAmelCase__				,				)

        SCREAMING_SNAKE_CASE :      List[str]       =   output.images

        SCREAMING_SNAKE_CASE :      List[Any]       =   torch.Generator(device=UpperCAmelCase__		).manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Any       =   alt_pipe(
            [prompt]				,				generator=UpperCAmelCase__				,				guidance_scale=6.0				,				num_inference_steps=2				,				output_type="""np"""				,				image=UpperCAmelCase__				,				return_dict=UpperCAmelCase__				,				)[0]

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   image[0, -3:, -3:, -1]
        SCREAMING_SNAKE_CASE :      int       =   image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 3_2, 3_2, 3)
        SCREAMING_SNAKE_CASE :      str       =   np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99]		)

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


  @unittest.skipIf(torch_device != """cuda"""				,				"""This test requires a GPU"""		)
  def  _lowercase      (			self    : Optional[int]		)					->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.dummy_cond_unet
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   PNDMScheduler(skip_prk_steps=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      List[str]       =   self.dummy_vae
        SCREAMING_SNAKE_CASE :      int       =   self.dummy_text_encoder
        SCREAMING_SNAKE_CASE :      List[Any]       =   XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""		)
        SCREAMING_SNAKE_CASE :      Tuple       =   7_7

        SCREAMING_SNAKE_CASE :      Optional[int]       =   self.dummy_image.to(UpperCAmelCase__		)

        # put models in fp16
        SCREAMING_SNAKE_CASE :      List[Any]       =   unet.half()
        SCREAMING_SNAKE_CASE :      Tuple       =   vae.half()
        SCREAMING_SNAKE_CASE :      str       =   bert.half()

        # make sure here that pndm scheduler skips prk
        SCREAMING_SNAKE_CASE :      str       =   AltDiffusionImgaImgPipeline(
            unet=UpperCAmelCase__				,				scheduler=UpperCAmelCase__				,				vae=UpperCAmelCase__				,				text_encoder=UpperCAmelCase__				,				tokenizer=UpperCAmelCase__				,				safety_checker=UpperCAmelCase__				,				feature_extractor=self.dummy_extractor				,				)
        SCREAMING_SNAKE_CASE :      Optional[int]       =   VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,				do_normalize=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      str       =   alt_pipe.to(UpperCAmelCase__		)
        alt_pipe.set_progress_bar_config(disable=UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      int       =   """A painting of a squirrel eating a burger"""
        SCREAMING_SNAKE_CASE :      List[str]       =   torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Any       =   alt_pipe(
            [prompt]				,				generator=UpperCAmelCase__				,				num_inference_steps=2				,				output_type="""np"""				,				image=UpperCAmelCase__				,				).images

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




  @unittest.skipIf(torch_device != """cuda"""				,				"""This test requires a GPU"""		)
  def  _lowercase      (			self    : Dict		)					->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
            """/img2img/sketch-mountains-input.jpg"""		)
        # resize to resolution that is divisible by 8 but not 16 or 32
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   init_image.resize((7_6_0, 5_0_4)		)

        SCREAMING_SNAKE_CASE :      int       =   """BAAI/AltDiffusion"""
        SCREAMING_SNAKE_CASE :      List[str]       =   AltDiffusionImgaImgPipeline.from_pretrained(
            UpperCAmelCase__				,				safety_checker=UpperCAmelCase__				,				)
        pipe.to(UpperCAmelCase__		)
        pipe.set_progress_bar_config(disable=UpperCAmelCase__		)
        pipe.enable_attention_slicing()

        SCREAMING_SNAKE_CASE :      int       =   """A fantasy landscape, trending on artstation"""

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   pipe(
            prompt=UpperCAmelCase__				,				image=UpperCAmelCase__				,				strength=0.75				,				guidance_scale=7.5				,				generator=UpperCAmelCase__				,				output_type="""np"""				,				)
        SCREAMING_SNAKE_CASE :      Tuple       =   output.images[0]

        SCREAMING_SNAKE_CASE :      Tuple       =   image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

        assert image.shape == (5_0_4, 7_6_0, 3)
        SCREAMING_SNAKE_CASE :      List[str]       =   np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00]		)

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







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







  """simple docstring"""




  def  _lowercase      (			self    : Any		)					->List[str]:
        """simple docstring"""







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




  def  _lowercase      (			self    : Optional[Any]		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Any       =   load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
            """/img2img/sketch-mountains-input.jpg"""		)
        SCREAMING_SNAKE_CASE :      str       =   init_image.resize((7_6_8, 5_1_2)		)
        SCREAMING_SNAKE_CASE :      int       =   load_numpy(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""		)

        SCREAMING_SNAKE_CASE :      Tuple       =   """BAAI/AltDiffusion"""
        SCREAMING_SNAKE_CASE :      str       =   AltDiffusionImgaImgPipeline.from_pretrained(
            UpperCAmelCase__				,				safety_checker=UpperCAmelCase__				,				)
        pipe.to(UpperCAmelCase__		)
        pipe.set_progress_bar_config(disable=UpperCAmelCase__		)
        pipe.enable_attention_slicing()

        SCREAMING_SNAKE_CASE :      Dict       =   """A fantasy landscape, trending on artstation"""

        SCREAMING_SNAKE_CASE :      Optional[int]       =   torch.manual_seed(0		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   pipe(
            prompt=UpperCAmelCase__				,				image=UpperCAmelCase__				,				strength=0.75				,				guidance_scale=7.5				,				generator=UpperCAmelCase__				,				output_type="""np"""				,				)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   output.images[0]

        assert image.shape == (5_1_2, 7_6_8, 3)
        # img2img is flaky across GPUs even in fp32, so using MAE here
        assert np.abs(expected_image - image		).max() < 1e-2




