





import unittest

import numpy as np

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

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 PoolFormerImageProcessor






class 					lowercase__ (			unittest.TestCase       ):

   '''simple docstring'''


   def __init__(					self,	__magic_name__,	__magic_name__=7,	__magic_name__=3,	__magic_name__=30,	__magic_name__=400,	__magic_name__=True,	__magic_name__=None,	__magic_name__=0.9,	__magic_name__=None,	__magic_name__=True,	__magic_name__=[0.5, 0.5, 0.5],	__magic_name__=[0.5, 0.5, 0.5],	)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__							:       Optional[Any]      =   size if size is not None else {'''shortest_edge''': 30}
       UpperCamelCase__							:       Tuple      =   crop_size if crop_size is not None else {'''height''': 30, '''width''': 30}
       UpperCamelCase__							:       Union[str, Any]      =   parent
       UpperCamelCase__							:       Dict      =   batch_size
       UpperCamelCase__							:       int      =   num_channels
       UpperCamelCase__							:       List[Any]      =   min_resolution
       UpperCamelCase__							:       Dict      =   max_resolution
       UpperCamelCase__							:       Optional[int]      =   do_resize_and_center_crop
       UpperCamelCase__							:       int      =   size
       UpperCamelCase__							:       Dict      =   crop_pct
       UpperCamelCase__							:       List[Any]      =   crop_size
       UpperCamelCase__							:       Optional[int]      =   do_normalize
       UpperCamelCase__							:       Optional[int]      =   image_mean
       UpperCamelCase__							:       List[Any]      =   image_std




   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       return {
           "size": self.size,
           "do_resize_and_center_crop": self.do_resize_and_center_crop,
           "crop_pct": self.crop_pct,
           "crop_size": self.crop_size,
           "do_normalize": self.do_normalize,
           "image_mean": self.image_mean,
           "image_std": self.image_std,
       }






@require_torch
@require_vision
class 					lowercase__ (			__lowerCamelCase    ,       unittest.TestCase       ):

   '''simple docstring'''


   a		:							Any     	=	PoolFormerImageProcessor if is_vision_available() else None




   def    UpperCamelCase__						(					self							)				->   Optional[int]:






       """simple docstring"""
       UpperCamelCase__							:       List[Any]      =   PoolFormerImageProcessingTester(self							)




   @property
   def    UpperCamelCase__						(					self							)				->   Dict:






       """simple docstring"""
       return self.image_processor_tester.prepare_image_processor_dict()




   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:       Any      =   self.image_processing_class(**self.image_processor_dict							)
       self.assertTrue(hasattr(__magic_name__,	'''do_resize_and_center_crop'''							)							)
       self.assertTrue(hasattr(__magic_name__,	'''size'''							)							)
       self.assertTrue(hasattr(__magic_name__,	'''crop_pct'''							)							)
       self.assertTrue(hasattr(__magic_name__,	'''do_normalize'''							)							)
       self.assertTrue(hasattr(__magic_name__,	'''image_mean'''							)							)
       self.assertTrue(hasattr(__magic_name__,	'''image_std'''							)							)




   def    UpperCamelCase__						(					self							)				->   Union[str, Any]:






       """simple docstring"""
       UpperCamelCase__							:       Optional[Any]      =   self.image_processing_class.from_dict(self.image_processor_dict							)
       self.assertEqual(image_processor.size,	{'''shortest_edge''': 30}							)
       self.assertEqual(image_processor.crop_size,	{'''height''': 30, '''width''': 30}							)

       UpperCamelCase__							:       List[str]      =   self.image_processing_class.from_dict(self.image_processor_dict,	size=42,	crop_size=84							)
       self.assertEqual(image_processor.size,	{'''shortest_edge''': 42}							)
       self.assertEqual(image_processor.crop_size,	{'''height''': 84, '''width''': 84}							)




   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       pass




   def    UpperCamelCase__						(					self							)				->   List[Any]:






       """simple docstring"""
       # Initialize image_processing
       UpperCamelCase__							:       List[str]      =   self.image_processing_class(**self.image_processor_dict							)
       # create random PIL images
       UpperCamelCase__							:       Union[str, Any]      =   prepare_image_inputs(self.image_processor_tester,	equal_resolution=__magic_name__							)
       for image in image_inputs:
           self.assertIsInstance(__magic_name__,	Image.Image							)

       # Test not batched input
       UpperCamelCase__							:       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.crop_size['''height'''],
               self.image_processor_tester.crop_size['''width'''],
           ),	)

       # Test batched
       UpperCamelCase__							:       str      =   image_processing(__magic_name__,	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.crop_size['''height'''],
               self.image_processor_tester.crop_size['''width'''],
           ),	)




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       # Initialize image_processing
       UpperCamelCase__							:       List[str]      =   self.image_processing_class(**self.image_processor_dict							)
       # create random numpy tensors
       UpperCamelCase__							:       Optional[Any]      =   prepare_image_inputs(self.image_processor_tester,	equal_resolution=__magic_name__,	numpify=__magic_name__							)
       for image in image_inputs:
           self.assertIsInstance(__magic_name__,	np.ndarray							)

       # Test not batched input
       UpperCamelCase__							:       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.crop_size['''height'''],
               self.image_processor_tester.crop_size['''width'''],
           ),	)

       # Test batched
       UpperCamelCase__							:       List[Any]      =   image_processing(__magic_name__,	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.crop_size['''height'''],
               self.image_processor_tester.crop_size['''width'''],
           ),	)




   def    UpperCamelCase__						(					self							)				->   Dict:






       """simple docstring"""
       # Initialize image_processing
       UpperCamelCase__							:       Optional[int]      =   self.image_processing_class(**self.image_processor_dict							)
       # create random PyTorch tensors
       UpperCamelCase__							:       Optional[int]      =   prepare_image_inputs(self.image_processor_tester,	equal_resolution=__magic_name__,	torchify=__magic_name__							)
       for image in image_inputs:
           self.assertIsInstance(__magic_name__,	torch.Tensor							)

       # Test not batched input
       UpperCamelCase__							:       Optional[int]      =   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.crop_size['''height'''],
               self.image_processor_tester.crop_size['''width'''],
           ),	)

       # Test batched
       UpperCamelCase__							:       int      =   image_processing(__magic_name__,	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.crop_size['''height'''],
               self.image_processor_tester.crop_size['''width'''],
           ),	)








import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


UpperCAmelCase_  							=				False






class 					lowercase__ (			unittest.TestCase       ):

   '''simple docstring'''


   pass






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

   '''simple docstring'''


   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




   def    UpperCamelCase__						(					self							)				->   List[Any]:






       """simple docstring"""
       UpperCamelCase__							:       Dict      =   VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion'''							)
       # remove text_unet
       pipe.remove_unused_weights()
       pipe.to(__magic_name__							)
       pipe.set_progress_bar_config(disable=__magic_name__							)

       UpperCamelCase__							:       int      =   '''A painting of a squirrel eating a burger '''
       UpperCamelCase__							:       str      =   torch.manual_seed(0							)
       UpperCamelCase__							:       int      =   pipe(
           prompt=__magic_name__,	generator=__magic_name__,	guidance_scale=7.5,	num_inference_steps=2,	output_type='''numpy'''							).images

       with tempfile.TemporaryDirectory() as tmpdirname:
           pipe.save_pretrained(__magic_name__							)
           UpperCamelCase__							:       Union[str, Any]      =   VersatileDiffusionTextToImagePipeline.from_pretrained(__magic_name__							)
       pipe.to(__magic_name__							)
       pipe.set_progress_bar_config(disable=__magic_name__							)

       UpperCamelCase__							:       Optional[Any]      =   generator.manual_seed(0							)
       UpperCamelCase__							:       str      =   pipe(
           prompt=__magic_name__,	generator=__magic_name__,	guidance_scale=7.5,	num_inference_steps=2,	output_type='''numpy'''							).images

       assert np.abs(image - new_image							).sum() < 1E-5, "Models don't have the same forward pass"




   def    UpperCamelCase__						(					self							)				->   Any:






       """simple docstring"""
       UpperCamelCase__							:       str      =   VersatileDiffusionTextToImagePipeline.from_pretrained(
           '''shi-labs/versatile-diffusion''',	torch_dtype=torch.floataa							)
       pipe.to(__magic_name__							)
       pipe.set_progress_bar_config(disable=__magic_name__							)

       UpperCamelCase__							:       Optional[int]      =   '''A painting of a squirrel eating a burger '''
       UpperCamelCase__							:       str      =   torch.manual_seed(0							)
       UpperCamelCase__							:       Optional[int]      =   pipe(
           prompt=__magic_name__,	generator=__magic_name__,	guidance_scale=7.5,	num_inference_steps=50,	output_type='''numpy'''							).images

       UpperCamelCase__							:       int      =   image[0, 253:256, 253:256, -1]

       assert image.shape == (1, 512, 512, 3)
       UpperCamelCase__							:       int      =   np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778]							)

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

