'''simple docstring'''





from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


SCREAMING_SNAKE_CASE_:					Any  =logging.get_logger(__name__)


if is_vision_available():
    import PIL




class 	__A				(			UpperCamelCase__     ):
    a__	:						List[str]	       =  ["""pixel_values"""]



    def __init__(self   :   str       ,      __a   :   bool = True       ,      __a   :   Dict[str, int] = None       ,      __a   :   PILImageResampling = PILImageResampling.BICUBIC       ,      __a   :   bool = True       ,      __a   :   Dict[str, int] = None       ,      __a   :   bool = True       ,      __a   :   Union[int, float] = 1 / 255       ,      __a   :   bool = True       ,      __a   :   Optional[Union[float, List[float]]] = None       ,      __a   :   Optional[Union[float, List[float]]] = None       ,      __a   :   bool = True       ,      **__a   :   Tuple       ,      ):
         super().__init__(**__a			)
         UpperCAmelCase_	   =       size if size is not None else {"shortest_edge": 224}
         UpperCAmelCase_	   =       get_size_dict(__a       ,      default_to_square=__a			)
         UpperCAmelCase_	   =       crop_size if crop_size is not None else {"height": 224, "width": 224}
         UpperCAmelCase_	   =       get_size_dict(__a       ,      default_to_square=__a       ,      param_name="crop_size"			)

         UpperCAmelCase_	   =       do_resize
         UpperCAmelCase_	   =       size
         UpperCAmelCase_	   =       resample
         UpperCAmelCase_	   =       do_center_crop
         UpperCAmelCase_	   =       crop_size
         UpperCAmelCase_	   =       do_rescale
         UpperCAmelCase_	   =       rescale_factor
         UpperCAmelCase_	   =       do_normalize
         UpperCAmelCase_	   =       image_mean if image_mean is not None else OPENAI_CLIP_MEAN
         UpperCAmelCase_	   =       image_std if image_std is not None else OPENAI_CLIP_STD
         UpperCAmelCase_	   =       do_convert_rgb



    def  _lowercase						(self   :   Dict       ,      __a   :   np.ndarray       ,      __a   :   Dict[str, int]       ,      __a   :   PILImageResampling = PILImageResampling.BICUBIC       ,      __a   :   Optional[Union[str, ChannelDimension]] = None       ,      **__a   :   Tuple       ,      ):
         UpperCAmelCase_	   =       get_size_dict(__a       ,      default_to_square=__a			)
         if "shortest_edge" not in size:
              raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""			)
         UpperCAmelCase_	   =       get_resize_output_image_size(__a       ,      size=size["shortest_edge"]       ,      default_to_square=__a			)
         return resize(__a       ,      size=__a       ,      resample=__a       ,      data_format=__a       ,      **__a			)



    def  _lowercase						(self   :   Any       ,      __a   :   np.ndarray       ,      __a   :   Dict[str, int]       ,      __a   :   Optional[Union[str, ChannelDimension]] = None       ,      **__a   :   Optional[Any]       ,      ):
         UpperCAmelCase_	   =       get_size_dict(__a			)
         if "height" not in size or "width" not in size:
              raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}"""			)
         return center_crop(__a       ,      size=(size["height"], size["width"])       ,      data_format=__a       ,      **__a			)



    def  _lowercase						(self   :   Dict       ,      __a   :   np.ndarray       ,      __a   :   Union[int, float]       ,      __a   :   Optional[Union[str, ChannelDimension]] = None       ,      **__a   :   int       ,      ):
         return rescale(__a       ,      scale=__a       ,      data_format=__a       ,      **__a			)



    def  _lowercase						(self   :   int       ,      __a   :   np.ndarray       ,      __a   :   Union[float, List[float]]       ,      __a   :   Union[float, List[float]]       ,      __a   :   Optional[Union[str, ChannelDimension]] = None       ,      **__a   :   Tuple       ,      ):
         return normalize(__a       ,      mean=__a       ,      std=__a       ,      data_format=__a       ,      **__a			)






    def  _lowercase						(self   :   int       ,      __a   :   ImageInput       ,      __a   :   bool = None       ,      __a   :   Dict[str, int] = None       ,      __a   :   PILImageResampling = None       ,      __a   :   bool = None       ,      __a   :   int = None       ,      __a   :   bool = None       ,      __a   :   float = None       ,      __a   :   bool = None       ,      __a   :   Optional[Union[float, List[float]]] = None       ,      __a   :   Optional[Union[float, List[float]]] = None       ,      __a   :   bool = None       ,      __a   :   Optional[Union[str, TensorType]] = None       ,      __a   :   Optional[ChannelDimension] = ChannelDimension.FIRST       ,      **__a   :   int       ,      ):
         UpperCAmelCase_	   =       do_resize if do_resize is not None else self.do_resize
         UpperCAmelCase_	   =       size if size is not None else self.size
         UpperCAmelCase_	   =       get_size_dict(__a       ,      param_name="size"       ,      default_to_square=__a			)
         UpperCAmelCase_	   =       resample if resample is not None else self.resample
         UpperCAmelCase_	   =       do_center_crop if do_center_crop is not None else self.do_center_crop
         UpperCAmelCase_	   =       crop_size if crop_size is not None else self.crop_size
         UpperCAmelCase_	   =       get_size_dict(__a       ,      param_name="crop_size"       ,      default_to_square=__a			)
         UpperCAmelCase_	   =       do_rescale if do_rescale is not None else self.do_rescale
         UpperCAmelCase_	   =       rescale_factor if rescale_factor is not None else self.rescale_factor
         UpperCAmelCase_	   =       do_normalize if do_normalize is not None else self.do_normalize
         UpperCAmelCase_	   =       image_mean if image_mean is not None else self.image_mean
         UpperCAmelCase_	   =       image_std if image_std is not None else self.image_std
         UpperCAmelCase_	   =       do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

         UpperCAmelCase_	   =       make_list_of_images(__a			)

         if not valid_images(__a			):
              raise ValueError(
                  "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
                  "torch.Tensor, tf.Tensor or jax.ndarray."			)

         if do_resize and size is None:
              raise ValueError("Size must be specified if do_resize is True."			)

         if do_center_crop and crop_size is None:
              raise ValueError("Crop size must be specified if do_center_crop is True."			)

         if do_rescale and rescale_factor is None:
              raise ValueError("Rescale factor must be specified if do_rescale is True."			)

         if do_normalize and (image_mean is None or image_std is None):
              raise ValueError("Image mean and std must be specified if do_normalize is True."			)

         # PIL RGBA images are converted to RGB
         if do_convert_rgb:
              UpperCAmelCase_	   =       [convert_to_rgb(__a			) for image in images]

         # All transformations expect numpy arrays.
         UpperCAmelCase_	   =       [to_numpy_array(__a			) for image in images]

         if do_resize:
              UpperCAmelCase_	   =       [self.resize(image=__a       ,      size=__a       ,      resample=__a			) for image in images]

         if do_center_crop:
              UpperCAmelCase_	   =       [self.center_crop(image=__a       ,      size=__a			) for image in images]

         if do_rescale:
              UpperCAmelCase_	   =       [self.rescale(image=__a       ,      scale=__a			) for image in images]

         if do_normalize:
              UpperCAmelCase_	   =       [self.normalize(image=__a       ,      mean=__a       ,      std=__a			) for image in images]

         UpperCAmelCase_	   =       [to_channel_dimension_format(__a       ,      __a			) for image in images]

         UpperCAmelCase_	   =       {"pixel_values": images}
         return BatchFeature(data=__a       ,      tensor_type=__a			)





'''simple docstring'''





import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch




@require_torch
class 	__A				:



    @property
    def  _lowercase						(self   :   int			):
         return self.get_dummy_input()



    @property
    def  _lowercase						(self   :   Any			):
         if self.block_type == "down":
              return (4, 32, 16, 16)
         elif self.block_type == "mid":
              return (4, 32, 32, 32)
         elif self.block_type == "up":
              return (4, 32, 64, 64)

         raise ValueError(f"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'."""			)



    def  _lowercase						(self   :   Tuple       ,      __a   :   List[str]=True       ,      __a   :   Any=False       ,      __a   :   List[Any]=False       ,      __a   :   Any=False       ,      ):
         UpperCAmelCase_	   =       4
         UpperCAmelCase_	   =       32
         UpperCAmelCase_	   =       (32, 32)

         UpperCAmelCase_	   =       torch.manual_seed(0			)
         UpperCAmelCase_	   =       torch.device(__a			)
         UpperCAmelCase_	   =       (batch_size, num_channels) + sizes
         UpperCAmelCase_	   =       randn_tensor(__a       ,      generator=__a       ,      device=__a			)
         UpperCAmelCase_	   =       {"hidden_states": hidden_states}

         if include_temb:
              UpperCAmelCase_	   =       128
              UpperCAmelCase_	   =       randn_tensor((batch_size, temb_channels)       ,      generator=__a       ,      device=__a			)

         if include_res_hidden_states_tuple:
              UpperCAmelCase_	   =       torch.manual_seed(1			)
              UpperCAmelCase_	   =       (randn_tensor(__a       ,      generator=__a       ,      device=__a			),)

         if include_encoder_hidden_states:
              UpperCAmelCase_	   =       floats_tensor((batch_size, 32, 32)			).to(__a			)

         if include_skip_sample:
              UpperCAmelCase_	   =       randn_tensor(((batch_size, 3) + sizes)       ,      generator=__a       ,      device=__a			)

         return dummy_input



    def  _lowercase						(self   :   Tuple			):
         UpperCAmelCase_	   =       {
             "in_channels": 32,
             "out_channels": 32,
             "temb_channels": 128,
         }
         if self.block_type == "up":
              UpperCAmelCase_	   =       32

         if self.block_type == "mid":
              init_dict.pop("out_channels"			)

         UpperCAmelCase_	   =       self.dummy_input
         return init_dict, inputs_dict



    def  _lowercase						(self   :   Tuple       ,      __a   :   Any			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.prepare_init_args_and_inputs_for_common()
         UpperCAmelCase_	   =       self.block_class(**__a			)
         unet_block.to(__a			)
         unet_block.eval()

         with torch.no_grad():
              UpperCAmelCase_	   =       unet_block(**__a			)

         if isinstance(__a       ,      __a			):
              UpperCAmelCase_	   =       output[0]

         self.assertEqual(output.shape       ,      self.output_shape			)

         UpperCAmelCase_	   =       output[0, -1, -3:, -3:]
         UpperCAmelCase_	   =       torch.tensor(__a			).to(__a			)
         assert torch_all_close(output_slice.flatten()       ,      __a       ,      atol=5E-3			)






    @unittest.skipIf(torch_device == "mps"       ,      "Training is not supported in mps"			)
    def  _lowercase						(self   :   Dict			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.prepare_init_args_and_inputs_for_common()
         UpperCAmelCase_	   =       self.block_class(**__a			)
         model.to(__a			)
         model.train()
         UpperCAmelCase_	   =       model(**__a			)

         if isinstance(__a       ,      __a			):
              UpperCAmelCase_	   =       output[0]

         UpperCAmelCase_	   =       torch.device(__a			)
         UpperCAmelCase_	   =       randn_tensor(output.shape       ,      device=__a			)
         UpperCAmelCase_	   =       torch.nn.functional.mse_loss(__a       ,      __a			)
         loss.backward()




