

import tempfile
import unittest

from diffusers import (
    DDIMScheduler,
    DDPMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    PNDMScheduler,
    logging,
)
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.utils.testing_utils import CaptureLogger

class  a     (		UpperCAmelCase ):
						_lowercase			  =	"config.json"


						@register_to_config
						def __init__(				self  ,    A_=2  ,    A_=5  ,    A_=(2, 5)  ,    A_="for diffusion"  ,    A_=[1, 3]  ,    ):







										'''simple docstring'''


										pass







class  a     (		UpperCAmelCase ):
						_lowercase			  =	"config.json"


						@register_to_config
						def __init__(				self  ,    A_=2  ,    A_=5  ,    A_=(2, 5)  ,    A_="for diffusion"  ,    A_=[1, 3]  ,    ):







										'''simple docstring'''


										pass







class  a     (		UpperCAmelCase ):
						_lowercase			  =	"config.json"


						@register_to_config
						def __init__(				self  ,    A_=2  ,    A_=5  ,    A_=(2, 5)  ,    A_="for diffusion"  ,    A_=[1, 3]  ,    A_=[1, 3]  ,    ):







										'''simple docstring'''


										pass







class  a     (		UpperCAmelCase ):
						_lowercase			  =	"config.json"


						@register_to_config
						def __init__(				self  ,    A_=2  ,    A_=5  ,    A_=(2, 5)  ,    A_="for diffusion"  ,    A_=[1, 5]  ,    A_=[5, 4]  ,    ):







										'''simple docstring'''


										pass







class  a     (		unittest.TestCase ):


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										with self.assertRaises(A_		):
														ConfigMixin.load_config("dummy_path"		)


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			SampleObject()
										_UpperCAmelCase				:						List[Any]       						=			obj.config
										assert config["a"] == 2
										assert config["b"] == 5
										assert config["c"] == (2, 5)
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]

										# init ignore private arguments
										_UpperCAmelCase				:						Optional[Any]       						=			SampleObject(_name_or_path="lalala"		)
										_UpperCAmelCase				:						List[str]       						=			obj.config
										assert config["a"] == 2
										assert config["b"] == 5
										assert config["c"] == (2, 5)
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]

										# can override default
										_UpperCAmelCase				:						str       						=			SampleObject(c=6		)
										_UpperCAmelCase				:						Tuple       						=			obj.config
										assert config["a"] == 2
										assert config["b"] == 5
										assert config["c"] == 6
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]

										# can use positional arguments.
										_UpperCAmelCase				:						int       						=			SampleObject(1  ,    c=6		)
										_UpperCAmelCase				:						List[Any]       						=			obj.config
										assert config["a"] == 1
										assert config["b"] == 5
										assert config["c"] == 6
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						int       						=			SampleObject()
										_UpperCAmelCase				:						Dict       						=			obj.config

										assert config["a"] == 2
										assert config["b"] == 5
										assert config["c"] == (2, 5)
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]

										with tempfile.TemporaryDirectory() as tmpdirname:
														obj.save_config(A_		)
														_UpperCAmelCase				:						List[Any]       						=			SampleObject.from_config(SampleObject.load_config(A_		)		)
														_UpperCAmelCase				:						Tuple       						=			new_obj.config

										# unfreeze configs
										_UpperCAmelCase				:						Optional[Any]       						=			dict(A_		)
										_UpperCAmelCase				:						str       						=			dict(A_		)

										assert config.pop("c"		) == (2, 5)  # instantiated as tuple
										assert new_config.pop("c"		) == [2, 5]  # saved & loaded as list because of json
										config.pop("_use_default_values"		)
										assert config == new_config


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Union[str, Any]       						=			logging.get_logger("diffusers.configuration_utils"		)
										# 30 for warning
										logger.setLevel(30		)

										with CaptureLogger(A_		) as cap_logger:
														_UpperCAmelCase				:						int       						=			DDIMScheduler.from_pretrained(
														    "hf-internal-testing/tiny-stable-diffusion-torch"  ,    subfolder="scheduler"		)

										assert ddim.__class__ == DDIMScheduler
										# no warning should be thrown
										assert cap_logger.out == ""


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			logging.get_logger("diffusers.configuration_utils"		)
										# 30 for warning
										logger.setLevel(30		)

										with CaptureLogger(A_		) as cap_logger:
														_UpperCAmelCase				:						Any       						=			EulerDiscreteScheduler.from_pretrained(
														    "hf-internal-testing/tiny-stable-diffusion-torch"  ,    subfolder="scheduler"		)

										assert euler.__class__ == EulerDiscreteScheduler
										# no warning should be thrown
										assert cap_logger.out == ""


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						List[str]       						=			logging.get_logger("diffusers.configuration_utils"		)
										# 30 for warning
										logger.setLevel(30		)

										with CaptureLogger(A_		) as cap_logger:
														_UpperCAmelCase				:						Tuple       						=			EulerAncestralDiscreteScheduler.from_pretrained(
														    "hf-internal-testing/tiny-stable-diffusion-torch"  ,    subfolder="scheduler"		)

										assert euler.__class__ == EulerAncestralDiscreteScheduler
										# no warning should be thrown
										assert cap_logger.out == ""


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Optional[Any]       						=			logging.get_logger("diffusers.configuration_utils"		)
										# 30 for warning
										logger.setLevel(30		)

										with CaptureLogger(A_		) as cap_logger:
														_UpperCAmelCase				:						Union[str, Any]       						=			PNDMScheduler.from_pretrained(
														    "hf-internal-testing/tiny-stable-diffusion-torch"  ,    subfolder="scheduler"		)

										assert pndm.__class__ == PNDMScheduler
										# no warning should be thrown
										assert cap_logger.out == ""


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Union[str, Any]       						=			logging.get_logger("diffusers.configuration_utils"		)
										# 30 for warning
										logger.setLevel(30		)

										with CaptureLogger(A_		) as cap_logger:
														_UpperCAmelCase				:						List[Any]       						=			DDPMScheduler.from_pretrained(
														    "hf-internal-testing/tiny-stable-diffusion-torch"  ,    subfolder="scheduler"  ,    prediction_type="sample"  ,    beta_end=8  ,    )

										with CaptureLogger(A_		) as cap_logger_a:
														_UpperCAmelCase				:						Optional[int]       						=			DDPMScheduler.from_pretrained("google/ddpm-celebahq-256"  ,    beta_start=88		)

										assert ddpm.__class__ == DDPMScheduler
										assert ddpm.config.prediction_type == "sample"
										assert ddpm.config.beta_end == 8
										assert ddpm_a.config.beta_start == 88

										# no warning should be thrown
										assert cap_logger.out == ""
										assert cap_logger_a.out == ""


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Union[str, Any]       						=			logging.get_logger("diffusers.configuration_utils"		)
										# 30 for warning
										logger.setLevel(30		)

										with CaptureLogger(A_		) as cap_logger:
														_UpperCAmelCase				:						List[str]       						=			DPMSolverMultistepScheduler.from_pretrained(
														    "hf-internal-testing/tiny-stable-diffusion-torch"  ,    subfolder="scheduler"		)

										assert dpm.__class__ == DPMSolverMultistepScheduler
										# no warning should be thrown
										assert cap_logger.out == ""





						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						int       						=			SampleObject()

										_UpperCAmelCase				:						Union[str, Any]       						=			{k: v for k, v in config.config.items() if not k.startswith("_"		)}

										# make sure that default config has all keys in `_use_default_values`
										assert set(config_dict.keys()		) == set(config.config._use_default_values		)

										with tempfile.TemporaryDirectory() as tmpdirname:
														config.save_config(A_		)

														# now loading it with SampleObject2 should put f into `_use_default_values`
														_UpperCAmelCase				:						Union[str, Any]       						=			SampleObjecta.from_config(A_		)

														assert "f" in config._use_default_values
														assert config.f == [1, 3]

										# now loading the config, should **NOT** use [1, 3] for `f`, but the default [1, 4] value
										# **BECAUSE** it is part of `config._use_default_values`
										_UpperCAmelCase				:						Tuple       						=			SampleObjecta.from_config(config.config		)
										assert new_config.f == [5, 4]

										config.config._use_default_values.pop()
										_UpperCAmelCase				:						Optional[Any]       						=			SampleObjecta.from_config(config.config		)
										assert new_config_a.f == [1, 3]

										# Nevertheless "e" should still be correctly loaded to [1, 3] from SampleObject2 instead of defaulting to [1, 5]
										assert new_config_a.e == [1, 3]







"""simple docstring"""
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


if is_torch_available():
			import torch

if is_vision_available():
			from PIL import Image

			from transformers import BlipImageProcessor


class 							lowerCamelCase_(      unittest.TestCase			):





					'''simple docstring'''



					def __init__(			self ,				lowerCamelCase__ ,				lowerCamelCase__=7 ,				lowerCamelCase__=3 ,				lowerCamelCase__=1_8 ,				lowerCamelCase__=3_0 ,				lowerCamelCase__=4_0_0 ,				lowerCamelCase__=True ,				lowerCamelCase__=None ,				lowerCamelCase__=True ,				lowerCamelCase__=False ,				lowerCamelCase__=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] ,				lowerCamelCase__=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] ,				lowerCamelCase__=True ,				):
									_lowerCamelCase					     = size if size is not None else {'''height''': 2_0, '''width''': 2_0}
									_lowerCamelCase					     = parent
									_lowerCamelCase					     = batch_size
									_lowerCamelCase					     = num_channels
									_lowerCamelCase					     = image_size
									_lowerCamelCase					     = min_resolution
									_lowerCamelCase					     = max_resolution
									_lowerCamelCase					     = do_resize
									_lowerCamelCase					     = size
									_lowerCamelCase					     = do_normalize
									_lowerCamelCase					     = image_mean
									_lowerCamelCase					     = image_std
									_lowerCamelCase					     = do_pad
									_lowerCamelCase					     = do_convert_rgb

					def 	snake_case__					(			self      ):
									return {
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "do_normalize": self.do_normalize,
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_convert_rgb": self.do_convert_rgb,
									    "do_pad": self.do_pad,
									}





					def 	snake_case__					(			self ,				lowerCamelCase__=False ,				lowerCamelCase__=False ,				lowerCamelCase__=False      ):
									assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

									if equal_resolution:
													_lowerCamelCase					     = []
													for i in range(self.batch_size      ):
																	image_inputs.append(
																	    np.random.randint(
																	        2_5_5 ,				size=(self.num_channels, self.max_resolution, self.max_resolution) ,				dtype=np.uinta      )      )
									else:
													_lowerCamelCase					     = []
													for i in range(self.batch_size      ):
																	_lowerCamelCase     ,   _lowerCamelCase					     = np.random.choice(np.arange(self.min_resolution ,				self.max_resolution      ) ,				2      )
																	image_inputs.append(np.random.randint(2_5_5 ,				size=(self.num_channels, width, height) ,				dtype=np.uinta      )      )

									if not numpify and not torchify:
													# PIL expects the channel dimension as last dimension
													_lowerCamelCase					     = [Image.fromarray(np.moveaxis(lowerCamelCase__ ,				0 ,				-1      )      ) for x in image_inputs]

									if torchify:
													_lowerCamelCase					     = [torch.from_numpy(lowerCamelCase__      ) for x in image_inputs]

									return image_inputs


@require_torch
@require_vision
class 							lowerCamelCase_(      A__, unittest.TestCase			):





					'''simple docstring'''



					lowercase__      :				Any        =       BlipImageProcessor if is_vision_available() else None

					def 	snake_case__					(			self      ):
									_lowerCamelCase					     = BlipImageProcessingTester(self      )

					@property
					def 	snake_case__					(			self      ):
									return self.image_processor_tester.prepare_image_processor_dict()

					def 	snake_case__					(			self      ):
									_lowerCamelCase					     = self.image_processing_class(**self.image_processor_dict      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''do_resize'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''size'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''do_normalize'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''image_mean'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''image_std'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''do_convert_rgb'''      )      )

					def 	snake_case__					(			self      ):
									pass

					def 	snake_case__					(			self      ):
									# Initialize image_processor
									_lowerCamelCase					     = self.image_processing_class(**self.image_processor_dict      )
									# create random PIL images
									_lowerCamelCase					     = self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__      )
									for image in image_inputs:
													self.assertIsInstance(lowerCamelCase__ ,				Image.Image      )

									# Test not batched input
									_lowerCamelCase					     = image_processor(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
									_lowerCamelCase					     = image_processor(lowerCamelCase__ ,				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 	snake_case__					(			self      ):
									# Initialize image_processor
									_lowerCamelCase					     = self.image_processing_class(**self.image_processor_dict      )
									# create random numpy tensors
									_lowerCamelCase					     = self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__ ,				numpify=lowerCamelCase__      )
									for image in image_inputs:
													self.assertIsInstance(lowerCamelCase__ ,				np.ndarray      )

									# Test not batched input
									_lowerCamelCase					     = image_processor(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
									_lowerCamelCase					     = image_processor(lowerCamelCase__ ,				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 	snake_case__					(			self      ):
									# Initialize image_processor
									_lowerCamelCase					     = self.image_processing_class(**self.image_processor_dict      )
									# create random PyTorch tensors
									_lowerCamelCase					     = self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__ ,				torchify=lowerCamelCase__      )
									for image in image_inputs:
													self.assertIsInstance(lowerCamelCase__ ,				torch.Tensor      )

									# Test not batched input
									_lowerCamelCase					     = image_processor(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
									_lowerCamelCase					     = image_processor(lowerCamelCase__ ,				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'''],
									    ) ,				)


@require_torch
@require_vision
class 							lowerCamelCase_(      A__, unittest.TestCase			):





					'''simple docstring'''



					lowercase__      :				Tuple        =       BlipImageProcessor if is_vision_available() else None

					def 	snake_case__					(			self      ):
									_lowerCamelCase					     = BlipImageProcessingTester(self ,				num_channels=4      )
									_lowerCamelCase					     = 3

					@property
					def 	snake_case__					(			self      ):
									return self.image_processor_tester.prepare_image_processor_dict()

					def 	snake_case__					(			self      ):
									_lowerCamelCase					     = self.image_processing_class(**self.image_processor_dict      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''do_resize'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''size'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''do_normalize'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''image_mean'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''image_std'''      )      )
									self.assertTrue(hasattr(lowerCamelCase__ ,				'''do_convert_rgb'''      )      )

					def 	snake_case__					(			self      ):
									pass





					def 	snake_case__					(			self      ):
									# Initialize image_processor
									_lowerCamelCase					     = self.image_processing_class(**self.image_processor_dict      )
									# create random PIL images
									_lowerCamelCase					     = self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__      )
									for image in image_inputs:
													self.assertIsInstance(lowerCamelCase__ ,				Image.Image      )

									# Test not batched input
									_lowerCamelCase					     = image_processor(image_inputs[0] ,				return_tensors='''pt'''      ).pixel_values
									self.assertEqual(
									    encoded_images.shape ,				(
									        1,
									        self.expected_encoded_image_num_channels,
									        self.image_processor_tester.size['''height'''],
									        self.image_processor_tester.size['''width'''],
									    ) ,				)

									# Test batched
									_lowerCamelCase					     = image_processor(lowerCamelCase__ ,				return_tensors='''pt'''      ).pixel_values
									self.assertEqual(
									    encoded_images.shape ,				(
									        self.image_processor_tester.batch_size,
									        self.expected_encoded_image_num_channels,
									        self.image_processor_tester.size['''height'''],
									        self.image_processor_tester.size['''width'''],
									    ) ,				)
