





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

import numpy as np

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


if is_torch_available():
	import torch

if is_vision_available():
	import PIL


lowerCAmelCase_    =				logging.get_logger(__name__)






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase )		->						Tuple[int, int]:






				"""simple docstring"""


				def constraint_to_multiple_of(_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase=0 ,				_UpperCamelCase=None ):
								snake_case_						:    List[Any]				=  round(val / multiple ) * multiple

								if max_val is not None and x > max_val:
												snake_case_						:    Tuple				=  math.floor(val / multiple ) * multiple

								if x < min_val:
												snake_case_						:    Union[str, Any]				=  math.ceil(val / multiple ) * multiple

								return x

				snake_case_						:    Optional[int]				=  (output_size, output_size) if isinstance(_UpperCamelCase ,				_UpperCamelCase ) else output_size

				snake_case_			,							snake_case_						:    List[str]				=  get_image_size(_UpperCamelCase )
				snake_case_			,							snake_case_						:    Dict				=  output_size

				# determine new height and width
				snake_case_						:    Any				=  output_height / input_height
				snake_case_						:    Any				=  output_width / input_width

				if keep_aspect_ratio:
								# scale as little as possible
								if abs(1 - scale_width ) < abs(1 - scale_height ):
												# fit width
												snake_case_						:    str				=  scale_width
								else:
												# fit height
												snake_case_						:    int				=  scale_height

				snake_case_						:    Any				=  constraint_to_multiple_of(scale_height * input_height ,				multiple=_UpperCamelCase )
				snake_case_						:    str				=  constraint_to_multiple_of(scale_width * input_width ,				multiple=_UpperCamelCase )

				return (new_height, new_width)





class 					__lowerCAmelCase       (			_a     ):
			lowerCamelCase_     :     Any       			=      ['''pixel_values''']






			def __init__(self					,							__magic_name__ = True					,							__magic_name__ = None					,							__magic_name__ = PILImageResampling.BILINEAR					,							__magic_name__ = False					,							__magic_name__ = 1					,							__magic_name__ = True					,							__magic_name__ = 1 / 255					,							__magic_name__ = True					,							__magic_name__ = None					,							__magic_name__ = None					,							**__magic_name__					,							)     ->   None:


							'''simple docstring'''



							super().__init__(**__magic_name__    )
							snake_case_						:    List[Any]				=  size if size is not None else {'''height''': 384, '''width''': 384}
							snake_case_						:    List[str]				=  get_size_dict(__magic_name__    )
							snake_case_						:    Dict				=  do_resize
							snake_case_						:    Optional[int]				=  size
							snake_case_						:    int				=  keep_aspect_ratio
							snake_case_						:    Optional[Any]				=  ensure_multiple_of
							snake_case_						:    str				=  resample
							snake_case_						:    Union[str, Any]				=  do_rescale
							snake_case_						:    List[Any]				=  rescale_factor
							snake_case_						:    List[str]				=  do_normalize
							snake_case_						:    Optional[int]				=  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
							snake_case_						:    Optional[int]				=  image_std if image_std is not None else IMAGENET_STANDARD_STD






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__ = False					,							__magic_name__ = 1					,							__magic_name__ = PILImageResampling.BICUBIC					,							__magic_name__ = None					,							**__magic_name__					,							)     ->   np.ndarray:


							'''simple docstring'''



							snake_case_						:    Optional[int]				=  get_size_dict(__magic_name__    )
							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()}'''    )
							snake_case_						:    int				=  get_resize_output_image_size(
							    __magic_name__					,							output_size=(size['''height'''], size['''width'''])					,							keep_aspect_ratio=__magic_name__					,							multiple=__magic_name__					,							)
							return resize(__magic_name__					,							size=__magic_name__					,							resample=__magic_name__					,							data_format=__magic_name__					,							**__magic_name__    )






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__ = None					,							**__magic_name__					,							)     ->   Optional[Any]:


							'''simple docstring'''



							return rescale(__magic_name__					,							scale=__magic_name__					,							data_format=__magic_name__					,							**__magic_name__    )






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__					,							__magic_name__ = None					,							**__magic_name__					,							)     ->   np.ndarray:


							'''simple docstring'''



							return normalize(__magic_name__					,							mean=__magic_name__					,							std=__magic_name__					,							data_format=__magic_name__					,							**__magic_name__    )






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = None					,							__magic_name__ = ChannelDimension.FIRST					,							**__magic_name__					,							)     ->   PIL.Image.Image:


							'''simple docstring'''



							snake_case_						:    Dict				=  do_resize if do_resize is not None else self.do_resize
							snake_case_						:    int				=  size if size is not None else self.size
							snake_case_						:    List[str]				=  get_size_dict(__magic_name__    )
							snake_case_						:    str				=  keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
							snake_case_						:    Any				=  ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
							snake_case_						:    int				=  resample if resample is not None else self.resample
							snake_case_						:    str				=  do_rescale if do_rescale is not None else self.do_rescale
							snake_case_						:    List[Any]				=  rescale_factor if rescale_factor is not None else self.rescale_factor
							snake_case_						:    Optional[int]				=  do_normalize if do_normalize is not None else self.do_normalize
							snake_case_						:    List[str]				=  image_mean if image_mean is not None else self.image_mean
							snake_case_						:    Dict				=  image_std if image_std is not None else self.image_std

							snake_case_						:    int				=  make_list_of_images(__magic_name__    )

							if not valid_images(__magic_name__    ):
											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 or resample is None:
											raise ValueError('''Size and resample 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_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.
							snake_case_						:    Optional[int]				=  [to_numpy_array(__magic_name__    ) for image in images]

							if do_resize:
											snake_case_						:    Any				=  [self.resize(image=__magic_name__					,							size=__magic_name__					,							resample=__magic_name__    ) for image in images]

							if do_rescale:
											snake_case_						:    Tuple				=  [self.rescale(image=__magic_name__					,							scale=__magic_name__    ) for image in images]

							if do_normalize:
											snake_case_						:    Optional[int]				=  [self.normalize(image=__magic_name__					,							mean=__magic_name__					,							std=__magic_name__    ) for image in images]

							snake_case_						:    List[str]				=  [to_channel_dimension_format(__magic_name__					,							__magic_name__    ) for image in images]

							snake_case_						:    Dict				=  {'''pixel_values''': images}
							return BatchFeature(data=__magic_name__					,							tensor_type=__magic_name__    )






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__ = None    )     ->   Any:


							'''simple docstring'''



							snake_case_						:    Optional[int]				=  outputs.logits

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

											if is_torch_tensor(__magic_name__    ):
															snake_case_						:    List[Any]				=  target_sizes.numpy()

											snake_case_						:    Union[str, Any]				=  []

											for idx in range(len(__magic_name__    )    ):
															snake_case_						:    int				=  torch.nn.functional.interpolate(
															    logits[idx].unsqueeze(dim=0    )					,							size=target_sizes[idx]					,							mode='''bilinear'''					,							align_corners=__magic_name__    )
															snake_case_						:    Any				=  resized_logits[0].argmax(dim=0    )
															semantic_segmentation.append(__magic_name__    )
							else:
											snake_case_						:    str				=  logits.argmax(dim=1    )
											snake_case_						:    int				=  [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
