





'''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     ):



     '''simple docstring'''

     def __init__(							self		:					str		,lowerCamelCase__		:					str		,lowerCamelCase__		:					bool = True		,lowerCamelCase__		:					Dict[str, int] = None		,lowerCamelCase__		:					int = 32		,lowerCamelCase__		:					bool = True		,lowerCamelCase__		:					Union[int, float] = 1 / 255		,lowerCamelCase__		:					bool = True		,lowerCamelCase__		:					bool = True		,lowerCamelCase__		:					Optional[Union[float, List[float]]] = [0.48145466, 0.4578275, 0.40821073]		,lowerCamelCase__		:					Optional[Union[float, List[float]]] = [0.26862954, 0.26130258, 0.27577711]		,lowerCamelCase__		:					bool = True		,lowerCamelCase__		:					str=7		,lowerCamelCase__		:					Any=30		,lowerCamelCase__		:					str=400		,lowerCamelCase__		:					Optional[Any]=3		,)  ->	int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		parent
           SCREAMING_SNAKE_CASE	=		do_resize
           SCREAMING_SNAKE_CASE	=		size if size is not None else {"""shortest_edge""": 288}
           SCREAMING_SNAKE_CASE	=		size_divisor
           SCREAMING_SNAKE_CASE	=		do_rescale
           SCREAMING_SNAKE_CASE	=		rescale_factor
           SCREAMING_SNAKE_CASE	=		do_normalize
           SCREAMING_SNAKE_CASE	=		do_center_crop
           SCREAMING_SNAKE_CASE	=		image_mean
           SCREAMING_SNAKE_CASE	=		image_std
           SCREAMING_SNAKE_CASE	=		do_pad
           SCREAMING_SNAKE_CASE	=		batch_size
           SCREAMING_SNAKE_CASE	=		num_channels
           SCREAMING_SNAKE_CASE	=		min_resolution
           SCREAMING_SNAKE_CASE	=		max_resolution






     def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	List[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        SCREAMING_SNAKE_CASE__						(							self		:					int		,lowerCamelCase__		:					Tuple		,lowerCamelCase__		:					Union[str, Any]=False )  ->	Any:




           '''simple docstring'''


           if not batched:
                 SCREAMING_SNAKE_CASE	=		self.size["""shortest_edge"""]
                 SCREAMING_SNAKE_CASE	=		image_inputs[0]
                 if isinstance(lowerCamelCase__		,Image.Image ):
                       SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		image.size
                 else:
                       SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		image.shape[1], image.shape[2]
                 SCREAMING_SNAKE_CASE	=		size / min(lowerCamelCase__		,lowerCamelCase__ )
                 if h < w:
                       SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		size, scale * w
                 else:
                       SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		scale * h, size

                 SCREAMING_SNAKE_CASE	=		int((1333 / 800) * size )
                 if max(lowerCamelCase__		,lowerCamelCase__ ) > max_size:
                       SCREAMING_SNAKE_CASE	=		max_size / max(lowerCamelCase__		,lowerCamelCase__ )
                       SCREAMING_SNAKE_CASE	=		newh * scale
                       SCREAMING_SNAKE_CASE	=		neww * scale

                 SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		int(newh + 0.5 ), int(neww + 0.5 )
                 SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		(
                     newh // self.size_divisor * self.size_divisor,
                     neww // self.size_divisor * self.size_divisor,
                 )

           else:
                 SCREAMING_SNAKE_CASE	=		[]
                 for image in image_inputs:
                       SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.get_expected_values([image] )
                       expected_values.append((expected_height, expected_width) )
                 SCREAMING_SNAKE_CASE	=		max(lowerCamelCase__		,key=lambda lowerCamelCase__ : item[0] )[0]
                 SCREAMING_SNAKE_CASE	=		max(lowerCamelCase__		,key=lambda lowerCamelCase__ : item[1] )[1]

           return expected_height, expected_width

@require_torch
@require_vision
class 	UpperCamelCase__				(   lowerCAmelCase_							,   unittest.TestCase     ):



     '''simple docstring'''

     __snake_case					:			Optional[int]				=    BridgeTowerImageProcessor if is_vision_available() else None






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		BridgeTowerImageProcessingTester(self )






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Dict:




           '''simple docstring'''


           return self.image_processor_tester.prepare_image_processor_dict()






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Optional[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.image_processing_class(**self.image_processor_dict )
           self.assertTrue(hasattr(lowerCamelCase__		,"""image_mean""" ) )
           self.assertTrue(hasattr(lowerCamelCase__		,"""image_std""" ) )
           self.assertTrue(hasattr(lowerCamelCase__		,"""do_normalize""" ) )
           self.assertTrue(hasattr(lowerCamelCase__		,"""do_resize""" ) )
           self.assertTrue(hasattr(lowerCamelCase__		,"""size""" ) )
           self.assertTrue(hasattr(lowerCamelCase__		,"""size_divisor""" ) )






     def        SCREAMING_SNAKE_CASE__						(							self		:					Dict )  ->	Optional[Any]:




           '''simple docstring'''


           pass






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	Any:




           '''simple docstring'''


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

           # Test not batched input
           SCREAMING_SNAKE_CASE	=		image_processing(image_inputs[0]		,return_tensors="""pt""" ).pixel_values

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.image_processor_tester.get_expected_values(lowerCamelCase__ )
           self.assertEqual(
               encoded_images.shape		,(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,)

           # Test batched
           SCREAMING_SNAKE_CASE	=		image_processing(lowerCamelCase__		,return_tensors="""pt""" ).pixel_values

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.image_processor_tester.get_expected_values(lowerCamelCase__		,batched=lowerCamelCase__ )
           self.assertEqual(
               encoded_images.shape		,(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   expected_height,
                   expected_width,
               )		,)






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	List[Any]:




           '''simple docstring'''


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

           # Test not batched input
           SCREAMING_SNAKE_CASE	=		image_processing(image_inputs[0]		,return_tensors="""pt""" ).pixel_values

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.image_processor_tester.get_expected_values(lowerCamelCase__ )
           self.assertEqual(
               encoded_images.shape		,(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,)

           # Test batched
           SCREAMING_SNAKE_CASE	=		image_processing(lowerCamelCase__		,return_tensors="""pt""" ).pixel_values

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.image_processor_tester.get_expected_values(lowerCamelCase__		,batched=lowerCamelCase__ )
           self.assertEqual(
               encoded_images.shape		,(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   expected_height,
                   expected_width,
               )		,)






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.image_processing_class(**self.image_processor_dict )
           # create random PyTorch tensors
           SCREAMING_SNAKE_CASE	=		prepare_image_inputs(self.image_processor_tester		,equal_resolution=lowerCamelCase__		,torchify=lowerCamelCase__ )
           for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase__		,torch.Tensor )

           # Test not batched input
           SCREAMING_SNAKE_CASE	=		image_processing(image_inputs[0]		,return_tensors="""pt""" ).pixel_values

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.image_processor_tester.get_expected_values(lowerCamelCase__ )
           self.assertEqual(
               encoded_images.shape		,(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,)

           # Test batched
           SCREAMING_SNAKE_CASE	=		image_processing(lowerCamelCase__		,return_tensors="""pt""" ).pixel_values

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.image_processor_tester.get_expected_values(lowerCamelCase__		,batched=lowerCamelCase__ )
           self.assertEqual(
               encoded_images.shape		,(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   expected_height,
                   expected_width,
               )		,)









import unittest

import torch

from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

class 	UpperCamelCase__				(   lowerCAmelCase_							,   lowerCAmelCase_							,   unittest.TestCase     ):



     '''simple docstring'''

     __snake_case					:			str				=    VQModel
     __snake_case					:			Optional[Any]				=    "sample"






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple		,lowerCamelCase__		:					Optional[Any]=(32, 32) )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		4
           SCREAMING_SNAKE_CASE	=		3

           SCREAMING_SNAKE_CASE	=		floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase__ )

           return {"sample": image}






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any] )  ->	List[str]:




           '''simple docstring'''


           return (3, 32, 32)






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	List[str]:




           '''simple docstring'''


           return (3, 32, 32)






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		{
               """block_out_channels""": [32, 64],
               """in_channels""": 3,
               """out_channels""": 3,
               """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""],
               """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""],
               """latent_channels""": 3,
           }
           SCREAMING_SNAKE_CASE	=		self.dummy_input
           return init_dict, inputs_dict






     def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	str:




           '''simple docstring'''


           pass






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




           '''simple docstring'''


           pass






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		VQModel.from_pretrained("""fusing/vqgan-dummy"""		,output_loading_info=lowerCamelCase__ )
           self.assertIsNotNone(lowerCamelCase__ )
           self.assertEqual(len(loading_info["""missing_keys"""] )		,0 )

           model.to(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		model(**self.dummy_input )

           assert image is not None, "Make sure output is not None"






     def        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		VQModel.from_pretrained("""fusing/vqgan-dummy""" )
           model.to(lowerCamelCase__ ).eval()

           torch.manual_seed(0 )
           if torch.cuda.is_available():
                 torch.cuda.manual_seed_all(0 )

           SCREAMING_SNAKE_CASE	=		torch.randn(1		,model.config.in_channels		,model.config.sample_size		,model.config.sample_size )
           SCREAMING_SNAKE_CASE	=		image.to(lowerCamelCase__ )
           with torch.no_grad():
                 SCREAMING_SNAKE_CASE	=		model(lowerCamelCase__ ).sample

           SCREAMING_SNAKE_CASE	=		output[0, -1, -3:, -3:].flatten().cpu()
           # fmt: off
           SCREAMING_SNAKE_CASE	=		torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] )
           # fmt: on
           self.assertTrue(torch.allclose(lowerCamelCase__		,lowerCamelCase__		,atol=1e-3 ) )


