



'''simple docstring'''


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


lowercase_      :				List[str]   					=    logging.get_logger(__name__)







def      SCREAMING_SNAKE_CASE				(				lowercase_    :      np.ndarray ,  lowercase_    :      Union[int, Iterable[int]] ,  lowercase_    :      bool ,  lowercase_    :      int						):
						def constraint_to_multiple_of(lowercase_    :      Union[str, Any] ,  lowercase_    :      Optional[int] ,  lowercase_    :      Optional[int]=0 ,  lowercase_    :      Union[str, Any]=None						):
												lowercase        =							round(val / multiple						) * multiple

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

												if x < min_val:
																		lowercase        =							math.ceil(val / multiple						) * multiple

												return x

						lowercase        =							(output_size, output_size) if isinstance(lowercase_ ,  lowercase_						) else output_size

						lowercase     ,   lowercase        =							get_image_size(lowercase_						)
						lowercase     ,   lowercase        =							output_size

						# determine new height and width
						lowercase        =							output_height / input_height
						lowercase        =							output_width / input_width

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

						lowercase        =							constraint_to_multiple_of(scale_height * input_height ,  multiple=lowercase_						)
						lowercase        =							constraint_to_multiple_of(scale_width * input_width ,  multiple=lowercase_						)

						return (new_height, new_width)




class      __UpperCamelCase       (_UpperCAmelCase			):
	__A			  =					['''pixel_values''']







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






							super().__init__(**_lowerCAmelCase						)
							lowercase        =							size if size is not None else {"""height""": 384, """width""": 384}
							lowercase        =							get_size_dict(_lowerCAmelCase						)
							lowercase        =							do_resize
							lowercase        =							size
							lowercase        =							keep_aspect_ratio
							lowercase        =							ensure_multiple_of
							lowercase        =							resample
							lowercase        =							do_rescale
							lowercase        =							rescale_factor
							lowercase        =							do_normalize
							lowercase        =							image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
							lowercase        =							image_std if image_std is not None else IMAGENET_STANDARD_STD







	def   _a   (    self ,				_lowerCAmelCase ,				_lowerCAmelCase ,				_lowerCAmelCase = False ,				_lowerCAmelCase = 1 ,				_lowerCAmelCase = PILImageResampling.BICUBIC ,				_lowerCAmelCase = None ,				**_lowerCAmelCase ,				)    ->    np.ndarray:
							'''simple docstring'''






							lowercase        =							get_size_dict(_lowerCAmelCase						)
							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()}"""						)
							lowercase        =							get_resize_output_image_size(
							    _lowerCAmelCase ,				output_size=(size["""height"""], size["""width"""]) ,				keep_aspect_ratio=_lowerCAmelCase ,				multiple=_lowerCAmelCase ,				)
							return resize(_lowerCAmelCase ,				size=_lowerCAmelCase ,				resample=_lowerCAmelCase ,				data_format=_lowerCAmelCase ,				**_lowerCAmelCase						)







	def   _a   (    self ,				_lowerCAmelCase ,				_lowerCAmelCase ,				_lowerCAmelCase = None ,				**_lowerCAmelCase ,				)    ->    Optional[Any]:
							'''simple docstring'''






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







	def   _a   (    self ,				_lowerCAmelCase ,				_lowerCAmelCase ,				_lowerCAmelCase ,				_lowerCAmelCase = None ,				**_lowerCAmelCase ,				)    ->    np.ndarray:
							'''simple docstring'''






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







	def   _a   (    self ,				_lowerCAmelCase ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = None ,				_lowerCAmelCase = ChannelDimension.FIRST ,				**_lowerCAmelCase ,				)    ->    PIL.Image.Image:
							'''simple docstring'''






							lowercase        =							do_resize if do_resize is not None else self.do_resize
							lowercase        =							size if size is not None else self.size
							lowercase        =							get_size_dict(_lowerCAmelCase						)
							lowercase        =							keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
							lowercase        =							ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
							lowercase        =							resample if resample is not None else self.resample
							lowercase        =							do_rescale if do_rescale is not None else self.do_rescale
							lowercase        =							rescale_factor if rescale_factor is not None else self.rescale_factor
							lowercase        =							do_normalize if do_normalize is not None else self.do_normalize
							lowercase        =							image_mean if image_mean is not None else self.image_mean
							lowercase        =							image_std if image_std is not None else self.image_std

							lowercase        =							make_list_of_images(_lowerCAmelCase						)

							if not valid_images(_lowerCAmelCase						):
													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.
							lowercase        =							[to_numpy_array(_lowerCAmelCase						) for image in images]

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

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

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

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

							lowercase        =							{"""pixel_values""": images}
							return BatchFeature(data=_lowerCAmelCase ,				tensor_type=_lowerCAmelCase						)







	def   _a   (    self ,				_lowerCAmelCase ,				_lowerCAmelCase = None						)    ->    Union[str, Any]:
							'''simple docstring'''






							lowercase        =							outputs.logits

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

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

													lowercase        =							[]

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

							return semantic_segmentation







'''simple docstring'''


from random import shuffle

import tensorflow as tf
from numpy import array







def      SCREAMING_SNAKE_CASE				(				lowercase_    :      List[str] ,  lowercase_    :      Optional[int]						):
						lowercase        =							int(lowercase_						)
						assert noofclusters < len(lowercase_						)

						# Find out the dimensionality
						lowercase        =							len(vectors[0]						)

						# Will help select random centroids from among the available vectors
						lowercase        =							list(range(len(lowercase_						)						)						)
						shuffle(lowercase_						)

						# GRAPH OF COMPUTATION
						# We initialize a new graph and set it as the default during each run
						# of this algorithm. This ensures that as this function is called
						# multiple times, the default graph doesn't keep getting crowded with
						# unused ops and Variables from previous function calls.

						lowercase        =							tf.Graph()

						with graph.as_default():
												# SESSION OF COMPUTATION

												lowercase        =							tf.Session()

												##CONSTRUCTING THE ELEMENTS OF COMPUTATION

												##First lets ensure we have a Variable vector for each centroid,
												##initialized to one of the vectors from the available data points
												lowercase        =							[
												    tf.Variable(vectors[vector_indices[i]]						) for i in range(lowercase_						)
												]
												##These nodes will assign the centroid Variables the appropriate
												##values
												lowercase        =							tf.placeholder("""float64""" ,  [dim]						)
												lowercase        =							[]
												for centroid in centroids:
																		cent_assigns.append(tf.assign(lowercase_ ,  lowercase_						)						)

												##Variables for cluster assignments of individual vectors(initialized
												##to 0 at first)
												lowercase        =							[tf.Variable(0						) for i in range(len(lowercase_						)						)]
												##These nodes will assign an assignment Variable the appropriate
												##value
												lowercase        =							tf.placeholder("""int32"""						)
												lowercase        =							[]
												for assignment in assignments:
																		cluster_assigns.append(tf.assign(lowercase_ ,  lowercase_						)						)

												##Now lets construct the node that will compute the mean
												# The placeholder for the input
												lowercase        =							tf.placeholder("""float""" ,  [None, dim]						)
												# The Node/op takes the input and computes a mean along the 0th
												# dimension, i.e. the list of input vectors
												lowercase        =							tf.reduce_mean(lowercase_ ,  0						)

												##Node for computing Euclidean distances
												# Placeholders for input
												lowercase        =							tf.placeholder("""float""" ,  [dim]						)
												lowercase        =							tf.placeholder("""float""" ,  [dim]						)
												lowercase        =							tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowercase_ ,  lowercase_						) ,  2						)						)						)

												##This node will figure out which cluster to assign a vector to,
												##based on Euclidean distances of the vector from the centroids.
												# Placeholder for input
												lowercase        =							tf.placeholder("""float""" ,  [noofclusters]						)
												lowercase        =							tf.argmin(lowercase_ ,  0						)

												##INITIALIZING STATE VARIABLES

												##This will help initialization of all Variables defined with respect
												##to the graph. The Variable-initializer should be defined after
												##all the Variables have been constructed, so that each of them
												##will be included in the initialization.
												lowercase        =							tf.initialize_all_variables()

												# Initialize all variables
												sess.run(lowercase_						)

												##CLUSTERING ITERATIONS

												# Now perform the Expectation-Maximization steps of K-Means clustering
												# iterations. To keep things simple, we will only do a set number of
												# iterations, instead of using a Stopping Criterion.
												lowercase        =							100
												for _ in range(lowercase_						):
																		##EXPECTATION STEP
																		##Based on the centroid locations till last iteration, compute
																		##the _expected_ centroid assignments.
																		# Iterate over each vector
																		for vector_n in range(len(lowercase_						)						):
																								lowercase        =							vectors[vector_n]
																								# Compute Euclidean distance between this vector and each
																								# centroid. Remember that this list cannot be named
																								#'centroid_distances', since that is the input to the
																								# cluster assignment node.
																								lowercase        =							[
																								    sess.run(lowercase_ ,  feed_dict={va: vect, va: sess.run(lowercase_						)}						)
																								    for centroid in centroids
																								]
																								# Now use the cluster assignment node, with the distances
																								# as the input
																								lowercase        =							sess.run(
																								    lowercase_ ,  feed_dict={centroid_distances: distances}						)
																								# Now assign the value to the appropriate state variable
																								sess.run(
																								    cluster_assigns[vector_n] ,  feed_dict={assignment_value: assignment}						)

																		##MAXIMIZATION STEP
																		# Based on the expected state computed from the Expectation Step,
																		# compute the locations of the centroids so as to maximize the
																		# overall objective of minimizing within-cluster Sum-of-Squares
																		for cluster_n in range(lowercase_						):
																								# Collect all the vectors assigned to this cluster
																								lowercase        =							[
																								    vectors[i]
																								    for i in range(len(lowercase_						)						)
																								    if sess.run(assignments[i]						) == cluster_n
																								]
																								# Compute new centroid location
																								lowercase        =							sess.run(
																								    lowercase_ ,  feed_dict={mean_input: array(lowercase_						)}						)
																								# Assign value to appropriate variable
																								sess.run(
																								    cent_assigns[cluster_n] ,  feed_dict={centroid_value: new_location}						)

        # Return centroids and assignments
												lowercase        =							sess.run(lowercase_						)
												lowercase        =							sess.run(lowercase_						)
												return centroids, assignments


