




'''simple docstring'''







import gc
import random
import unittest

import numpy as np
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import (
    DiffusionPipeline,
    UnCLIPImageVariationPipeline,
    UnCLIPScheduler,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()


class 			_a  (	__a							,							unittest.TestCase ):
       __a				:     int   				=					UnCLIPImageVariationPipeline
       __a				:     Any   				=					IMAGE_VARIATION_PARAMS - {"""height""", """width""", """guidance_scale"""}
       __a				:     Any   				=					IMAGE_VARIATION_BATCH_PARAMS

       __a				:     Dict   				=					[
           """generator""",
           """return_dict""",
           """decoder_num_inference_steps""",
           """super_res_num_inference_steps""",
       ]
       __a				:     int   				=					False
       @property
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           return 32
       @property
       def     A      (	self						:	Dict				):



           '''simple docstring'''

           return 32
       @property
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           return self.time_input_dim
       @property
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           return self.time_input_dim * 4
       @property
       def     A      (	self						:	int				):



           '''simple docstring'''

           return 100
       @property
       def     A      (	self						:	Any				):



           '''simple docstring'''

           UpperCAmelCase			       =		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)
           return tokenizer
       @property
       def     A      (	self						:	str				):



           '''simple docstring'''

           torch.manual_seed(0				)
           UpperCAmelCase			       =		CLIPTextConfig(
               bos_token_id=0   ,				eos_token_id=2   ,				hidden_size=self.text_embedder_hidden_size   ,				projection_dim=self.text_embedder_hidden_size   ,				intermediate_size=37   ,				layer_norm_eps=1E-05   ,				num_attention_heads=4   ,				num_hidden_layers=5   ,				pad_token_id=1   ,				vocab_size=1_000   ,				)
           return CLIPTextModelWithProjection(lowercase				)
       @property
       def     A      (	self						:	str				):



           '''simple docstring'''

           torch.manual_seed(0				)
           UpperCAmelCase			       =		CLIPVisionConfig(
               hidden_size=self.text_embedder_hidden_size   ,				projection_dim=self.text_embedder_hidden_size   ,				num_hidden_layers=5   ,				num_attention_heads=4   ,				image_size=32   ,				intermediate_size=37   ,				patch_size=1   ,				)
           return CLIPVisionModelWithProjection(lowercase				)
       @property
       def     A      (	self						:	int				):



           '''simple docstring'''

           torch.manual_seed(0				)

           UpperCAmelCase			       =		{
               '''clip_embeddings_dim''': self.text_embedder_hidden_size,
               '''time_embed_dim''': self.time_embed_dim,
               '''cross_attention_dim''': self.cross_attention_dim,
           }

           UpperCAmelCase			       =		UnCLIPTextProjModel(**lowercase				)
           return model
       @property
       def     A      (	self						:	Dict				):



           '''simple docstring'''

           torch.manual_seed(0				)

           UpperCAmelCase			       =		{
               '''sample_size''': 32,
               # RGB in channels
               '''in_channels''': 3,
               # Out channels is double in channels because predicts mean and variance
               '''out_channels''': 6,
               '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
               '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
               '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
               '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
               '''layers_per_block''': 1,
               '''cross_attention_dim''': self.cross_attention_dim,
               '''attention_head_dim''': 4,
               '''resnet_time_scale_shift''': '''scale_shift''',
               '''class_embed_type''': '''identity''',
           }

           UpperCAmelCase			       =		UNetaDConditionModel(**lowercase				)
           return model
       @property
       def     A      (	self						:	str				):



           '''simple docstring'''

           return {
               "sample_size": 64,
               "layers_per_block": 1,
               "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
               "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
               "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
               "in_channels": 6,
               "out_channels": 3,
           }
       @property
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           torch.manual_seed(0				)

           UpperCAmelCase			       =		UNetaDModel(**self.dummy_super_res_kwargs				)
           return model
       @property
       def     A      (	self						:	Union[str, Any]				):



           '''simple docstring'''

           torch.manual_seed(1				)

           UpperCAmelCase			       =		UNetaDModel(**self.dummy_super_res_kwargs				)
           return model
       def     A      (	self						:	Union[str, Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.dummy_decoder
           UpperCAmelCase			       =		self.dummy_text_proj
           UpperCAmelCase			       =		self.dummy_text_encoder
           UpperCAmelCase			       =		self.dummy_tokenizer
           UpperCAmelCase			       =		self.dummy_super_res_first
           UpperCAmelCase			       =		self.dummy_super_res_last

           UpperCAmelCase			       =		UnCLIPScheduler(
               variance_type='''learned_range'''   ,				prediction_type='''epsilon'''   ,				num_train_timesteps=1_000   ,				)

           UpperCAmelCase			       =		UnCLIPScheduler(
               variance_type='''fixed_small_log'''   ,				prediction_type='''epsilon'''   ,				num_train_timesteps=1_000   ,				)

           UpperCAmelCase			       =		CLIPImageProcessor(crop_size=32   ,				size=32				)

           UpperCAmelCase			       =		self.dummy_image_encoder

           return {
               "decoder": decoder,
               "text_encoder": text_encoder,
               "tokenizer": tokenizer,
               "text_proj": text_proj,
               "feature_extractor": feature_extractor,
               "image_encoder": image_encoder,
               "super_res_first": super_res_first,
               "super_res_last": super_res_last,
               "decoder_scheduler": decoder_scheduler,
               "super_res_scheduler": super_res_scheduler,
           }
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	str   ,				lowercase						:	Any=0   ,				lowercase						:	Optional[int]=True				):



           '''simple docstring'''

           UpperCAmelCase			       =		floats_tensor((1, 3, 32, 32)   ,				rng=random.Random(lowercase				)				).to(lowercase				)
           if str(lowercase				).startswith('''mps'''				):
               UpperCAmelCase			       =		torch.manual_seed(lowercase				)
           else:
               UpperCAmelCase			       =		torch.Generator(device=lowercase				).manual_seed(lowercase				)

           if pil_image:
               UpperCAmelCase			       =		input_image * 0.5 + 0.5
               UpperCAmelCase			       =		input_image.clamp(0   ,				1				)
               UpperCAmelCase			       =		input_image.cpu().permute(0   ,				2   ,				3   ,				1				).float().numpy()
               UpperCAmelCase			       =		DiffusionPipeline.numpy_to_pil(lowercase				)[0]

           return {
               "image": input_image,
               "generator": generator,
               "decoder_num_inference_steps": 2,
               "super_res_num_inference_steps": 2,
               "output_type": "np",
           }
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		'''cpu'''

           UpperCAmelCase			       =		self.get_dummy_components()

           UpperCAmelCase			       =		self.pipeline_class(**lowercase				)
           UpperCAmelCase			       =		pipe.to(lowercase				)

           pipe.set_progress_bar_config(disable=lowercase				)

           UpperCAmelCase			       =		self.get_dummy_inputs(lowercase   ,				pil_image=lowercase				)

           UpperCAmelCase			       =		pipe(**lowercase				)
           UpperCAmelCase			       =		output.images

           UpperCAmelCase			       =		self.get_dummy_inputs(lowercase   ,				pil_image=lowercase				)

           UpperCAmelCase			       =		pipe(
               **lowercase   ,				return_dict=lowercase   ,				)[0]

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

           assert image.shape == (1, 64, 64, 3)

           UpperCAmelCase			       =		np.array(
               [
                   0.9997,
                   0.0002,
                   0.9997,
                   0.9997,
                   0.9969,
                   0.0023,
                   0.9997,
                   0.9969,
                   0.9970,
               ]				)

           assert np.abs(image_slice.flatten() - expected_slice				).max() < 1E-2
           assert np.abs(image_from_tuple_slice.flatten() - expected_slice				).max() < 1E-2
       def     A      (	self						:	List[Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		'''cpu'''

           UpperCAmelCase			       =		self.get_dummy_components()

           UpperCAmelCase			       =		self.pipeline_class(**lowercase				)
           UpperCAmelCase			       =		pipe.to(lowercase				)

           pipe.set_progress_bar_config(disable=lowercase				)

           UpperCAmelCase			       =		self.get_dummy_inputs(lowercase   ,				pil_image=lowercase				)

           UpperCAmelCase			       =		pipe(**lowercase				)
           UpperCAmelCase			       =		output.images

           UpperCAmelCase			       =		self.get_dummy_inputs(lowercase   ,				pil_image=lowercase				)

           UpperCAmelCase			       =		pipe(
               **lowercase   ,				return_dict=lowercase   ,				)[0]

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

           assert image.shape == (1, 64, 64, 3)

           UpperCAmelCase			       =		np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971]				)

           assert np.abs(image_slice.flatten() - expected_slice				).max() < 1E-2
           assert np.abs(image_from_tuple_slice.flatten() - expected_slice				).max() < 1E-2
       def     A      (	self						:	int				):



           '''simple docstring'''

           UpperCAmelCase			       =		'''cpu'''

           UpperCAmelCase			       =		self.get_dummy_components()

           UpperCAmelCase			       =		self.pipeline_class(**lowercase				)
           UpperCAmelCase			       =		pipe.to(lowercase				)

           pipe.set_progress_bar_config(disable=lowercase				)

           UpperCAmelCase			       =		self.get_dummy_inputs(lowercase   ,				pil_image=lowercase				)
           UpperCAmelCase			       =		[
               pipeline_inputs['''image'''],
               pipeline_inputs['''image'''],
           ]

           UpperCAmelCase			       =		pipe(**lowercase				)
           UpperCAmelCase			       =		output.images

           UpperCAmelCase			       =		self.get_dummy_inputs(lowercase   ,				pil_image=lowercase				)
           UpperCAmelCase			       =		[
               tuple_pipeline_inputs['''image'''],
               tuple_pipeline_inputs['''image'''],
           ]

           UpperCAmelCase			       =		pipe(
               **lowercase   ,				return_dict=lowercase   ,				)[0]

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

           assert image.shape == (2, 64, 64, 3)

           UpperCAmelCase			       =		np.array(
               [
                   0.9997,
                   0.9989,
                   0.0008,
                   0.0021,
                   0.9960,
                   0.0018,
                   0.0014,
                   0.0002,
                   0.9933,
               ]				)

           assert np.abs(image_slice.flatten() - expected_slice				).max() < 1E-2
           assert np.abs(image_from_tuple_slice.flatten() - expected_slice				).max() < 1E-2
       def     A      (	self						:	str				):



           '''simple docstring'''

           UpperCAmelCase			       =		torch.device('''cpu'''				)


           class 			_a  :
                  __a				:     Optional[Any]   				=					1






           UpperCAmelCase			       =		self.get_dummy_components()

           UpperCAmelCase			       =		self.pipeline_class(**lowercase				)
           UpperCAmelCase			       =		pipe.to(lowercase				)

           pipe.set_progress_bar_config(disable=lowercase				)

           UpperCAmelCase			       =		torch.Generator(device=lowercase				).manual_seed(0				)
           UpperCAmelCase			       =		pipe.decoder.dtype
           UpperCAmelCase			       =		1

           UpperCAmelCase			       =		(
               batch_size,
               pipe.decoder.config.in_channels,
               pipe.decoder.config.sample_size,
               pipe.decoder.config.sample_size,
           )
           UpperCAmelCase			       =		pipe.prepare_latents(
               lowercase   ,				dtype=lowercase   ,				device=lowercase   ,				generator=lowercase   ,				latents=lowercase   ,				scheduler=DummyScheduler()				)

           UpperCAmelCase			       =		(
               batch_size,
               pipe.super_res_first.config.in_channels // 2,
               pipe.super_res_first.config.sample_size,
               pipe.super_res_first.config.sample_size,
           )
           UpperCAmelCase			       =		pipe.prepare_latents(
               lowercase   ,				dtype=lowercase   ,				device=lowercase   ,				generator=lowercase   ,				latents=lowercase   ,				scheduler=DummyScheduler()				)

           UpperCAmelCase			       =		self.get_dummy_inputs(lowercase   ,				pil_image=lowercase				)

           UpperCAmelCase			       =		pipe(
               **lowercase   ,				decoder_latents=lowercase   ,				super_res_latents=lowercase				).images

           UpperCAmelCase			       =		self.get_dummy_inputs(lowercase   ,				pil_image=lowercase				)
           # Don't pass image, instead pass embedding
           UpperCAmelCase			       =		pipeline_inputs.pop('''image'''				)
           UpperCAmelCase			       =		pipe.image_encoder(lowercase				).image_embeds

           UpperCAmelCase			       =		pipe(
               **lowercase   ,				decoder_latents=lowercase   ,				super_res_latents=lowercase   ,				image_embeddings=lowercase   ,				).images

           # make sure passing text embeddings manually is identical
           assert np.abs(img_out_a - img_out_a				).max() < 1E-4
       @skip_mps
       def     A      (	self						:	Any				):



           '''simple docstring'''

           UpperCAmelCase			       =		torch_device == '''cpu'''

           # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor
           UpperCAmelCase			       =		1E-2

           self._test_attention_slicing_forward_pass(
               test_max_difference=lowercase   ,				expected_max_diff=lowercase				)
       @skip_mps
       def     A      (	self						:	int				):



           '''simple docstring'''

           UpperCAmelCase			       =		torch_device == '''cpu'''
           UpperCAmelCase			       =		True
           UpperCAmelCase			       =		[
               '''decoder_num_inference_steps''',
               '''super_res_num_inference_steps''',
           ]

           self._test_inference_batch_single_identical(
               test_max_difference=lowercase   ,				relax_max_difference=lowercase   ,				additional_params_copy_to_batched_inputs=lowercase   ,				)
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           UpperCAmelCase			       =		[
               '''decoder_num_inference_steps''',
               '''super_res_num_inference_steps''',
           ]

           if torch_device == "mps":
               # TODO: MPS errors with larger batch sizes
               UpperCAmelCase			       =		[2, 3]
               self._test_inference_batch_consistent(
                   batch_sizes=lowercase   ,				additional_params_copy_to_batched_inputs=lowercase   ,				)
           else:
               self._test_inference_batch_consistent(
                   additional_params_copy_to_batched_inputs=lowercase				)
       @skip_mps
       def     A      (	self						:	Any				):



           '''simple docstring'''

           return super().test_dict_tuple_outputs_equivalent()
       @skip_mps
       def     A      (	self						:	List[str]				):



           '''simple docstring'''

           return super().test_save_load_local()







       @skip_mps
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           return super().test_save_load_optional_components()






@slow
@require_torch_gpu
class 			_a  (	unittest.TestCase ):
       def     A      (	self						:	List[Any]				):



           '''simple docstring'''

           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()







       def     A      (	self						:	int				):



           '''simple docstring'''

           UpperCAmelCase			       =		load_image(
               '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png'''				)
           UpperCAmelCase			       =		load_numpy(
               '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
               '''/unclip/karlo_v1_alpha_cat_variation_fp16.npy'''				)

           UpperCAmelCase			       =		UnCLIPImageVariationPipeline.from_pretrained(
               '''kakaobrain/karlo-v1-alpha-image-variations'''   ,				torch_dtype=torch.floataa				)
           UpperCAmelCase			       =		pipeline.to(lowercase				)
           pipeline.set_progress_bar_config(disable=lowercase				)

           UpperCAmelCase			       =		torch.Generator(device='''cpu'''				).manual_seed(0				)
           UpperCAmelCase			       =		pipeline(
               lowercase   ,				generator=lowercase   ,				output_type='''np'''   ,				)

           UpperCAmelCase			       =		output.images[0]

           assert image.shape == (256, 256, 3)

           assert_mean_pixel_difference(lowercase   ,				lowercase   ,				15				)










'''simple docstring'''







from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
   import torch


A     =logging.get_logger(__name__)


class 			_a  (	__a ):
       __a				:     str   				=					["""pixel_values"""]
       def __init__(	self						:	Optional[int]   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Dict[str, int]] = None   ,				lowercase						:	PILImageResampling = PILImageResampling.BILINEAR   ,				lowercase						:	bool = True   ,				lowercase						:	Dict[str, int] = None   ,				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						:	Union[str, Any]   ,				):



           '''simple docstring'''

           super().__init__(**lowercase				)
           UpperCAmelCase			       =		size if size is not None else {'''shortest_edge''': 256}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				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 IMAGENET_STANDARD_MEAN
           UpperCAmelCase			       =		image_std if image_std is not None else IMAGENET_STANDARD_STD
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	PILImageResampling = PILImageResampling.BICUBIC   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Any   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           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(lowercase   ,				size=size['''shortest_edge''']   ,				default_to_square=lowercase				)
           return resize(lowercase   ,				size=lowercase   ,				resample=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	int   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase				)
           if "height" not in size or "width" not in size:
               raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"				)
           return center_crop(lowercase   ,				size=(size['''height'''], size['''width'''])   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Tuple   ,				lowercase						:	np.ndarray   ,				lowercase						:	float   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	List[str]				):



           '''simple docstring'''

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



           '''simple docstring'''

           return normalize(lowercase   ,				mean=lowercase   ,				std=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	ImageInput   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	PILImageResampling = None   ,				lowercase						:	bool = None   ,				lowercase						:	Dict[str, int] = 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						:	Union[str, ChannelDimension] = ChannelDimension.FIRST   ,				**lowercase						:	Dict   ,				):



           '''simple docstring'''

           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(lowercase   ,				default_to_square=lowercase				)
           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(lowercase   ,				param_name='''crop_size'''				)
           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			       =		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:
               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.'''				)

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

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

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

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

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

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

           UpperCAmelCase			       =		{'''pixel_values''': images}
           return BatchFeature(data=lowercase   ,				tensor_type=lowercase				)







       def     A      (	self						:	Tuple   ,				lowercase						:	str   ,				lowercase						:	List[Tuple] = None				):



           '''simple docstring'''

           UpperCAmelCase			       =		outputs.logits

           # Resize logits and compute semantic segmentation maps
           if target_sizes is not None:
               if len(lowercase				) != len(lowercase				):
                   raise ValueError(
                       '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''				)

               if is_torch_tensor(lowercase				):
                   UpperCAmelCase			       =		target_sizes.numpy()

               UpperCAmelCase			       =		[]

               for idx in range(len(lowercase				)				):
                   UpperCAmelCase			       =		torch.nn.functional.interpolate(
                       logits[idx].unsqueeze(dim=0				)   ,				size=target_sizes[idx]   ,				mode='''bilinear'''   ,				align_corners=lowercase				)
                   UpperCAmelCase			       =		resized_logits[0].argmax(dim=0				)
                   semantic_segmentation.append(lowercase				)
           else:
               UpperCAmelCase			       =		logits.argmax(dim=1				)
               UpperCAmelCase			       =		[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]				)]

           return semantic_segmentation




