


"""simple docstring"""
import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
				from PIL import Image

				from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
				import torch

if is_tf_available():
				import tensorflow as tf





@require_vision
@require_torchvision
class      __A     (unittest.TestCase):





							'''simple docstring'''

							def 		lowerCAmelCase       (				self							:      int       )					->str:



														"""simple docstring"""



														snake_case_           =		tempfile.mkdtemp()
														snake_case_           =		SamImageProcessor()
														snake_case_           =		SamProcessor(UpperCAmelCase_       )
														processor.save_pretrained(self.tmpdirname       )



							def 		lowerCAmelCase       (				self							:      List[Any]		,       **UpperCAmelCase_							:      Any       )					->Tuple:



														"""simple docstring"""



														return AutoProcessor.from_pretrained(self.tmpdirname		,       **UpperCAmelCase_       ).image_processor



							def 		lowerCAmelCase       (				self							:      List[str]       )					->Dict:



														"""simple docstring"""



														shutil.rmtree(self.tmpdirname       )



							def 		lowerCAmelCase       (				self							:      Dict       )					->Optional[int]:



														"""simple docstring"""



														snake_case_           =		[np.random.randint(255		,       size=(3, 30, 400)		,       dtype=np.uinta       )]

														snake_case_           =		[Image.fromarray(np.moveaxis(UpperCAmelCase_		,       0		,       -1       )       ) for x in image_inputs]

														return image_inputs



							def 		lowerCAmelCase       (				self							:      Any       )					->str:



														"""simple docstring"""



														snake_case_           =		SamProcessor(image_processor=self.get_image_processor()       )
														processor.save_pretrained(self.tmpdirname       )

														snake_case_           =		self.get_image_processor(do_normalize=UpperCAmelCase_		,       padding_value=1.0       )

														snake_case_           =		SamProcessor.from_pretrained(self.tmpdirname		,       do_normalize=UpperCAmelCase_		,       padding_value=1.0       )

														self.assertEqual(processor.image_processor.to_json_string()		,       image_processor_add_kwargs.to_json_string()       )
														self.assertIsInstance(processor.image_processor		,       UpperCAmelCase_       )



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



														"""simple docstring"""



														snake_case_           =		self.get_image_processor()

														snake_case_           =		SamProcessor(image_processor=UpperCAmelCase_       )

														snake_case_           =		self.prepare_image_inputs()

														snake_case_           =		image_processor(UpperCAmelCase_		,       return_tensors="""np"""       )
														snake_case_           =		processor(images=UpperCAmelCase_		,       return_tensors="""np"""       )

														input_feat_extract.pop("""original_sizes"""       )  # pop original_sizes as it is popped in the processor
														input_feat_extract.pop("""reshaped_input_sizes"""       )  # pop original_sizes as it is popped in the processor

														for key in input_feat_extract.keys():
																					self.assertAlmostEqual(input_feat_extract[key].sum()		,       input_processor[key].sum()		,       delta=1E-2       )



							@require_torch
							def 		lowerCAmelCase       (				self							:      Optional[Any]       )					->int:



														"""simple docstring"""



														snake_case_           =		self.get_image_processor()

														snake_case_           =		SamProcessor(image_processor=UpperCAmelCase_       )
														snake_case_           =		[torch.ones((1, 3, 5, 5)       )]

														snake_case_           =		[[1_764, 2_646]]

														snake_case_           =		[[683, 1_024]]
														snake_case_           =		processor.post_process_masks(UpperCAmelCase_		,       UpperCAmelCase_		,       UpperCAmelCase_       )
														self.assertEqual(masks[0].shape		,       (1, 3, 1_764, 2_646)       )

														snake_case_           =		processor.post_process_masks(
														    UpperCAmelCase_		,       torch.tensor(UpperCAmelCase_       )		,       torch.tensor(UpperCAmelCase_       )       )
														self.assertEqual(masks[0].shape		,       (1, 3, 1_764, 2_646)       )

														# should also work with np
														snake_case_           =		[np.ones((1, 3, 5, 5)       )]
														snake_case_           =		processor.post_process_masks(UpperCAmelCase_		,       np.array(UpperCAmelCase_       )		,       np.array(UpperCAmelCase_       )       )

														self.assertEqual(masks[0].shape		,       (1, 3, 1_764, 2_646)       )

														snake_case_           =		[[1, 0], [0, 1]]
														with self.assertRaises(UpperCAmelCase_       ):
																					snake_case_           =		processor.post_process_masks(UpperCAmelCase_		,       np.array(UpperCAmelCase_       )		,       np.array(UpperCAmelCase_       )       )





@require_vision
@require_tf
class      __A     (unittest.TestCase):





							'''simple docstring'''

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



														"""simple docstring"""



														snake_case_           =		tempfile.mkdtemp()
														snake_case_           =		SamImageProcessor()
														snake_case_           =		SamProcessor(UpperCAmelCase_       )
														processor.save_pretrained(self.tmpdirname       )



							def 		lowerCAmelCase       (				self							:      Optional[Any]		,       **UpperCAmelCase_							:      Tuple       )					->Dict:



														"""simple docstring"""



														return AutoProcessor.from_pretrained(self.tmpdirname		,       **UpperCAmelCase_       ).image_processor



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



														"""simple docstring"""



														shutil.rmtree(self.tmpdirname       )



							def 		lowerCAmelCase       (				self							:      Dict       )					->List[Any]:



														"""simple docstring"""



														snake_case_           =		[np.random.randint(255		,       size=(3, 30, 400)		,       dtype=np.uinta       )]

														snake_case_           =		[Image.fromarray(np.moveaxis(UpperCAmelCase_		,       0		,       -1       )       ) for x in image_inputs]

														return image_inputs



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



														"""simple docstring"""



														snake_case_           =		SamProcessor(image_processor=self.get_image_processor()       )
														processor.save_pretrained(self.tmpdirname       )

														snake_case_           =		self.get_image_processor(do_normalize=UpperCAmelCase_		,       padding_value=1.0       )

														snake_case_           =		SamProcessor.from_pretrained(self.tmpdirname		,       do_normalize=UpperCAmelCase_		,       padding_value=1.0       )

														self.assertEqual(processor.image_processor.to_json_string()		,       image_processor_add_kwargs.to_json_string()       )
														self.assertIsInstance(processor.image_processor		,       UpperCAmelCase_       )



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



														"""simple docstring"""



														snake_case_           =		self.get_image_processor()

														snake_case_           =		SamProcessor(image_processor=UpperCAmelCase_       )

														snake_case_           =		self.prepare_image_inputs()

														snake_case_           =		image_processor(UpperCAmelCase_		,       return_tensors="""np"""       )
														snake_case_           =		processor(images=UpperCAmelCase_		,       return_tensors="""np"""       )

														input_feat_extract.pop("""original_sizes"""       )  # pop original_sizes as it is popped in the processor
														input_feat_extract.pop("""reshaped_input_sizes"""       )  # pop reshaped_input_sizes as it is popped in the processor

														for key in input_feat_extract.keys():
																					self.assertAlmostEqual(input_feat_extract[key].sum()		,       input_processor[key].sum()		,       delta=1E-2       )



							@require_tf
							def 		lowerCAmelCase       (				self							:      List[Any]       )					->List[Any]:



														"""simple docstring"""



														snake_case_           =		self.get_image_processor()

														snake_case_           =		SamProcessor(image_processor=UpperCAmelCase_       )
														snake_case_           =		[tf.ones((1, 3, 5, 5)       )]

														snake_case_           =		[[1_764, 2_646]]

														snake_case_           =		[[683, 1_024]]
														snake_case_           =		processor.post_process_masks(UpperCAmelCase_		,       UpperCAmelCase_		,       UpperCAmelCase_		,       return_tensors="""tf"""       )
														self.assertEqual(masks[0].shape		,       (1, 3, 1_764, 2_646)       )

														snake_case_           =		processor.post_process_masks(
														    UpperCAmelCase_		,       tf.convert_to_tensor(UpperCAmelCase_       )		,       tf.convert_to_tensor(UpperCAmelCase_       )		,       return_tensors="""tf"""		,       )
														self.assertEqual(masks[0].shape		,       (1, 3, 1_764, 2_646)       )

														# should also work with np
														snake_case_           =		[np.ones((1, 3, 5, 5)       )]
														snake_case_           =		processor.post_process_masks(
														    UpperCAmelCase_		,       np.array(UpperCAmelCase_       )		,       np.array(UpperCAmelCase_       )		,       return_tensors="""tf"""       )

														self.assertEqual(masks[0].shape		,       (1, 3, 1_764, 2_646)       )

														snake_case_           =		[[1, 0], [0, 1]]
														with self.assertRaises(tf.errors.InvalidArgumentError       ):
																					snake_case_           =		processor.post_process_masks(
																					    UpperCAmelCase_		,       np.array(UpperCAmelCase_       )		,       np.array(UpperCAmelCase_       )		,       return_tensors="""tf"""       )





@require_vision
@require_torchvision
class      __A     (unittest.TestCase):





							'''simple docstring'''

							def 		lowerCAmelCase       (				self							:      int       )					->Any:



														"""simple docstring"""



														snake_case_           =		tempfile.mkdtemp()
														snake_case_           =		SamImageProcessor()
														snake_case_           =		SamProcessor(UpperCAmelCase_       )
														processor.save_pretrained(self.tmpdirname       )



							def 		lowerCAmelCase       (				self							:      Dict		,       **UpperCAmelCase_							:      List[Any]       )					->str:



														"""simple docstring"""



														return AutoProcessor.from_pretrained(self.tmpdirname		,       **UpperCAmelCase_       ).image_processor



							def 		lowerCAmelCase       (				self							:      int       )					->Tuple:



														"""simple docstring"""



														shutil.rmtree(self.tmpdirname       )



							def 		lowerCAmelCase       (				self							:      int       )					->Dict:



														"""simple docstring"""



														snake_case_           =		[np.random.randint(255		,       size=(3, 30, 400)		,       dtype=np.uinta       )]

														snake_case_           =		[Image.fromarray(np.moveaxis(UpperCAmelCase_		,       0		,       -1       )       ) for x in image_inputs]

														return image_inputs



							@is_pt_tf_cross_test
							def 		lowerCAmelCase       (				self							:      str       )					->Optional[int]:



														"""simple docstring"""



														snake_case_           =		self.get_image_processor()

														snake_case_           =		SamProcessor(image_processor=UpperCAmelCase_       )
														snake_case_           =		np.random.randint(0		,       2		,       size=(1, 3, 5, 5)       ).astype(np.floataa       )
														snake_case_           =		[tf.convert_to_tensor(UpperCAmelCase_       )]
														snake_case_           =		[torch.tensor(UpperCAmelCase_       )]

														snake_case_           =		[[1_764, 2_646]]

														snake_case_           =		[[683, 1_024]]
														snake_case_           =		processor.post_process_masks(
														    UpperCAmelCase_		,       UpperCAmelCase_		,       UpperCAmelCase_		,       return_tensors="""tf"""       )
														snake_case_           =		processor.post_process_masks(
														    UpperCAmelCase_		,       UpperCAmelCase_		,       UpperCAmelCase_		,       return_tensors="""pt"""       )

														self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()       )       )



							@is_pt_tf_cross_test
							def 		lowerCAmelCase       (				self							:      Optional[Any]       )					->int:



														"""simple docstring"""



														snake_case_           =		self.get_image_processor()

														snake_case_           =		SamProcessor(image_processor=UpperCAmelCase_       )

														snake_case_           =		self.prepare_image_inputs()

														snake_case_           =		image_processor(UpperCAmelCase_		,       return_tensors="""pt"""       )["""pixel_values"""].numpy()
														snake_case_           =		processor(images=UpperCAmelCase_		,       return_tensors="""pt"""       )["""pixel_values"""].numpy()

														snake_case_           =		image_processor(UpperCAmelCase_		,       return_tensors="""tf"""       )["""pixel_values"""].numpy()
														snake_case_           =		processor(images=UpperCAmelCase_		,       return_tensors="""tf"""       )["""pixel_values"""].numpy()

														self.assertTrue(np.allclose(UpperCAmelCase_		,       UpperCAmelCase_       )       )
														self.assertTrue(np.allclose(UpperCAmelCase_		,       UpperCAmelCase_       )       )
														self.assertTrue(np.allclose(UpperCAmelCase_		,       UpperCAmelCase_       )       )







"""simple docstring"""
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      __A     (snake_case__						,		snake_case__						,		unittest.TestCase):





							'''simple docstring'''

							__lowercase:		str							      =    VQModel
							__lowercase:		Union[str, Any]							      =    """sample"""



							@property
							def 		lowerCAmelCase       (				self							:      List[str]		,       UpperCAmelCase_							:      List[str]=(32, 32)       )					->Tuple:



														"""simple docstring"""



														snake_case_           =		4
														snake_case_           =		3

														snake_case_           =		floats_tensor((batch_size, num_channels) + sizes       ).to(UpperCAmelCase_       )

														return {"sample": image}



							@property
							def 		lowerCAmelCase       (				self							:      Tuple       )					->str:



														"""simple docstring"""



														return (3, 32, 32)



							@property
							def 		lowerCAmelCase       (				self							:      List[Any]       )					->Any:



														"""simple docstring"""



														return (3, 32, 32)



							def 		lowerCAmelCase       (				self							:      Optional[int]       )					->Dict:



														"""simple docstring"""



														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,
														}
														snake_case_           =		self.dummy_input
														return init_dict, inputs_dict



							def 		lowerCAmelCase       (				self							:      List[str]       )					->Dict:



														"""simple docstring"""



														pass



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



														"""simple docstring"""



														pass



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



														"""simple docstring"""



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

														model.to(UpperCAmelCase_       )
														snake_case_           =		model(**self.dummy_input       )

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



							def 		lowerCAmelCase       (				self							:      Tuple       )					->Optional[Any]:



														"""simple docstring"""



														snake_case_           =		VQModel.from_pretrained("""fusing/vqgan-dummy"""       )
														model.to(UpperCAmelCase_       ).eval()

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

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

														snake_case_           =		output[0, -1, -3:, -3:].flatten().cpu()
														# fmt: off
														snake_case_           =		torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143]       )
														# fmt: on
														self.assertTrue(torch.allclose(UpperCAmelCase_		,       UpperCAmelCase_		,       atol=1E-3       )       )



