

import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()






class     __magic_name__     (							unittest.TestCase     ):


 @property
 def _UpperCamelCase						(    self		:			List[str]     )     ->   Union[str, Any]:
   UpperCAmelCase          =	1
   UpperCAmelCase          =	3
   UpperCAmelCase          =	(3_2, 3_2)

   UpperCAmelCase          =	floats_tensor((batch_size, num_channels) + sizes      ,    rng=random.Random(0     )     ).to(lowerCAmelCase__     )
   return image


 @property
 def _UpperCamelCase						(    self		:			int     )     ->   List[str]:
   torch.manual_seed(0     )
   UpperCAmelCase          =	UNetaDModel(
       block_out_channels=(3_2, 6_4)      ,    layers_per_block=2      ,    sample_size=3_2      ,    in_channels=6      ,    out_channels=3      ,    down_block_types=("DownBlock2D", "AttnDownBlock2D")      ,    up_block_types=("AttnUpBlock2D", "UpBlock2D")      ,    )
   return model


 @property
 def _UpperCamelCase						(    self		:			Optional[Any]     )     ->   Optional[int]:
   torch.manual_seed(0     )
   UpperCAmelCase          =	VQModel(
       block_out_channels=[3_2, 6_4]      ,    in_channels=3      ,    out_channels=3      ,    down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]      ,    up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]      ,    latent_channels=3      ,    )
   return model


 def _UpperCamelCase						(    self		:			Union[str, Any]     )     ->   Optional[int]:
   UpperCAmelCase          =	"cpu"
   UpperCAmelCase          =	self.dummy_uncond_unet
   UpperCAmelCase          =	DDIMScheduler()
   UpperCAmelCase          =	self.dummy_vq_model

   UpperCAmelCase          =	LDMSuperResolutionPipeline(unet=lowerCAmelCase__      ,    vqvae=lowerCAmelCase__      ,    scheduler=lowerCAmelCase__     )
   ldm.to(lowerCAmelCase__     )
   ldm.set_progress_bar_config(disable=lowerCAmelCase__     )

   UpperCAmelCase          =	self.dummy_image.to(lowerCAmelCase__     )

   UpperCAmelCase          =	torch.Generator(device=lowerCAmelCase__     ).manual_seed(0     )
   UpperCAmelCase          =	ldm(image=lowerCAmelCase__      ,    generator=lowerCAmelCase__      ,    num_inference_steps=2      ,    output_type="numpy"     ).images

   UpperCAmelCase          =	image[0, -3:, -3:, -1]

   assert image.shape == (1, 6_4, 6_4, 3)
   UpperCAmelCase          =	np.array([0.8_678, 0.8_245, 0.6_381, 0.6_830, 0.4_385, 0.5_599, 0.4_641, 0.6_201, 0.5_150]     )

   assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1e-2


 @unittest.skipIf(torch_device != "cuda"      ,    "This test requires a GPU"     )
 def _UpperCamelCase						(    self		:			Any     )     ->   List[str]:
   UpperCAmelCase          =	self.dummy_uncond_unet
   UpperCAmelCase          =	DDIMScheduler()
   UpperCAmelCase          =	self.dummy_vq_model

   # put models in fp16
   UpperCAmelCase          =	unet.half()
   UpperCAmelCase          =	vqvae.half()

   UpperCAmelCase          =	LDMSuperResolutionPipeline(unet=lowerCAmelCase__      ,    vqvae=lowerCAmelCase__      ,    scheduler=lowerCAmelCase__     )
   ldm.to(lowerCAmelCase__     )
   ldm.set_progress_bar_config(disable=lowerCAmelCase__     )

   UpperCAmelCase          =	self.dummy_image.to(lowerCAmelCase__     )

   UpperCAmelCase          =	ldm(lowerCAmelCase__      ,    num_inference_steps=2      ,    output_type="numpy"     ).images

   assert image.shape == (1, 6_4, 6_4, 3)






@slow
@require_torch
class     __magic_name__     (							unittest.TestCase     ):


 def _UpperCamelCase						(    self		:			Optional[int]     )     ->   Union[str, Any]:
   UpperCAmelCase          =	load_image(
       "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
       "/vq_diffusion/teddy_bear_pool.png"     )
   UpperCAmelCase          =	init_image.resize((6_4, 6_4)      ,    resample=PIL_INTERPOLATION["lanczos"]     )

   UpperCAmelCase          =	LDMSuperResolutionPipeline.from_pretrained("duongna/ldm-super-resolution"      ,    device_map="auto"     )
   ldm.set_progress_bar_config(disable=lowerCAmelCase__     )

   UpperCAmelCase          =	torch.manual_seed(0     )
   UpperCAmelCase          =	ldm(image=lowerCAmelCase__      ,    generator=lowerCAmelCase__      ,    num_inference_steps=2_0      ,    output_type="numpy"     ).images

   UpperCAmelCase          =	image[0, -3:, -3:, -1]

   assert image.shape == (1, 2_5_6, 2_5_6, 3)
   UpperCAmelCase          =	np.array([0.7_644, 0.7_679, 0.7_642, 0.7_633, 0.7_666, 0.7_560, 0.7_425, 0.7_257, 0.6_907]     )

   assert np.abs(image_slice.flatten() - expected_slice     ).max() < 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 (
    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


lowerCAmelCase__							=			logging.get_logger(__name__)


if is_vision_available():
      import PIL






class     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    ["""pixel_values"""]


 def __init__(    self		:			str      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Dict[str, int] = None      ,    lowerCAmelCase__		:			PILImageResampling = PILImageResampling.BICUBIC      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Dict[str, int] = None      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Union[int, float] = 1 / 2_5_5      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Optional[Union[float, List[float]]] = None      ,    lowerCAmelCase__		:			Optional[Union[float, List[float]]] = None      ,    lowerCAmelCase__		:			bool = True      ,    **lowerCAmelCase__		:			str      ,    )     ->   None:
   super().__init__(**lowerCAmelCase__     )
   UpperCAmelCase          =	size if size is not None else {"shortest_edge": 2_2_4}
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__      ,    default_to_square=lowerCAmelCase__     )
   UpperCAmelCase          =	crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__     )

   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 _UpperCamelCase						(    self		:			Optional[Any]      ,    lowerCAmelCase__		:			np.ndarray      ,    lowerCAmelCase__		:			Dict[str, int]      ,    lowerCAmelCase__		:			PILImageResampling = PILImageResampling.BICUBIC      ,    lowerCAmelCase__		:			Optional[Union[str, ChannelDimension]] = None      ,    **lowerCAmelCase__		:			Optional[int]      ,    )     ->   np.ndarray:
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__      ,    default_to_square=lowerCAmelCase__     )
   UpperCAmelCase          =	get_resize_output_image_size(
       lowerCAmelCase__      ,    size=(size["height"], size["width"])      ,    default_to_square=lowerCAmelCase__     )
   return resize(lowerCAmelCase__      ,    size=lowerCAmelCase__      ,    resample=lowerCAmelCase__      ,    data_format=lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			List[Any]      ,    lowerCAmelCase__		:			np.ndarray      ,    lowerCAmelCase__		:			Dict[str, int]      ,    lowerCAmelCase__		:			Optional[Union[str, ChannelDimension]] = None      ,    **lowerCAmelCase__		:			List[Any]      ,    )     ->   np.ndarray:
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__     )
   return center_crop(lowerCAmelCase__      ,    size=(size["height"], size["width"])      ,    data_format=lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Any      ,    lowerCAmelCase__		:			np.ndarray      ,    lowerCAmelCase__		:			Union[int, float]      ,    lowerCAmelCase__		:			Optional[Union[str, ChannelDimension]] = None      ,    **lowerCAmelCase__		:			List[Any]      ,    )     ->   Optional[int]:
   return rescale(lowerCAmelCase__      ,    scale=lowerCAmelCase__      ,    data_format=lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Union[str, Any]      ,    lowerCAmelCase__		:			np.ndarray      ,    lowerCAmelCase__		:			Union[float, List[float]]      ,    lowerCAmelCase__		:			Union[float, List[float]]      ,    lowerCAmelCase__		:			Optional[Union[str, ChannelDimension]] = None      ,    **lowerCAmelCase__		:			List[str]      ,    )     ->   np.ndarray:
   return normalize(lowerCAmelCase__      ,    mean=lowerCAmelCase__      ,    std=lowerCAmelCase__      ,    data_format=lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			List[str]      ,    lowerCAmelCase__		:			ImageInput      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			Dict[str, int] = None      ,    lowerCAmelCase__		:			PILImageResampling = None      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			int = None      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			float = None      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			Optional[Union[float, List[float]]] = None      ,    lowerCAmelCase__		:			Optional[Union[float, List[float]]] = None      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			Optional[Union[str, TensorType]] = None      ,    lowerCAmelCase__		:			Optional[ChannelDimension] = ChannelDimension.FIRST      ,    **lowerCAmelCase__		:			int      ,    )     ->   PIL.Image.Image:
   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(lowerCAmelCase__      ,    default_to_square=lowerCAmelCase__     )
   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(lowerCAmelCase__     )
   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(lowerCAmelCase__     )

   if not valid_images(lowerCAmelCase__     ):
     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(lowerCAmelCase__     ) for image in images]

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

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

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

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

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

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

   UpperCAmelCase          =	{"pixel_values": images}
   return BatchFeature(data=lowerCAmelCase__      ,    tensor_type=lowerCAmelCase__     )



