




"""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,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
		import PIL

if is_torch_available():
		import torch


a            =							logging.get_logger(__name__)






class 					SCREAMING_SNAKE_CASE__    (    _a    ):
						_a			  =  ['pixel_values']


						def __init__(							self :	Any  ,  lowerCAmelCase :	bool = True  ,  lowerCAmelCase :	Dict[str, int] = None  ,  lowerCAmelCase :	PILImageResampling = PILImageResampling.BILINEAR  ,  lowerCAmelCase :	bool = True  ,  lowerCAmelCase :	Union[int, float] = 1 / 255  ,  lowerCAmelCase :	bool = True  ,  lowerCAmelCase :	Dict[str, int] = None  ,  lowerCAmelCase :	bool = True  ,  **lowerCAmelCase :	Dict  ,  ):
										super().__init__(**SCREAMING_SNAKE_CASE_    )
										lowerCAmelCase              = size if size is not None else {"""shortest_edge""": 224}
										lowerCAmelCase              = get_size_dict(SCREAMING_SNAKE_CASE_  ,  default_to_square=SCREAMING_SNAKE_CASE_    )
										lowerCAmelCase              = crop_size if crop_size is not None else {"""height""": 256, """width""": 256}
										lowerCAmelCase              = get_size_dict(SCREAMING_SNAKE_CASE_  ,  param_name="""crop_size"""    )

										lowerCAmelCase              = do_resize
										lowerCAmelCase              = size
										lowerCAmelCase              = resample
										lowerCAmelCase              = do_rescale
										lowerCAmelCase              = rescale_factor
										lowerCAmelCase              = do_center_crop
										lowerCAmelCase              = crop_size
										lowerCAmelCase              = do_flip_channel_order


						def      __lowercase       (							self :	List[str]  ,  lowerCAmelCase :	np.ndarray  ,  lowerCAmelCase :	Dict[str, int]  ,  lowerCAmelCase :	PILImageResampling = PIL.Image.BILINEAR  ,  lowerCAmelCase :	Optional[Union[str, ChannelDimension]] = None  ,  **lowerCAmelCase :	str  ,  ):
										lowerCAmelCase              = get_size_dict(SCREAMING_SNAKE_CASE_  ,  default_to_square=SCREAMING_SNAKE_CASE_    )
										if "shortest_edge" not in size:
														raise ValueError(f'''The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}'''    )
										lowerCAmelCase              = get_resize_output_image_size(SCREAMING_SNAKE_CASE_  ,  size=size["""shortest_edge"""]  ,  default_to_square=SCREAMING_SNAKE_CASE_    )
										return resize(SCREAMING_SNAKE_CASE_  ,  size=SCREAMING_SNAKE_CASE_  ,  resample=SCREAMING_SNAKE_CASE_  ,  data_format=SCREAMING_SNAKE_CASE_  ,  **SCREAMING_SNAKE_CASE_    )


						def      __lowercase       (							self :	Any  ,  lowerCAmelCase :	np.ndarray  ,  lowerCAmelCase :	Dict[str, int]  ,  lowerCAmelCase :	Optional[Union[str, ChannelDimension]] = None  ,  **lowerCAmelCase :	Optional[Any]  ,  ):
										lowerCAmelCase              = get_size_dict(SCREAMING_SNAKE_CASE_    )
										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()}'''    )
										return center_crop(SCREAMING_SNAKE_CASE_  ,  size=(size["""height"""], size["""width"""])  ,  data_format=SCREAMING_SNAKE_CASE_  ,  **SCREAMING_SNAKE_CASE_    )


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


						def      __lowercase       (							self :	Tuple  ,  lowerCAmelCase :	np.ndarray  ,  lowerCAmelCase :	Optional[Union[str, ChannelDimension]] = None    ):
										return flip_channel_order(SCREAMING_SNAKE_CASE_  ,  data_format=SCREAMING_SNAKE_CASE_    )


						def      __lowercase       (							self :	int  ,  lowerCAmelCase :	ImageInput  ,  lowerCAmelCase :	bool = None  ,  lowerCAmelCase :	Dict[str, int] = None  ,  lowerCAmelCase :	PILImageResampling = None  ,  lowerCAmelCase :	bool = None  ,  lowerCAmelCase :	float = None  ,  lowerCAmelCase :	bool = None  ,  lowerCAmelCase :	Dict[str, int] = None  ,  lowerCAmelCase :	bool = None  ,  lowerCAmelCase :	Optional[Union[str, TensorType]] = None  ,  lowerCAmelCase :	ChannelDimension = ChannelDimension.FIRST  ,  **lowerCAmelCase :	Dict  ,  ):
										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_center_crop if do_center_crop is not None else self.do_center_crop
										lowerCAmelCase              = (
										    do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
										)

										lowerCAmelCase              = size if size is not None else self.size
										lowerCAmelCase              = get_size_dict(SCREAMING_SNAKE_CASE_  ,  default_to_square=SCREAMING_SNAKE_CASE_    )
										lowerCAmelCase              = crop_size if crop_size is not None else self.crop_size
										lowerCAmelCase              = get_size_dict(SCREAMING_SNAKE_CASE_  ,  param_name="""crop_size"""    )

										lowerCAmelCase              = make_list_of_images(SCREAMING_SNAKE_CASE_    )

										if not valid_images(SCREAMING_SNAKE_CASE_    ):
														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_rescale and rescale_factor is None:
														raise ValueError("""Rescale factor must be specified if do_rescale is True."""    )

										if do_center_crop and crop_size is None:
														raise ValueError("""Crop size must be specified if do_center_crop is True."""    )

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

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

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

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

										# the pretrained checkpoints assume images are BGR, not RGB
										if do_flip_channel_order:
														lowerCAmelCase              = [self.flip_channel_order(image=SCREAMING_SNAKE_CASE_    ) for image in images]

										lowerCAmelCase              = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_  ,  SCREAMING_SNAKE_CASE_    ) for image in images]

										lowerCAmelCase              = {"""pixel_values""": images}
										return BatchFeature(data=SCREAMING_SNAKE_CASE_  ,  tensor_type=SCREAMING_SNAKE_CASE_    )




						def      __lowercase       (							self :	Union[str, Any]  ,  lowerCAmelCase :	str  ,  lowerCAmelCase :	List[Tuple] = None    ):
										lowerCAmelCase              = outputs.logits

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

														if is_torch_tensor(SCREAMING_SNAKE_CASE_    ):
																		lowerCAmelCase              = target_sizes.numpy()

														lowerCAmelCase              = []

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

										return semantic_segmentation







from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
						if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')):
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline
else:
						from .pipeline_unclip import UnCLIPPipeline
						from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline
						from .text_proj import UnCLIPTextProjModel




