'''simple docstring'''
import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available


if is_torch_available():
 import numpy as np
 import torch

if is_vision_available():
 from PIL import Image







def 				__UpperCamelCase (					__UpperCAmelCase  :					Tuple ,   __UpperCAmelCase  :					List[Any]=False ,   __UpperCAmelCase  :					str=False ,   __UpperCAmelCase  :					Any=False			)							->	Optional[Any]:
  assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

  lowercase				:							Tuple									=   []
  for i in range(image_processor_tester.batch_size			):
    if equal_resolution:
      lowercase				:							Optional[int]									=   image_processor_tester.max_resolution
    else:
      # To avoid getting image width/height 0
      lowercase				:							str									=   image_processor_tester.min_resolution
      if getattr(_a ,   '''size_divisor''' ,   _a			):
        # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
        lowercase				:							int									=   max(image_processor_tester.size_divisor ,   _a			)
      lowercase				:							Tuple									=   np.random.choice(np.arange(_a ,   image_processor_tester.max_resolution			) ,   2			)
    image_inputs.append(
        np.random.randint(255 ,   size=(image_processor_tester.num_channels, width, height) ,   dtype=np.uinta			)			)

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

  if torchify:
    lowercase				:							Tuple									=   [torch.from_numpy(_a			) for image in image_inputs]

  return image_inputs







def 				__UpperCamelCase (					__UpperCAmelCase  :					List[Any] ,   __UpperCAmelCase  :					Union[str, Any]=10 ,   __UpperCAmelCase  :					int=10 ,   __UpperCAmelCase  :					Tuple=False ,   __UpperCAmelCase  :					Tuple=False			)							->	List[str]:
  lowercase				:							Dict									=   []
  for i in range(image_processor_tester.num_frames			):
    video.append(np.random.randint(255 ,   size=(image_processor_tester.num_channels, width, height) ,   dtype=np.uinta			)			)

  if not numpify and not torchify:
    # PIL expects the channel dimension as last dimension
    lowercase				:							Any									=   [Image.fromarray(np.moveaxis(_a ,   0 ,   -1			)			) for frame in video]

  if torchify:
    lowercase				:							Tuple									=   [torch.from_numpy(_a			) for frame in video]

  return video







def 				__UpperCamelCase (					__UpperCAmelCase  :					List[str] ,   __UpperCAmelCase  :					Dict=False ,   __UpperCAmelCase  :					str=False ,   __UpperCAmelCase  :					int=False			)							->	Optional[int]:
  assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

  lowercase				:							Optional[Any]									=   []
  for i in range(image_processor_tester.batch_size			):
    if equal_resolution:
      lowercase				:							Optional[Any]									=   image_processor_tester.max_resolution
    else:
      lowercase				:							Any									=   np.random.choice(
          np.arange(image_processor_tester.min_resolution ,   image_processor_tester.max_resolution			) ,   2			)
      lowercase				:							Dict									=   prepare_video(
          image_processor_tester=_a ,   width=_a ,   height=_a ,   numpify=_a ,   torchify=_a ,   )
    video_inputs.append(_a			)

  return video_inputs






class _lowerCAmelCase			:
      UpperCAmelCase_	:						Any	 =       None







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Any									=   self.image_processing_class(**self.image_processor_dict     )
        lowercase				:							Any									=   json.loads(image_processor.to_json_string()     )
        for key, value in self.image_processor_dict.items():
          self.assertEqual(obj[key]  ,    _lowerCamelCase     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							List[Any]									=   self.image_processing_class(**self.image_processor_dict     )

        with tempfile.TemporaryDirectory() as tmpdirname:
          lowercase				:							List[str]									=   os.path.join(_lowerCamelCase  ,    '''image_processor.json'''     )
          image_processor_first.to_json_file(_lowerCamelCase     )
          lowercase				:							Any									=   self.image_processing_class.from_json_file(_lowerCamelCase     )

        self.assertEqual(image_processor_second.to_dict()  ,    image_processor_first.to_dict()     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Union[str, Any]									=   self.image_processing_class(**self.image_processor_dict     )

        with tempfile.TemporaryDirectory() as tmpdirname:
          lowercase				:							List[str]									=   image_processor_first.save_pretrained(_lowerCamelCase     )[0]
          check_json_file_has_correct_format(_lowerCamelCase     )
          lowercase				:							Optional[int]									=   self.image_processing_class.from_pretrained(_lowerCamelCase     )

        self.assertEqual(image_processor_second.to_dict()  ,    image_processor_first.to_dict()     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							str									=   self.image_processing_class()
        self.assertIsNotNone(_lowerCamelCase     )







      @require_torch
      @require_vision
      def      lowerCamelCase__      (  self     ):
        if self.test_cast_dtype is not None:
          # Initialize image_processor
          lowercase				:							int									=   self.image_processing_class(**self.image_processor_dict     )

          # create random PyTorch tensors
          lowercase				:							List[str]									=   prepare_image_inputs(self.image_processor_tester  ,    equal_resolution=_lowerCamelCase  ,    torchify=_lowerCamelCase     )

          lowercase				:							Optional[int]									=   image_processor(_lowerCamelCase  ,    return_tensors='''pt'''     )
          # for layoutLM compatiblity
          self.assertEqual(encoding.pixel_values.device  ,    torch.device('''cpu'''     )     )
          self.assertEqual(encoding.pixel_values.dtype  ,    torch.floataa     )

          lowercase				:							Optional[int]									=   image_processor(_lowerCamelCase  ,    return_tensors='''pt'''     ).to(torch.floataa     )
          self.assertEqual(encoding.pixel_values.device  ,    torch.device('''cpu'''     )     )
          self.assertEqual(encoding.pixel_values.dtype  ,    torch.floataa     )

          lowercase				:							List[str]									=   image_processor(_lowerCamelCase  ,    return_tensors='''pt'''     ).to('''cpu'''  ,    torch.bfloataa     )
          self.assertEqual(encoding.pixel_values.device  ,    torch.device('''cpu'''     )     )
          self.assertEqual(encoding.pixel_values.dtype  ,    torch.bfloataa     )

          with self.assertRaises(_lowerCamelCase     ):
            lowercase				:							Optional[int]									=   image_processor(_lowerCamelCase  ,    return_tensors='''pt'''     ).to(torch.bfloataa  ,    '''cpu'''     )

          # Try with text + image feature
          lowercase				:							int									=   image_processor(_lowerCamelCase  ,    return_tensors='''pt'''     )
          encoding.update({'''input_ids''': torch.LongTensor([[1, 2, 3], [4, 5, 6]]     )}     )
          lowercase				:							List[Any]									=   encoding.to(torch.floataa     )

          self.assertEqual(encoding.pixel_values.device  ,    torch.device('''cpu'''     )     )
          self.assertEqual(encoding.pixel_values.dtype  ,    torch.floataa     )
          self.assertEqual(encoding.input_ids.dtype  ,    torch.long     )
'''simple docstring'''
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       __lowercase		(    unittest.TestCase    ):







     """simple docstring"""






     @property
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Dict		     =	1
         __UpperCamelCase						:						Union[str, Any]		     =	3
         __UpperCamelCase						:						Tuple		     =	(3_2, 3_2)

         __UpperCamelCase						:						List[Any]		     =	floats_tensor((batch_size, num_channels) + sizes  ,      rng=random.Random(0     )     ).to(_lowerCamelCase     )
         return image







     @property
     def lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						Dict		     =	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 lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						List[str]		     =	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 lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Tuple		     =	'cpu'
         __UpperCamelCase						:						Union[str, Any]		     =	self.dummy_uncond_unet
         __UpperCamelCase						:						List[str]		     =	DDIMScheduler()
         __UpperCamelCase						:						Any		     =	self.dummy_vq_model

         __UpperCamelCase						:						Tuple		     =	LDMSuperResolutionPipeline(unet=_lowerCamelCase  ,      vqvae=_lowerCamelCase  ,      scheduler=_lowerCamelCase     )
         ldm.to(_lowerCamelCase     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						int		     =	self.dummy_image.to(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	torch.Generator(device=_lowerCamelCase     ).manual_seed(0     )
         __UpperCamelCase						:						Union[str, Any]		     =	ldm(image=_lowerCamelCase  ,      generator=_lowerCamelCase  ,      num_inference_steps=2  ,      output_type='numpy'     ).images

         __UpperCamelCase						:						str		     =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 6_4, 6_4, 3)
         __UpperCamelCase						:						str		     =	np.array([0.8_6_7_8, 0.8_2_4_5, 0.6_3_8_1, 0.6_8_3_0, 0.4_3_8_5, 0.5_5_9_9, 0.4_6_4_1, 0.6_2_0_1, 0.5_1_5_0]     )

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







     @unittest.skipIf(torch_device != 'cuda'  ,      'This test requires a GPU'     )
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	self.dummy_uncond_unet
         __UpperCamelCase						:						Optional[int]		     =	DDIMScheduler()
         __UpperCamelCase						:						Any		     =	self.dummy_vq_model

         # put models in fp16
         __UpperCamelCase						:						str		     =	unet.half()
         __UpperCamelCase						:						Optional[Any]		     =	vqvae.half()

         __UpperCamelCase						:						Optional[int]		     =	LDMSuperResolutionPipeline(unet=_lowerCamelCase  ,      vqvae=_lowerCamelCase  ,      scheduler=_lowerCamelCase     )
         ldm.to(_lowerCamelCase     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						Dict		     =	self.dummy_image.to(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[Any]		     =	ldm(_lowerCamelCase  ,      num_inference_steps=2  ,      output_type='numpy'     ).images

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






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







     """simple docstring"""






     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						List[Any]		     =	load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/vq_diffusion/teddy_bear_pool.png'     )
         __UpperCamelCase						:						List[Any]		     =	init_image.resize((6_4, 6_4)  ,      resample=PIL_INTERPOLATION['lanczos']     )

         __UpperCamelCase						:						List[str]		     =	LDMSuperResolutionPipeline.from_pretrained('duongna/ldm-super-resolution'  ,      device_map='auto'     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	torch.manual_seed(0     )
         __UpperCamelCase						:						Dict		     =	ldm(image=_lowerCamelCase  ,      generator=_lowerCamelCase  ,      num_inference_steps=2_0  ,      output_type='numpy'     ).images

         __UpperCamelCase						:						List[Any]		     =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 2_5_6, 2_5_6, 3)
         __UpperCamelCase						:						str		     =	np.array([0.7_6_4_4, 0.7_6_7_9, 0.7_6_4_2, 0.7_6_3_3, 0.7_6_6_6, 0.7_5_6_0, 0.7_4_2_5, 0.7_2_5_7, 0.6_9_0_7]     )

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



