



'''simple docstring'''






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 				lowercase			(    _lowerCamelCase							):


 """simple docstring"""


 UpperCAmelCase		      =    """config.json"""







 @register_to_config
 def __init__(				self    ,a_=2    ,a_=5    ,a_=(2, 5)    ,a_="for diffusion"    ,a_=[1, 3]    ,)						->  Tuple:
        pass







class 				lowercase			(    _lowerCamelCase							):


 """simple docstring"""


 UpperCAmelCase		      =    """config.json"""







 @register_to_config
 def __init__(				self    ,a_=2    ,a_=5    ,a_=(2, 5)    ,a_="for diffusion"    ,a_=[1, 3]    ,)						->  Tuple:
        pass







class 				lowercase			(    _lowerCamelCase							):


 """simple docstring"""


 UpperCAmelCase		      =    """config.json"""







 @register_to_config
 def __init__(				self    ,a_=2    ,a_=5    ,a_=(2, 5)    ,a_="for diffusion"    ,a_=[1, 3]    ,a_=[1, 3]    ,)						->  Union[str, Any]:
        pass







class 				lowercase			(    _lowerCamelCase							):


 """simple docstring"""


 UpperCAmelCase		      =    """config.json"""







 @register_to_config
 def __init__(				self    ,a_=2    ,a_=5    ,a_=(2, 5)    ,a_="for diffusion"    ,a_=[1, 5]    ,a_=[5, 4]    ,)						->  Tuple:
        pass







class 				lowercase			(    unittest.TestCase							):


 """simple docstring"""


 def _snake_case					(				self				)						->  Optional[int]:
        with self.assertRaises(a_				):
               ConfigMixin.load_config("""dummy_path"""				)







 def _snake_case					(				self				)						->  Union[str, Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					SampleObject()
        _UpperCAmelCase    :		Union[str, 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    :		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]

        # can override default
        _UpperCAmelCase    :		str     	=					SampleObject(c=6				)
        _UpperCAmelCase    :		Dict     	=					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    :		List[str]     	=					SampleObject(1    ,c=6				)
        _UpperCAmelCase    :		Tuple     	=					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 _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Any     	=					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    :		Optional[int]     	=					SampleObject.from_config(SampleObject.load_config(a_				)				)
               _UpperCAmelCase    :		str     	=					new_obj.config

        # unfreeze configs
        _UpperCAmelCase    :		str     	=					dict(a_				)
        _UpperCAmelCase    :		Any     	=					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 _snake_case					(				self				)						->  List[str]:
        _UpperCAmelCase    :		List[str]     	=					logging.get_logger("""diffusers.configuration_utils"""				)
        # 30 for warning
        logger.setLevel(30				)

        with CaptureLogger(a_				) as cap_logger:
               _UpperCAmelCase    :		Dict     	=					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 _snake_case					(				self				)						->  List[str]:
        _UpperCAmelCase    :		Tuple     	=					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 _snake_case					(				self				)						->  Tuple:
        _UpperCAmelCase    :		List[Any]     	=					logging.get_logger("""diffusers.configuration_utils"""				)
        # 30 for warning
        logger.setLevel(30				)

        with CaptureLogger(a_				) as cap_logger:
               _UpperCAmelCase    :		Optional[Any]     	=					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 _snake_case					(				self				)						->  Optional[int]:
        _UpperCAmelCase    :		Dict     	=					logging.get_logger("""diffusers.configuration_utils"""				)
        # 30 for warning
        logger.setLevel(30				)

        with CaptureLogger(a_				) as cap_logger:
               _UpperCAmelCase    :		List[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 _snake_case					(				self				)						->  Optional[int]:
        _UpperCAmelCase    :		Tuple     	=					logging.get_logger("""diffusers.configuration_utils"""				)
        # 30 for warning
        logger.setLevel(30				)

        with CaptureLogger(a_				) as cap_logger:
               _UpperCAmelCase    :		List[str]     	=					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    :		Any     	=					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 _snake_case					(				self				)						->  List[str]:
        _UpperCAmelCase    :		str     	=					logging.get_logger("""diffusers.configuration_utils"""				)
        # 30 for warning
        logger.setLevel(30				)

        with CaptureLogger(a_				) as cap_logger:
               _UpperCAmelCase    :		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 _snake_case					(				self				)						->  Optional[int]:
        # let's first save a config that should be in the form
        #    a=2,
        #    b=5,
        #    c=(2, 5),
        #    d="for diffusion",
        #    e=[1, 3],

        _UpperCAmelCase    :		Dict     	=					SampleObject()

        _UpperCAmelCase    :		Tuple     	=					{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    :		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    :		List[Any]     	=					SampleObjecta.from_config(config.config				)
        assert new_config.f == [5, 4]

        config.config._use_default_values.pop()
        _UpperCAmelCase    :		Union[str, 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 				lowercase			(    unittest.TestCase							):


 """simple docstring"""


 def __init__(				self    ,a_    ,a_=7    ,a_=3    ,a_=18    ,a_=30    ,a_=400    ,a_=True    ,a_=None    ,a_=True    ,a_=False    ,a_=[0.4814_5466, 0.457_8275, 0.4082_1073]    ,a_=[0.2686_2954, 0.2613_0258, 0.2757_7711]    ,a_=True    ,)						->  Optional[int]:
        _UpperCAmelCase    :		Dict     	=					size if size is not None else {"""height""": 20, """width""": 20}
        _UpperCAmelCase    :		Dict     	=					parent
        _UpperCAmelCase    :		Tuple     	=					batch_size
        _UpperCAmelCase    :		Optional[int]     	=					num_channels
        _UpperCAmelCase    :		int     	=					image_size
        _UpperCAmelCase    :		List[Any]     	=					min_resolution
        _UpperCAmelCase    :		str     	=					max_resolution
        _UpperCAmelCase    :		Tuple     	=					do_resize
        _UpperCAmelCase    :		Union[str, Any]     	=					size
        _UpperCAmelCase    :		int     	=					do_normalize
        _UpperCAmelCase    :		List[str]     	=					image_mean
        _UpperCAmelCase    :		Any     	=					image_std
        _UpperCAmelCase    :		Union[str, Any]     	=					do_pad
        _UpperCAmelCase    :		Tuple     	=					do_convert_rgb







 def _snake_case					(				self				)						->  List[str]:
        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    ,a_=False    ,a_=False    ,a_=False				)						->  Dict:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
               _UpperCAmelCase    :		Union[str, Any]     	=					[]
               for i in range(self.batch_size				):
                      image_inputs.append(
                          np.random.randint(
                              255    ,size=(self.num_channels, self.max_resolution, self.max_resolution)    ,dtype=np.uinta				)				)
        else:
               _UpperCAmelCase    :		Optional[int]     	=					[]
               for i in range(self.batch_size				):
                      _UpperCAmelCase	,_UpperCAmelCase    :		int     	=					np.random.choice(np.arange(self.min_resolution    ,self.max_resolution				)    ,2				)
                      image_inputs.append(np.random.randint(255    ,size=(self.num_channels, width, height)    ,dtype=np.uinta				)				)

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

        if torchify:
               _UpperCAmelCase    :		Optional[int]     	=					[torch.from_numpy(a_				) for x in image_inputs]

        return image_inputs







@require_torch
@require_vision
class 				lowercase			(    _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    BlipImageProcessor if is_vision_available() else None







 def _snake_case					(				self				)						->  List[Any]:
        _UpperCAmelCase    :		Dict     	=					BlipImageProcessingTester(self				)







 @property
 def _snake_case					(				self				)						->  str:
        return self.image_processor_tester.prepare_image_processor_dict()







 def _snake_case					(				self				)						->  Tuple:
        _UpperCAmelCase    :		List[str]     	=					self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(a_    ,"""do_resize"""				)				)
        self.assertTrue(hasattr(a_    ,"""size"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_normalize"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_mean"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_std"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_convert_rgb"""				)				)







 def _snake_case					(				self				)						->  Any:
        pass







 def _snake_case					(				self				)						->  Union[str, Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		List[str]     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        _UpperCAmelCase    :		str     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,Image.Image				)

        # Test not batched input
        _UpperCAmelCase    :		List[str]     	=					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
        _UpperCAmelCase    :		List[str]     	=					image_processor(a_    ,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				)						->  Optional[Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		str     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random numpy tensors
        _UpperCAmelCase    :		str     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_    ,numpify=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,np.ndarray				)

        # Test not batched input
        _UpperCAmelCase    :		Dict     	=					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
        _UpperCAmelCase    :		int     	=					image_processor(a_    ,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				)						->  List[str]:
        # Initialize image_processor
        _UpperCAmelCase    :		Dict     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PyTorch tensors
        _UpperCAmelCase    :		Union[str, Any]     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_    ,torchify=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,torch.Tensor				)

        # Test not batched input
        _UpperCAmelCase    :		str     	=					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
        _UpperCAmelCase    :		Optional[Any]     	=					image_processor(a_    ,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 				lowercase			(    _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    BlipImageProcessor if is_vision_available() else None







 def _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					BlipImageProcessingTester(self    ,num_channels=4				)
        _UpperCAmelCase    :		List[Any]     	=					3







 @property
 def _snake_case					(				self				)						->  int:
        return self.image_processor_tester.prepare_image_processor_dict()







 def _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(a_    ,"""do_resize"""				)				)
        self.assertTrue(hasattr(a_    ,"""size"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_normalize"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_mean"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_std"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_convert_rgb"""				)				)







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







 def _snake_case					(				self				)						->  List[Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		Any     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        _UpperCAmelCase    :		Optional[Any]     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,Image.Image				)

        # Test not batched input
        _UpperCAmelCase    :		List[Any]     	=					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
        _UpperCAmelCase    :		Dict     	=					image_processor(a_    ,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"""],
            )    ,)



