






"""simple docstring"""







import os
import tempfile
import unittest

import numpy as np
import torch

from diffusers.models import ModelMixin, UNetaDConditionModel
from diffusers.models.attention_processor import AttnProcessor, LoRAAttnProcessor
from diffusers.utils import (
    floats_tensor,
    logging,
    skip_mps,
    torch_device,
)
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

a :				Optional[Any]      					=		logging.get_logger(__name__)





def 						lowercase__(A					,		A = True						)				->Optional[int]:




						"""simple docstring"""



						lowercase__				:      str=       {}
						for name in model.attn_processors.keys():
												lowercase__				:      Union[str, Any]=       name.endswith("attn2.processor"						) and not (
												    name.startswith("transformer_in"						) or "temp_attentions" in name.split("."						)
												)
												lowercase__				:      List[str]=       model.config.cross_attention_dim if has_cross_attention else None
												if name.startswith("mid_block"						):
																		lowercase__				:      Optional[Any]=       model.config.block_out_channels[-1]
												elif name.startswith("up_blocks"						):
																		lowercase__				:      Optional[Any]=       int(name[len("up_blocks."						)]						)
																		lowercase__				:      List[str]=       list(reversed(model.config.block_out_channels						)						)[block_id]
												elif name.startswith("down_blocks"						):
																		lowercase__				:      List[Any]=       int(name[len("down_blocks."						)]						)
																		lowercase__				:      Optional[Any]=       model.config.block_out_channels[block_id]
												elif name.startswith("transformer_in"						):
																		# Note that the `8 * ...` comes from: https://github.com/huggingface/diffusers/blob/7139f0e874f10b2463caa8cbd585762a309d12d6/src/diffusers/models/unet_3d_condition.py#L148
																		lowercase__				:      Optional[int]=       8 * model.config.attention_head_dim

												lowercase__				:      List[str]=       LoRAAttnProcessor(hidden_size=A					,		cross_attention_dim=A						)
												lowercase__				:      int=       lora_attn_procs[name].to(model.device						)

												if mock_weights:
																		# add 1 to weights to mock trained weights
																		with torch.no_grad():
																								lora_attn_procs[name].to_q_lora.up.weight += 1
																								lora_attn_procs[name].to_k_lora.up.weight += 1
																								lora_attn_procs[name].to_v_lora.up.weight += 1
																								lora_attn_procs[name].to_out_lora.up.weight += 1

						return lora_attn_procs







@skip_mps
class     __UpperCAmelCase(   SCREAMING_SNAKE_CASE__  ,  SCREAMING_SNAKE_CASE__  ,  unittest.TestCase							):




						"""simple docstring"""




						__lowerCamelCase				       =					UNetaDConditionModel
						__lowerCamelCase				       =					"sample"




						@property
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      List[str]=       4
												lowercase__				:      Tuple=       4
												lowercase__				:      Any=       4
												lowercase__				:      Tuple=       (32, 32)

												lowercase__				:      Dict=       floats_tensor((batch_size, num_channels, num_frames) + sizes			).to(snake_case__			)
												lowercase__				:      int=       torch.tensor([10]			).to(snake_case__			)
												lowercase__				:      List[Any]=       floats_tensor((batch_size, 4, 32)			).to(snake_case__			)

												return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states}




						@property
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												return (4, 4, 32, 32)




						@property
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												return (4, 4, 32, 32)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      Union[str, Any]=       {
												    "block_out_channels": (32, 64),
												    "down_block_types": (
												        "CrossAttnDownBlock3D",
												        "DownBlock3D",
												    ),
												    "up_block_types": ("UpBlock3D", "CrossAttnUpBlock3D"),
												    "cross_attention_dim": 32,
												    "attention_head_dim": 8,
												    "out_channels": 4,
												    "in_channels": 4,
												    "layers_per_block": 1,
												    "sample_size": 32,
												}
												lowercase__				:      int=       self.dummy_input
												return init_dict, inputs_dict




						@unittest.skipIf(
						    torch_device != "cuda" or not is_xformers_available()       ,  reason="XFormers attention is only available with CUDA and `xformers` installed"       ,  )
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      Tuple=       self.prepare_init_args_and_inputs_for_common()
												lowercase__				:      Union[str, Any]=       self.model_class(**snake_case__			)

												model.enable_xformers_memory_efficient_attention()

												assert (
												    model.mid_block.attentions[0].transformer_blocks[0].attna.processor.__class__.__name__
												    == "XFormersAttnProcessor"
												), "xformers is not enabled"




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      List[Any]=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      List[str]=       32

												lowercase__				:      int=       self.model_class(**snake_case__			)
												model.to(snake_case__			)
												model.eval()

												with torch.no_grad():
																		lowercase__				:      List[Any]=       model(**snake_case__			)

																		if isinstance(snake_case__       ,  snake_case__			):
																								lowercase__				:      Dict=       output.sample

												self.assertIsNotNone(snake_case__			)
												lowercase__				:      Dict=       inputs_dict["sample"].shape
												self.assertEqual(output.shape       ,  snake_case__       ,  "Input and output shapes do not match"			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      List[str]=       self.prepare_init_args_and_inputs_for_common()
												lowercase__				:      List[Any]=       self.model_class(**snake_case__			)
												model.to(snake_case__			)
												model.eval()

												with torch.no_grad():
																		# Warmup pass when using mps (see #372)
																		if torch_device == "mps" and isinstance(snake_case__       ,  snake_case__			):
																								model(**self.dummy_input			)

																		lowercase__				:      Tuple=       model(**snake_case__			)
																		if isinstance(snake_case__       ,  snake_case__			):
																								lowercase__				:      List[Any]=       first.sample

																		lowercase__				:      List[str]=       model(**snake_case__			)
																		if isinstance(snake_case__       ,  snake_case__			):
																								lowercase__				:      int=       second.sample

												lowercase__				:      List[str]=       first.cpu().numpy()
												lowercase__				:      Tuple=       second.cpu().numpy()
												lowercase__				:      str=       out_a[~np.isnan(snake_case__			)]
												lowercase__				:      Union[str, Any]=       out_a[~np.isnan(snake_case__			)]
												lowercase__				:      Optional[int]=       np.amax(np.abs(out_a - out_a			)			)
												self.assertLessEqual(snake_case__       ,  1e-5			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      Any=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      List[Any]=       8

												lowercase__				:      List[Any]=       self.model_class(**snake_case__			)
												model.to(snake_case__			)
												model.eval()

												model.set_attention_slice("auto"			)
												with torch.no_grad():
																		lowercase__				:      int=       model(**snake_case__			)
												assert output is not None

												model.set_attention_slice("max"			)
												with torch.no_grad():
																		lowercase__				:      int=       model(**snake_case__			)
												assert output is not None

												model.set_attention_slice(2			)
												with torch.no_grad():
																		lowercase__				:      Any=       model(**snake_case__			)
												assert output is not None




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      Optional[int]=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      List[str]=       8

												lowercase__				:      Dict=       self.model_class(**snake_case__			)
												model.to(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      str=       model(**snake_case__			).sample

												lowercase__				:      Union[str, Any]=       create_lora_layers(snake_case__			)

												# make sure we can set a list of attention processors
												model.set_attn_processor(snake_case__			)
												model.to(snake_case__			)

												# test that attn processors can be set to itself
												model.set_attn_processor(model.attn_processors			)

												with torch.no_grad():
																		lowercase__				:      str=       model(**snake_case__       ,  cross_attention_kwargs={"scale": 0.0}			).sample
																		lowercase__				:      str=       model(**snake_case__       ,  cross_attention_kwargs={"scale": 0.5}			).sample
																		lowercase__				:      Optional[Any]=       model(**snake_case__       ,  cross_attention_kwargs={"scale": 0.5}			).sample

												assert (samplea - samplea).abs().max() < 3e-3
												assert (samplea - samplea).abs().max() < 3e-3

												# sample 2 and sample 3 should be different
												assert (samplea - samplea).abs().max() > 3e-3




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      Dict=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      Tuple=       8

												torch.manual_seed(0			)
												lowercase__				:      List[Any]=       self.model_class(**snake_case__			)
												model.to(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      Any=       model(**snake_case__			).sample

												lowercase__				:      Union[str, Any]=       create_lora_layers(snake_case__			)
												model.set_attn_processor(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      Optional[int]=       model(**snake_case__       ,  cross_attention_kwargs={"scale": 0.5}			).sample

												with tempfile.TemporaryDirectory() as tmpdirname:
																		model.save_attn_procs(snake_case__			)
																		self.assertTrue(os.path.isfile(os.path.join(snake_case__       ,  "pytorch_lora_weights.bin"			)			)			)
																		torch.manual_seed(0			)
																		lowercase__				:      int=       self.model_class(**snake_case__			)
																		new_model.to(snake_case__			)
																		new_model.load_attn_procs(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      str=       new_model(**snake_case__       ,  cross_attention_kwargs={"scale": 0.5}			).sample

												assert (sample - new_sample).abs().max() < 1e-3

												# LoRA and no LoRA should NOT be the same
												assert (sample - old_sample).abs().max() > 1e-4




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      str=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      Union[str, Any]=       8

												torch.manual_seed(0			)
												lowercase__				:      Tuple=       self.model_class(**snake_case__			)
												model.to(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      Union[str, Any]=       model(**snake_case__			).sample

												lowercase__				:      Any=       create_lora_layers(snake_case__			)
												model.set_attn_processor(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      List[str]=       model(**snake_case__       ,  cross_attention_kwargs={"scale": 0.5}			).sample

												with tempfile.TemporaryDirectory() as tmpdirname:
																		model.save_attn_procs(snake_case__       ,  safe_serialization=snake_case__			)
																		self.assertTrue(os.path.isfile(os.path.join(snake_case__       ,  "pytorch_lora_weights.safetensors"			)			)			)
																		torch.manual_seed(0			)
																		lowercase__				:      int=       self.model_class(**snake_case__			)
																		new_model.to(snake_case__			)
																		new_model.load_attn_procs(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      List[Any]=       new_model(**snake_case__       ,  cross_attention_kwargs={"scale": 0.5}			).sample

												assert (sample - new_sample).abs().max() < 3e-3

												# LoRA and no LoRA should NOT be the same
												assert (sample - old_sample).abs().max() > 1e-4




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# enable deterministic behavior for gradient checkpointing
												lowercase__,	lowercase__				:      Any=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      List[str]=       8

												torch.manual_seed(0			)
												lowercase__				:      Tuple=       self.model_class(**snake_case__			)
												model.to(snake_case__			)

												lowercase__				:      Optional[Any]=       create_lora_layers(snake_case__       ,  mock_weights=snake_case__			)
												model.set_attn_processor(snake_case__			)
												# Saving as torch, properly reloads with directly filename
												with tempfile.TemporaryDirectory() as tmpdirname:
																		model.save_attn_procs(snake_case__			)
																		self.assertTrue(os.path.isfile(os.path.join(snake_case__       ,  "pytorch_lora_weights.bin"			)			)			)
																		torch.manual_seed(0			)
																		lowercase__				:      List[Any]=       self.model_class(**snake_case__			)
																		new_model.to(snake_case__			)
																		new_model.load_attn_procs(snake_case__       ,  weight_name="pytorch_lora_weights.bin"			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      Any=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      Optional[Any]=       8

												torch.manual_seed(0			)
												lowercase__				:      Tuple=       self.model_class(**snake_case__			)
												model.to(snake_case__			)

												lowercase__				:      str=       create_lora_layers(snake_case__       ,  mock_weights=snake_case__			)
												model.set_attn_processor(snake_case__			)
												# Saving as torch, properly reloads with directly filename
												with tempfile.TemporaryDirectory() as tmpdirname:
																		model.save_attn_procs(snake_case__			)
																		self.assertTrue(os.path.isfile(os.path.join(snake_case__       ,  "pytorch_lora_weights.bin"			)			)			)
																		torch.manual_seed(0			)
																		lowercase__				:      List[Any]=       self.model_class(**snake_case__			)
																		new_model.to(snake_case__			)
																		with self.assertRaises(snake_case__			) as e:
																								new_model.load_attn_procs(snake_case__       ,  use_safetensors=snake_case__			)
																		self.assertIn("Error no file named pytorch_lora_weights.safetensors"       ,  str(e.exception			)			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      Optional[int]=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      List[str]=       8

												torch.manual_seed(0			)
												lowercase__				:      Optional[int]=       self.model_class(**snake_case__			)
												model.to(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      int=       model(**snake_case__			).sample

												lowercase__				:      List[Any]=       create_lora_layers(snake_case__			)
												model.set_attn_processor(snake_case__			)

												with torch.no_grad():
																		lowercase__				:      int=       model(**snake_case__       ,  cross_attention_kwargs={"scale": 0.0}			).sample

												model.set_attn_processor(AttnProcessor()			)

												with torch.no_grad():
																		lowercase__				:      Optional[Any]=       model(**snake_case__			).sample

												assert (sample - new_sample).abs().max() < 1e-4
												assert (sample - old_sample).abs().max() < 3e-3




						@unittest.skipIf(
						    torch_device != "cuda" or not is_xformers_available()       ,  reason="XFormers attention is only available with CUDA and `xformers` installed"       ,  )
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# enable deterministic behavior for gradient checkpointing
												lowercase__,	lowercase__				:      List[str]=       self.prepare_init_args_and_inputs_for_common()

												lowercase__				:      List[Any]=       4

												torch.manual_seed(0			)
												lowercase__				:      Any=       self.model_class(**snake_case__			)
												model.to(snake_case__			)
												lowercase__				:      List[Any]=       create_lora_layers(snake_case__			)
												model.set_attn_processor(snake_case__			)

												# default
												with torch.no_grad():
																		lowercase__				:      List[Any]=       model(**snake_case__			).sample

																		model.enable_xformers_memory_efficient_attention()
																		lowercase__				:      Optional[int]=       model(**snake_case__			).sample

																		model.disable_xformers_memory_efficient_attention()
																		lowercase__				:      Tuple=       model(**snake_case__			).sample

												assert (sample - on_sample).abs().max() < 1e-4
												assert (sample - off_sample).abs().max() < 1e-4




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__,	lowercase__				:      List[str]=       self.prepare_init_args_and_inputs_for_common()
												lowercase__				:      Optional[Any]=       32

												lowercase__				:      Union[str, Any]=       self.model_class(**snake_case__			)
												model.to(snake_case__			)
												model.eval()

												with torch.no_grad():
																		lowercase__				:      Dict=       model(**snake_case__			)[0]

												model.enable_forward_chunking()
												with torch.no_grad():
																		lowercase__				:      List[str]=       model(**snake_case__			)[0]

												self.assertEqual(output.shape       ,  output_a.shape       ,  "Shape doesn't match"			)
												assert np.abs(output.cpu() - output_a.cpu()			).max() < 1e-2


# (todo: sayakpaul) implement SLOW tests.














"""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 CLIPImageProcessor


class     __UpperCAmelCase(   unittest.TestCase							):




						"""simple docstring"""




						def __init__(   self       ,  snake_case__       ,  snake_case__=7       ,  snake_case__=3       ,  snake_case__=18       ,  snake_case__=30       ,  snake_case__=400       ,  snake_case__=True       ,  snake_case__=None       ,  snake_case__=True       ,  snake_case__=None       ,  snake_case__=True       ,  snake_case__=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]       ,  snake_case__=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]       ,  snake_case__=True       ,  ):
												'''simple docstring'''
												lowercase__				:      int=       size if size is not None else {"shortest_edge": 20}
												lowercase__				:      int=       crop_size if crop_size is not None else {"height": 18, "width": 18}
												lowercase__				:      Union[str, Any]=       parent
												lowercase__				:      Optional[Any]=       batch_size
												lowercase__				:      List[str]=       num_channels
												lowercase__				:      str=       image_size
												lowercase__				:      Optional[int]=       min_resolution
												lowercase__				:      Union[str, Any]=       max_resolution
												lowercase__				:      List[Any]=       do_resize
												lowercase__				:      Any=       size
												lowercase__				:      Optional[Any]=       do_center_crop
												lowercase__				:      List[str]=       crop_size
												lowercase__				:      List[Any]=       do_normalize
												lowercase__				:      Optional[Any]=       image_mean
												lowercase__				:      Dict=       image_std
												lowercase__				:      Dict=       do_convert_rgb




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												return {
												    "do_resize": self.do_resize,
												    "size": self.size,
												    "do_center_crop": self.do_center_crop,
												    "crop_size": self.crop_size,
												    "do_normalize": self.do_normalize,
												    "image_mean": self.image_mean,
												    "image_std": self.image_std,
												    "do_convert_rgb": self.do_convert_rgb,
												}




						def 		UpperCAmelCase_       (   self       ,  snake_case__=False       ,  snake_case__=False       ,  snake_case__=False			):
												'''simple docstring'''
												assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

												if equal_resolution:
																		lowercase__				:      Optional[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:
																		lowercase__				:      Optional[Any]=       []
																		for i in range(self.batch_size			):
																								lowercase__,	lowercase__				:      str=       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
																		lowercase__				:      Dict=       [Image.fromarray(np.moveaxis(snake_case__       ,  0       ,  -1			)			) for x in image_inputs]

												if torchify:
																		lowercase__				:      Tuple=       [torch.from_numpy(snake_case__			) for x in image_inputs]

												return image_inputs


@require_torch
@require_vision
class     __UpperCAmelCase(   SCREAMING_SNAKE_CASE__  ,  unittest.TestCase							):




						"""simple docstring"""




						__lowerCamelCase				       =					CLIPImageProcessor if is_vision_available() else None




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      List[Any]=       CLIPImageProcessingTester(self			)




						@property
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												return self.image_processor_tester.prepare_image_processor_dict()




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      Dict=       self.image_processing_class(**self.image_processor_dict			)
												self.assertTrue(hasattr(snake_case__       ,  "do_resize"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "size"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_center_crop"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "center_crop"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_normalize"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "image_mean"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "image_std"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_convert_rgb"			)			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      List[str]=       self.image_processing_class.from_dict(self.image_processor_dict			)
												self.assertEqual(image_processor.size       ,  {"shortest_edge": 20}			)
												self.assertEqual(image_processor.crop_size       ,  {"height": 18, "width": 18}			)

												lowercase__				:      Dict=       self.image_processing_class.from_dict(self.image_processor_dict       ,  size=42       ,  crop_size=84			)
												self.assertEqual(image_processor.size       ,  {"shortest_edge": 42}			)
												self.assertEqual(image_processor.crop_size       ,  {"height": 84, "width": 84}			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												pass




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# Initialize image_processing
												lowercase__				:      int=       self.image_processing_class(**self.image_processor_dict			)
												# create random PIL images
												lowercase__				:      Optional[Any]=       self.image_processor_tester.prepare_inputs(equal_resolution=snake_case__			)
												for image in image_inputs:
																		self.assertIsInstance(snake_case__       ,  Image.Image			)

												# Test not batched input
												lowercase__				:      List[str]=       image_processing(image_inputs[0]       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )

												# Test batched
												lowercase__				:      Dict=       image_processing(snake_case__       ,  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.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# Initialize image_processing
												lowercase__				:      Any=       self.image_processing_class(**self.image_processor_dict			)
												# create random numpy tensors
												lowercase__				:      Tuple=       self.image_processor_tester.prepare_inputs(equal_resolution=snake_case__       ,  numpify=snake_case__			)
												for image in image_inputs:
																		self.assertIsInstance(snake_case__       ,  np.ndarray			)

												# Test not batched input
												lowercase__				:      Dict=       image_processing(image_inputs[0]       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )

												# Test batched
												lowercase__				:      int=       image_processing(snake_case__       ,  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.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# Initialize image_processing
												lowercase__				:      Optional[Any]=       self.image_processing_class(**self.image_processor_dict			)
												# create random PyTorch tensors
												lowercase__				:      Union[str, Any]=       self.image_processor_tester.prepare_inputs(equal_resolution=snake_case__       ,  torchify=snake_case__			)
												for image in image_inputs:
																		self.assertIsInstance(snake_case__       ,  torch.Tensor			)

												# Test not batched input
												lowercase__				:      Any=       image_processing(image_inputs[0]       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )

												# Test batched
												lowercase__				:      Union[str, Any]=       image_processing(snake_case__       ,  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.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )


@require_torch
@require_vision
class     __UpperCAmelCase(   SCREAMING_SNAKE_CASE__  ,  unittest.TestCase							):




						"""simple docstring"""




						__lowerCamelCase				       =					CLIPImageProcessor if is_vision_available() else None




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      Optional[int]=       CLIPImageProcessingTester(self       ,  num_channels=4			)
												lowercase__				:      Optional[Any]=       3




						@property
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												return self.image_processor_tester.prepare_image_processor_dict()




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      List[str]=       self.image_processing_class(**self.image_processor_dict			)
												self.assertTrue(hasattr(snake_case__       ,  "do_resize"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "size"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_center_crop"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "center_crop"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_normalize"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "image_mean"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "image_std"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_convert_rgb"			)			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												pass




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# Initialize image_processing
												lowercase__				:      int=       self.image_processing_class(**self.image_processor_dict			)
												# create random PIL images
												lowercase__				:      int=       self.image_processor_tester.prepare_inputs(equal_resolution=snake_case__			)
												for image in image_inputs:
																		self.assertIsInstance(snake_case__       ,  Image.Image			)

												# Test not batched input
												lowercase__				:      Optional[int]=       image_processing(image_inputs[0]       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        1,
												        self.expected_encoded_image_num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )

												# Test batched
												lowercase__				:      Any=       image_processing(snake_case__       ,  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.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )






