import gc
import unittest

from parameterized import parameterized

from diffusers import FlaxUNetaDConditionModel
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow


if is_flax_available():
    import jax
    import jax.numpy as jnp
@slow
@require_flax
class     a_			(						unittest.TestCase						):






 '''simple docstring'''






 def 		__snake_case						(      self :  List[str]      ,   lowercase__ :  int      ,   lowercase__ :  Tuple):







        '''simple docstring'''



        return F"""gaussian_noise_s={seed}_shape={'_'.join([str(lowercase__) for s in shape])}.npy"""




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        super().tearDown()
        gc.collect()




 def 		__snake_case						(      self :  int      ,   lowercase__ :  str=0      ,   lowercase__ :  List[str]=(4, 4, 64, 64)      ,   lowercase__ :  List[Any]=False):







        '''simple docstring'''



        lowerCAmelCase__					     = jnp.bfloataa if fpaa else jnp.floataa
        lowerCAmelCase__					     = jnp.array(load_hf_numpy(self.get_file_format(lowercase__      ,   lowercase__))      ,   dtype=lowercase__)
        return image




 def 		__snake_case						(      self :  Any      ,   lowercase__ :  Optional[Any]=False      ,   lowercase__ :  Dict="CompVis/stable-diffusion-v1-4"):







        '''simple docstring'''



        lowerCAmelCase__					     = jnp.bfloataa if fpaa else jnp.floataa
        lowerCAmelCase__					     = 'bf16' if fpaa else None

        lowerCAmelCase__     , lowerCAmelCase__					     = FlaxUNetaDConditionModel.from_pretrained(
            lowercase__      ,   subfolder='unet'      ,   dtype=lowercase__      ,   revision=lowercase__)
        return model, params




 def 		__snake_case						(      self :  str      ,   lowercase__ :  Optional[int]=0      ,   lowercase__ :  Any=(4, 77, 768)      ,   lowercase__ :  Optional[int]=False):







        '''simple docstring'''



        lowerCAmelCase__					     = jnp.bfloataa if fpaa else jnp.floataa
        lowerCAmelCase__					     = jnp.array(load_hf_numpy(self.get_file_format(lowercase__      ,   lowercase__))      ,   dtype=lowercase__)
        return hidden_states




 @parameterized.expand(
     [
         # fmt: off
         [83, 4, [-0.2_323, -0.1_304, 0.0_813, -0.3_093, -0.0_919, -0.1_571, -0.1_125, -0.5_806]],
         [17, 0.55, [-0.0_831, -0.2_443, 0.0_901, -0.0_919, 0.3_396, 0.0_103, -0.3_743, 0.0_701]],
         [8, 0.89, [-0.4_863, 0.0_859, 0.0_875, -0.1_658, 0.9_199, -0.0_114, 0.4_839, 0.4_639]],
         [3, 1_000, [-0.5_649, 0.2_402, -0.5_518, 0.1_248, 1.1_328, -0.2_443, -0.0_325, -1.0_078]],
         # fmt: on
     ])
 def 		__snake_case						(      self :  Tuple      ,   lowercase__ :  str      ,   lowercase__ :  Any      ,   lowercase__ :  Any):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.get_unet_model(model_id='CompVis/stable-diffusion-v1-4'      ,   fpaa=lowercase__)
        lowerCAmelCase__					     = self.get_latents(lowercase__      ,   fpaa=lowercase__)
        lowerCAmelCase__					     = self.get_encoder_hidden_states(lowercase__      ,   fpaa=lowercase__)

        lowerCAmelCase__					     = model.apply(
            {'params': params}      ,   lowercase__      ,   jnp.array(lowercase__      ,   dtype=jnp.intaa)      ,   encoder_hidden_states=lowercase__      ,   ).sample

        assert sample.shape == latents.shape

        lowerCAmelCase__					     = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()))      ,   dtype=jnp.floataa)
        lowerCAmelCase__					     = jnp.array(lowercase__      ,   dtype=jnp.floataa)

        # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware
        assert jnp.allclose(lowercase__      ,   lowercase__      ,   atol=1e-2)




 @parameterized.expand(
     [
         # fmt: off
         [83, 4, [0.1_514, 0.0_807, 0.1_624, 0.1_016, -0.1_896, 0.0_263, 0.0_677, 0.2_310]],
         [17, 0.55, [0.1_164, -0.0_216, 0.0_170, 0.1_589, -0.3_120, 0.1_005, -0.0_581, -0.1_458]],
         [8, 0.89, [-0.1_758, -0.0_169, 0.1_004, -0.1_411, 0.1_312, 0.1_103, -0.1_996, 0.2_139]],
         [3, 1_000, [0.1_214, 0.0_352, -0.0_731, -0.1_562, -0.0_994, -0.0_906, -0.2_340, -0.0_539]],
         # fmt: on
     ])
 def 		__snake_case						(      self :  Tuple      ,   lowercase__ :  Tuple      ,   lowercase__ :  List[str]      ,   lowercase__ :  Any):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.get_unet_model(model_id='stabilityai/stable-diffusion-2'      ,   fpaa=lowercase__)
        lowerCAmelCase__					     = self.get_latents(lowercase__      ,   shape=(4, 4, 96, 96)      ,   fpaa=lowercase__)
        lowerCAmelCase__					     = self.get_encoder_hidden_states(lowercase__      ,   shape=(4, 77, 1_024)      ,   fpaa=lowercase__)

        lowerCAmelCase__					     = model.apply(
            {'params': params}      ,   lowercase__      ,   jnp.array(lowercase__      ,   dtype=jnp.intaa)      ,   encoder_hidden_states=lowercase__      ,   ).sample

        assert sample.shape == latents.shape

        lowerCAmelCase__					     = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()))      ,   dtype=jnp.floataa)
        lowerCAmelCase__					     = jnp.array(lowercase__      ,   dtype=jnp.floataa)

        # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware
        assert jnp.allclose(lowercase__      ,   lowercase__      ,   atol=1e-2)

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 convert_to_rgb, 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


if is_vision_available():
    import PIL


lowerCAmelCase__     						=			logging.get_logger(__name__)
class     a_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= ['pixel_values']




 def __init__(      self :  Tuple      ,   lowercase__ :  bool = True      ,   lowercase__ :  Dict[str, int] = None      ,   lowercase__ :  PILImageResampling = PILImageResampling.BICUBIC      ,   lowercase__ :  bool = True      ,   lowercase__ :  Union[int, float] = 1 / 255      ,   lowercase__ :  bool = True      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  bool = True      ,   **lowercase__ :  List[Any]      ,   ):







        '''simple docstring'''



        super().__init__(**lowercase__)
        lowerCAmelCase__					     = size if size is not None else {'height': 384, 'width': 384}
        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)

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




 def 		__snake_case						(      self :  List[str]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Dict[str, int]      ,   lowercase__ :  PILImageResampling = PILImageResampling.BICUBIC      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Dict      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)
        if "height" not in size or "width" not in size:
               raise ValueError(F"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""")
        lowerCAmelCase__					     = (size['height'], size['width'])
        return resize(lowercase__      ,   size=lowercase__      ,   resample=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  List[str]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Union[int, float]      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Union[str, Any]      ,   ):







        '''simple docstring'''



        return rescale(lowercase__      ,   scale=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Union[float, List[float]]      ,   lowercase__ :  Union[float, List[float]]      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Any      ,   ):







        '''simple docstring'''



        return normalize(lowercase__      ,   mean=lowercase__      ,   std=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  Any      ,   lowercase__ :  ImageInput      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[Dict[str, int]] = None      ,   lowercase__ :  PILImageResampling = None      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[float] = None      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[str, TensorType]] = None      ,   lowercase__ :  bool = None      ,   lowercase__ :  ChannelDimension = ChannelDimension.FIRST      ,   **lowercase__ :  Dict      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = do_resize if do_resize is not None else self.do_resize
        lowerCAmelCase__					     = resample if resample is not None else self.resample
        lowerCAmelCase__					     = do_rescale if do_rescale is not None else self.do_rescale
        lowerCAmelCase__					     = rescale_factor if rescale_factor is not None else self.rescale_factor
        lowerCAmelCase__					     = do_normalize if do_normalize is not None else self.do_normalize
        lowerCAmelCase__					     = image_mean if image_mean is not None else self.image_mean
        lowerCAmelCase__					     = image_std if image_std is not None else self.image_std
        lowerCAmelCase__					     = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

        lowerCAmelCase__					     = size if size is not None else self.size
        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)

        lowerCAmelCase__					     = make_list_of_images(lowercase__)

        if not valid_images(lowercase__):
               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 or resample is None:
               raise ValueError('Size and resample must be specified if do_resize 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:
               lowerCAmelCase__					     = [convert_to_rgb(lowercase__) for image in images]

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

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

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

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

        lowerCAmelCase__					     = [to_channel_dimension_format(lowercase__      ,   lowercase__) for image in images]

        lowerCAmelCase__					     = BatchFeature(data={'pixel_values': images}      ,   tensor_type=lowercase__)

        return encoded_outputs
