"""simple docstring"""







import unittest
from typing import Dict, List, Optional, Union

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 BridgeTowerImageProcessor







class  UpperCamelCase	(    unittest.TestCase						):
   def __init__(    self  ,__UpperCamelCase  ,__UpperCamelCase = True  ,__UpperCamelCase = None  ,__UpperCamelCase = 32  ,__UpperCamelCase = True  ,__UpperCamelCase = 1 / 255  ,__UpperCamelCase = True  ,__UpperCamelCase = True  ,__UpperCamelCase = [0.4814_5466, 0.457_8275, 0.4082_1073]  ,__UpperCamelCase = [0.2686_2954, 0.2613_0258, 0.2757_7711]  ,__UpperCamelCase = True  ,__UpperCamelCase=7  ,__UpperCamelCase=30  ,__UpperCamelCase=400  ,__UpperCamelCase=3  ,)			->   str:


        '''simple docstring'''


        lowercase_			:       Any									=			parent
        lowercase_			:       Any									=			do_resize
        lowercase_			:       Any									=			size if size is not None else {'shortest_edge': 288}
        lowercase_			:       Tuple									=			size_divisor
        lowercase_			:       Tuple									=			do_rescale
        lowercase_			:       List[str]									=			rescale_factor
        lowercase_			:       Tuple									=			do_normalize
        lowercase_			:       Optional[Any]									=			do_center_crop
        lowercase_			:       Dict									=			image_mean
        lowercase_			:       List[str]									=			image_std
        lowercase_			:       List[Any]									=			do_pad
        lowercase_			:       str									=			batch_size
        lowercase_			:       str									=			num_channels
        lowercase_			:       Tuple									=			min_resolution
        lowercase_			:       Optional[int]									=			max_resolution
   def     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "do_resize": self.do_resize,
            "size": self.size,
            "size_divisor": self.size_divisor,
        }







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase=False    )			->   Union[str, Any]:


        '''simple docstring'''


        if not batched:
             lowercase_			:       Dict									=			self.size['shortest_edge']
             lowercase_			:       Dict									=			image_inputs[0]
             if isinstance(__UpperCamelCase  ,Image.Image    ):
                  lowercase_							,						lowercase_			:       List[Any]									=			image.size
             else:
                  lowercase_							,						lowercase_			:       Optional[Any]									=			image.shape[1], image.shape[2]
             lowercase_			:       Any									=			size / min(__UpperCamelCase  ,__UpperCamelCase    )
             if h < w:
                  lowercase_							,						lowercase_			:       Tuple									=			size, scale * w
             else:
                  lowercase_							,						lowercase_			:       Dict									=			scale * h, size

             lowercase_			:       str									=			int((1333 / 800) * size    )
             if max(__UpperCamelCase  ,__UpperCamelCase    ) > max_size:
                  lowercase_			:       str									=			max_size / max(__UpperCamelCase  ,__UpperCamelCase    )
                  lowercase_			:       Union[str, Any]									=			newh * scale
                  lowercase_			:       str									=			neww * scale

             lowercase_							,						lowercase_			:       Dict									=			int(newh + 0.5    ), int(neww + 0.5    )
             lowercase_							,						lowercase_			:       Optional[Any]									=			(
                 newh // self.size_divisor * self.size_divisor,
                 neww // self.size_divisor * self.size_divisor,
             )

        else:
             lowercase_			:       str									=			[]
             for image in image_inputs:
                  lowercase_							,						lowercase_			:       Dict									=			self.get_expected_values([image]    )
                  expected_values.append((expected_height, expected_width)    )
             lowercase_			:       Any									=			max(__UpperCamelCase  ,key=lambda __UpperCamelCase    : item[0]    )[0]
             lowercase_			:       str									=			max(__UpperCamelCase  ,key=lambda __UpperCamelCase    : item[1]    )[1]

        return expected_height, expected_width







@require_torch
@require_vision
class  UpperCamelCase	(    lowercase_		,   unittest.TestCase						):
   lowercase							=						BridgeTowerImageProcessor if is_vision_available() else None
   def     _UpperCAmelCase     (    self    )			->   Optional[Any]:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			BridgeTowerImageProcessingTester(self    )
   @property
   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        return self.image_processor_tester.prepare_image_processor_dict()
   def     _UpperCAmelCase     (    self    )			->   List[str]:


        '''simple docstring'''


        lowercase_			:       str									=			self.image_processing_class(**self.image_processor_dict    )
        self.assertTrue(hasattr(__UpperCamelCase  ,'image_mean'    )    )
        self.assertTrue(hasattr(__UpperCamelCase  ,'image_std'    )    )
        self.assertTrue(hasattr(__UpperCamelCase  ,'do_normalize'    )    )
        self.assertTrue(hasattr(__UpperCamelCase  ,'do_resize'    )    )
        self.assertTrue(hasattr(__UpperCamelCase  ,'size'    )    )
        self.assertTrue(hasattr(__UpperCamelCase  ,'size_divisor'    )    )
   def     _UpperCAmelCase     (    self    )			->   Optional[int]:


        '''simple docstring'''


        pass
   def     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


        lowercase_			:       int									=			self.image_processing_class(**self.image_processor_dict    )
        # create random PIL images
        lowercase_			:       Tuple									=			prepare_image_inputs(self.image_processor_tester  ,equal_resolution=__UpperCamelCase    )
        for image in image_inputs:
             self.assertIsInstance(__UpperCamelCase  ,Image.Image    )

        # Test not batched input
        lowercase_			:       Optional[int]									=			image_processing(image_inputs[0]  ,return_tensors='pt'    ).pixel_values

        lowercase_							,						lowercase_			:       List[str]									=			self.image_processor_tester.get_expected_values(__UpperCamelCase    )
        self.assertEqual(
            encoded_images.shape  ,(1, self.image_processor_tester.num_channels, expected_height, expected_width)  ,)

        # Test batched
        lowercase_			:       List[str]									=			image_processing(__UpperCamelCase  ,return_tensors='pt'    ).pixel_values

        lowercase_							,						lowercase_			:       str									=			self.image_processor_tester.get_expected_values(__UpperCamelCase  ,batched=__UpperCamelCase    )
        self.assertEqual(
            encoded_images.shape  ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )  ,)
   def     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


        lowercase_			:       Tuple									=			self.image_processing_class(**self.image_processor_dict    )
        # create random numpy tensors
        lowercase_			:       Any									=			prepare_image_inputs(self.image_processor_tester  ,equal_resolution=__UpperCamelCase  ,numpify=__UpperCamelCase    )
        for image in image_inputs:
             self.assertIsInstance(__UpperCamelCase  ,np.ndarray    )

        # Test not batched input
        lowercase_			:       Union[str, Any]									=			image_processing(image_inputs[0]  ,return_tensors='pt'    ).pixel_values

        lowercase_							,						lowercase_			:       Dict									=			self.image_processor_tester.get_expected_values(__UpperCamelCase    )
        self.assertEqual(
            encoded_images.shape  ,(1, self.image_processor_tester.num_channels, expected_height, expected_width)  ,)

        # Test batched
        lowercase_			:       List[Any]									=			image_processing(__UpperCamelCase  ,return_tensors='pt'    ).pixel_values

        lowercase_							,						lowercase_			:       List[str]									=			self.image_processor_tester.get_expected_values(__UpperCamelCase  ,batched=__UpperCamelCase    )
        self.assertEqual(
            encoded_images.shape  ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )  ,)







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


        '''simple docstring'''


        lowercase_			:       str									=			self.image_processing_class(**self.image_processor_dict    )
        # create random PyTorch tensors
        lowercase_			:       Optional[int]									=			prepare_image_inputs(self.image_processor_tester  ,equal_resolution=__UpperCamelCase  ,torchify=__UpperCamelCase    )
        for image in image_inputs:
             self.assertIsInstance(__UpperCamelCase  ,torch.Tensor    )

        # Test not batched input
        lowercase_			:       int									=			image_processing(image_inputs[0]  ,return_tensors='pt'    ).pixel_values

        lowercase_							,						lowercase_			:       Tuple									=			self.image_processor_tester.get_expected_values(__UpperCamelCase    )
        self.assertEqual(
            encoded_images.shape  ,(1, self.image_processor_tester.num_channels, expected_height, expected_width)  ,)

        # Test batched
        lowercase_			:       Union[str, Any]									=			image_processing(__UpperCamelCase  ,return_tensors='pt'    ).pixel_values

        lowercase_							,						lowercase_			:       Dict									=			self.image_processor_tester.get_expected_values(__UpperCamelCase  ,batched=__UpperCamelCase    )
        self.assertEqual(
            encoded_images.shape  ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )  ,)


"""simple docstring"""







import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin







@skip_mps
class  UpperCamelCase	(    lowercase_		,   lowercase_		,   unittest.TestCase						):
   lowercase							=						IFImgaImgSuperResolutionPipeline
   lowercase							=						TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
   lowercase							=						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'}						)
   lowercase							=						PipelineTesterMixin.required_optional_params - {'latents'}
   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        return self._get_superresolution_dummy_components()
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase=0    )			->   List[str]:


        '''simple docstring'''


        if str(__UpperCamelCase    ).startswith('mps'    ):
             lowercase_			:       Any									=			torch.manual_seed(__UpperCamelCase    )
        else:
             lowercase_			:       int									=			torch.Generator(device=__UpperCamelCase    ).manual_seed(__UpperCamelCase    )

        lowercase_			:       Optional[int]									=			floats_tensor((1, 3, 32, 32)  ,rng=random.Random(__UpperCamelCase    )    ).to(__UpperCamelCase    )
        lowercase_			:       List[str]									=			floats_tensor((1, 3, 16, 16)  ,rng=random.Random(__UpperCamelCase    )    ).to(__UpperCamelCase    )

        lowercase_			:       Optional[Any]									=			{
            'prompt': 'A painting of a squirrel eating a burger',
            'image': image,
            'original_image': original_image,
            'generator': generator,
            'num_inference_steps': 2,
            'output_type': 'numpy',
        }

        return inputs
   @unittest.skipIf(
       torch_device != 'cuda' or not is_xformers_available()  ,reason='XFormers attention is only available with CUDA and `xformers` installed'  ,)
   def     _UpperCAmelCase     (    self    )			->   Optional[Any]:


        '''simple docstring'''


        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3    )
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        self._test_save_load_optional_components()
   @unittest.skipIf(torch_device != 'cuda'  ,reason='float16 requires CUDA'    )
   def     _UpperCAmelCase     (    self    )			->   Optional[int]:


        '''simple docstring'''


        super().test_save_load_floataa(expected_max_diff=1e-1    )
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        self._test_attention_slicing_forward_pass(expected_max_diff=1e-2    )
   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


        self._test_save_load_local()







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


        '''simple docstring'''


        self._test_inference_batch_single_identical(
            expected_max_diff=1e-2  ,)

