




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 		lowercase							(     unittest.TestCase	):

     def       a__			(						self       )		->							Any:
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()

     @property
     def       a__			(						self       )		->							Union[str, Any]:
           _A							:  Dict    =		1
           _A							:  List[Any]    =		3
           _A							:  str    =		(32, 32)

           _A							:  Dict    =		floats_tensor((batch_size, num_channels) + sizes	,  rng=random.Random(0       )       ).to(_a       )
           return image

     @property
     def       a__			(						self       )		->							str:
           torch.manual_seed(0       )
           _A							:  List[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	,  )
           return model

     @property
     def       a__			(						self       )		->							int:
           torch.manual_seed(0       )
           _A							:  Union[str, 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	,  )
           return model

     @property
     def       a__			(						self       )		->							Union[str, Any]:
           torch.manual_seed(0       )
           _A							:  Union[str, Any]    =		RobertaSeriesConfig(
               hidden_size=32	,  project_dim=32	,  intermediate_size=37	,  layer_norm_eps=1e-05	,  num_attention_heads=4	,  num_hidden_layers=5	,  pad_token_id=1	,  vocab_size=5006	,  )
           return RobertaSeriesModelWithTransformation(_a       )

     @property
     def       a__			(						self       )		->							int:
           def extract(*_a	,  **_a       ):







                 class 		lowercase							:

                      def __init__(						self       )		->							Any:
                            _A							:  List[Any]    =		torch.ones([0]       )



                      def       a__			(						self	,  _a       )		->							Optional[Any]:
                            self.pixel_values.to(_a       )
                            return self


                 return Out()

           return extract

     def       a__			(						self       )		->							Tuple:
           _A							:  str    =		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
           _A							:  int    =		self.dummy_cond_unet
           _A							:  List[Any]    =		PNDMScheduler(skip_prk_steps=_a       )
           _A							:  Optional[int]    =		self.dummy_vae
           _A							:  Dict    =		self.dummy_text_encoder
           _A							:  Union[str, Any]    =		XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""       )
           _A							:  List[Any]    =		77

           _A							:  str    =		self.dummy_image.to(_a       )
           _A							:  Any    =		init_image / 2 + 0.5

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

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

           _A							:  Any    =		output.images

           _A							:  int    =		torch.Generator(device=_a       ).manual_seed(0       )
           _A							:  Tuple    =		alt_pipe(
               [prompt]	,  generator=_a	,  guidance_scale=6.0	,  num_inference_steps=2	,  output_type="""np"""	,  image=_a	,  return_dict=_a	,  )[0]

           _A							:  List[Any]    =		image[0, -3:, -3:, -1]
           _A							:  Optional[Any]    =		image_from_tuple[0, -3:, -3:, -1]

           assert image.shape == (1, 32, 32, 3)
           _A							:  Dict    =		np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]       )

           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       a__			(						self       )		->							Optional[Any]:
           _A							:  int    =		self.dummy_cond_unet
           _A							:  List[str]    =		PNDMScheduler(skip_prk_steps=_a       )
           _A							:  List[str]    =		self.dummy_vae
           _A							:  Tuple    =		self.dummy_text_encoder
           _A							:  str    =		XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""       )
           _A							:  str    =		77

           _A							:  List[Any]    =		self.dummy_image.to(_a       )

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

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

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

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



     @unittest.skipIf(torch_device != """cuda"""	,  """This test requires a GPU"""       )
     def       a__			(						self       )		->							str:
           _A							:  Tuple    =		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
           _A							:  Union[str, Any]    =		init_image.resize((760, 504)       )

           _A							:  Union[str, Any]    =		"""BAAI/AltDiffusion"""
           _A							:  Any    =		AltDiffusionImgaImgPipeline.from_pretrained(
               _a	,  safety_checker=_a	,  )
           pipe.to(_a       )
           pipe.set_progress_bar_config(disable=_a       )
           pipe.enable_attention_slicing()

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

           _A							:  Tuple    =		torch.manual_seed(0       )
           _A							:  int    =		pipe(
               prompt=_a	,  image=_a	,  strength=0.75	,  guidance_scale=7.5	,  generator=_a	,  output_type="""np"""	,  )
           _A							:  int    =		output.images[0]

           _A							:  List[str]    =		image[255:258, 383:386, -1]

           assert image.shape == (504, 760, 3)
           _A							:  Dict    =		np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]       )

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







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

     def       a__			(						self       )		->							Tuple:
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()



     def       a__			(						self       )		->							Tuple:
           _A							:  List[Any]    =		load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/img2img/sketch-mountains-input.jpg"""       )
           _A							:  str    =		init_image.resize((768, 512)       )
           _A							:  List[Any]    =		load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""       )

           _A							:  str    =		"""BAAI/AltDiffusion"""
           _A							:  str    =		AltDiffusionImgaImgPipeline.from_pretrained(
               _a	,  safety_checker=_a	,  )
           pipe.to(_a       )
           pipe.set_progress_bar_config(disable=_a       )
           pipe.enable_attention_slicing()

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

           _A							:  str    =		torch.manual_seed(0       )
           _A							:  int    =		pipe(
               prompt=_a	,  image=_a	,  strength=0.75	,  guidance_scale=7.5	,  generator=_a	,  output_type="""np"""	,  )
           _A							:  int    =		output.images[0]

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







import unittest

import numpy as np

from transformers.file_utils import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import DPTImageProcessor







class 		lowercase							(     unittest.TestCase	):

     def __init__(						self	,  _a	,  _a=7	,  _a=3	,  _a=18	,  _a=30	,  _a=400	,  _a=True	,  _a=None	,  _a=True	,  _a=[0.5, 0.5, 0.5]	,  _a=[0.5, 0.5, 0.5]	,  )		->							Tuple:
           _A							:  Any    =		size if size is not None else {"""height""": 18, """width""": 18}
           _A							:  Optional[Any]    =		parent
           _A							:  Union[str, Any]    =		batch_size
           _A							:  List[Any]    =		num_channels
           _A							:  List[str]    =		image_size
           _A							:  Optional[Any]    =		min_resolution
           _A							:  List[Any]    =		max_resolution
           _A							:  Optional[Any]    =		do_resize
           _A							:  str    =		size
           _A							:  List[str]    =		do_normalize
           _A							:  Dict    =		image_mean
           _A							:  int    =		image_std



     def       a__			(						self       )		->							Any:
           return {
               "image_mean": self.image_mean,
               "image_std": self.image_std,
               "do_normalize": self.do_normalize,
               "do_resize": self.do_resize,
               "size": self.size,
           }







@require_torch
@require_vision
class 		lowercase							(     UpperCamelCase__,unittest.TestCase	):
     _a											=		DPTImageProcessor if is_vision_available() else None

     def       a__			(						self       )		->							Optional[int]:
           _A							:  Optional[Any]    =		DPTImageProcessingTester(self       )

     @property
     def       a__			(						self       )		->							Tuple:
           return self.image_processor_tester.prepare_image_processor_dict()

     def       a__			(						self       )		->							Any:
           _A							:  List[str]    =		self.image_processing_class(**self.image_processor_dict       )
           self.assertTrue(hasattr(_a	,  """image_mean"""       )       )
           self.assertTrue(hasattr(_a	,  """image_std"""       )       )
           self.assertTrue(hasattr(_a	,  """do_normalize"""       )       )
           self.assertTrue(hasattr(_a	,  """do_resize"""       )       )
           self.assertTrue(hasattr(_a	,  """size"""       )       )

     def       a__			(						self       )		->							Any:
           _A							:  List[str]    =		self.image_processing_class.from_dict(self.image_processor_dict       )
           self.assertEqual(image_processor.size	,  {"""height""": 18, """width""": 18}       )

           _A							:  str    =		self.image_processing_class.from_dict(self.image_processor_dict	,  size=42       )
           self.assertEqual(image_processor.size	,  {"""height""": 42, """width""": 42}       )

     def       a__			(						self       )		->							List[Any]:
           # Initialize image_processing
           _A							:  Optional[int]    =		self.image_processing_class(**self.image_processor_dict       )
           # create random PIL images
           _A							:  Any    =		prepare_image_inputs(self.image_processor_tester	,  equal_resolution=_a       )
           for image in image_inputs:
                 self.assertIsInstance(_a	,  Image.Image       )

           # Test not batched input
           _A							:  Union[str, Any]    =		image_processing(image_inputs[0]	,  return_tensors="""pt"""       ).pixel_values
           self.assertEqual(
               encoded_images.shape	,  (
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )	,  )

           # Test batched
           _A							:  int    =		image_processing(_a	,  return_tensors="""pt"""       ).pixel_values
           self.assertEqual(
               encoded_images.shape	,  (
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )	,  )

     def       a__			(						self       )		->							Union[str, Any]:
           # Initialize image_processing
           _A							:  List[Any]    =		self.image_processing_class(**self.image_processor_dict       )
           # create random numpy tensors
           _A							:  Optional[Any]    =		prepare_image_inputs(self.image_processor_tester	,  equal_resolution=_a	,  numpify=_a       )
           for image in image_inputs:
                 self.assertIsInstance(_a	,  np.ndarray       )

           # Test not batched input
           _A							:  Dict    =		image_processing(image_inputs[0]	,  return_tensors="""pt"""       ).pixel_values
           self.assertEqual(
               encoded_images.shape	,  (
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )	,  )

           # Test batched
           _A							:  Any    =		image_processing(_a	,  return_tensors="""pt"""       ).pixel_values
           self.assertEqual(
               encoded_images.shape	,  (
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )	,  )



     def       a__			(						self       )		->							List[str]:
           # Initialize image_processing
           _A							:  Dict    =		self.image_processing_class(**self.image_processor_dict       )
           # create random PyTorch tensors
           _A							:  str    =		prepare_image_inputs(self.image_processor_tester	,  equal_resolution=_a	,  torchify=_a       )
           for image in image_inputs:
                 self.assertIsInstance(_a	,  torch.Tensor       )

           # Test not batched input
           _A							:  Optional[Any]    =		image_processing(image_inputs[0]	,  return_tensors="""pt"""       ).pixel_values
           self.assertEqual(
               encoded_images.shape	,  (
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )	,  )

           # Test batched
           _A							:  int    =		image_processing(_a	,  return_tensors="""pt"""       ).pixel_values
           self.assertEqual(
               encoded_images.shape	,  (
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )	,  )

