





'''simple docstring'''







from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
					import torch

if is_tf_available():
					import tensorflow as tf


class 					__a      (lowerCamelCase     ):
							__a					:   Union[str, Any]									=       ["image_processor"]
							__a					:   List[Any]									=       "SamImageProcessor"

							def __init__(							self							:     Optional[int]       ,     __magic_name__							:     Tuple   )					->       Optional[int]:







													"""simple docstring"""
													super().__init__(__magic_name__   )
													UpperCAmelCase_			:      Optional[Any]     						=  self.image_processor
													UpperCAmelCase_			:      Optional[int]     						=  -10
													UpperCAmelCase_			:      Any     						=  self.image_processor.size['''longest_edge''']

							def __call__(							self							:     Tuple       ,     __magic_name__							:     Tuple=None       ,     __magic_name__							:     List[str]=None       ,     __magic_name__							:     int=None       ,     __magic_name__							:     Optional[int]=None       ,     __magic_name__							:     Optional[Union[str, TensorType]] = None       ,     **__magic_name__							:     Dict       ,     )					->       BatchEncoding:







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  self.image_processor(
													    __magic_name__       ,     return_tensors=__magic_name__       ,     **__magic_name__       ,     )

													# pop arguments that are not used in the foward but used nevertheless
													UpperCAmelCase_			:      Union[str, Any]     						=  encoding_image_processor['''original_sizes''']

													if hasattr(__magic_name__       ,     '''numpy'''   ):  # Checks if Torch or TF tensor
																			UpperCAmelCase_			:      Optional[Any]     						=  original_sizes.numpy()

													UpperCAmelCase_						,       UpperCAmelCase_						,       UpperCAmelCase_			:      str     						=  self._check_and_preprocess_points(
													    input_points=__magic_name__       ,     input_labels=__magic_name__       ,     input_boxes=__magic_name__       ,     )

													UpperCAmelCase_			:      List[Any]     						=  self._normalize_and_convert(
													    __magic_name__       ,     __magic_name__       ,     input_points=__magic_name__       ,     input_labels=__magic_name__       ,     input_boxes=__magic_name__       ,     return_tensors=__magic_name__       ,     )

													return encoding_image_processor

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     List[Any]       ,     __magic_name__							:     Union[str, Any]       ,     __magic_name__							:     List[str]=None       ,     __magic_name__							:     List[str]=None       ,     __magic_name__							:     Optional[int]=None       ,     __magic_name__							:     List[Any]="pt"       ,     )					->       Tuple:







													"""simple docstring"""
													if input_points is not None:
																			if len(__magic_name__   ) != len(__magic_name__   ):
																									UpperCAmelCase_			:      Dict     						=  [
																									    self._normalize_coordinates(self.target_size       ,     __magic_name__       ,     original_sizes[0]   ) for point in input_points
																									]
																			else:
																									UpperCAmelCase_			:      int     						=  [
																									    self._normalize_coordinates(self.target_size       ,     __magic_name__       ,     __magic_name__   )
																									    for point, original_size in zip(__magic_name__       ,     __magic_name__   )
																									]
																			# check that all arrays have the same shape
																			if not all(point.shape == input_points[0].shape for point in input_points   ):
																									if input_labels is not None:
																															UpperCAmelCase_						,       UpperCAmelCase_			:      Union[str, Any]     						=  self._pad_points_and_labels(__magic_name__       ,     __magic_name__   )

																			UpperCAmelCase_			:      List[Any]     						=  np.array(__magic_name__   )

													if input_labels is not None:
																			UpperCAmelCase_			:      List[str]     						=  np.array(__magic_name__   )

													if input_boxes is not None:
																			if len(__magic_name__   ) != len(__magic_name__   ):
																									UpperCAmelCase_			:      List[Any]     						=  [
																									    self._normalize_coordinates(self.target_size       ,     __magic_name__       ,     original_sizes[0]       ,     is_bounding_box=__magic_name__   )
																									    for box in input_boxes
																									]
																			else:
																									UpperCAmelCase_			:      Any     						=  [
																									    self._normalize_coordinates(self.target_size       ,     __magic_name__       ,     __magic_name__       ,     is_bounding_box=__magic_name__   )
																									    for box, original_size in zip(__magic_name__       ,     __magic_name__   )
																									]
																			UpperCAmelCase_			:      int     						=  np.array(__magic_name__   )

													if input_boxes is not None:
																			if return_tensors == "pt":
																									UpperCAmelCase_			:      List[str]     						=  torch.from_numpy(__magic_name__   )
																									# boxes batch size of 1 by default
																									UpperCAmelCase_			:      Tuple     						=  input_boxes.unsqueeze(1   ) if len(input_boxes.shape   ) != 3 else input_boxes
																			elif return_tensors == "tf":
																									UpperCAmelCase_			:      Union[str, Any]     						=  tf.convert_to_tensor(__magic_name__   )
																									# boxes batch size of 1 by default
																									UpperCAmelCase_			:      Tuple     						=  tf.expand_dims(__magic_name__       ,     1   ) if len(input_boxes.shape   ) != 3 else input_boxes
																			encoding_image_processor.update({'''input_boxes''': input_boxes}   )
													if input_points is not None:
																			if return_tensors == "pt":
																									UpperCAmelCase_			:      List[Any]     						=  torch.from_numpy(__magic_name__   )
																									# point batch size of 1 by default
																									UpperCAmelCase_			:      Tuple     						=  input_points.unsqueeze(1   ) if len(input_points.shape   ) != 4 else input_points
																			elif return_tensors == "tf":
																									UpperCAmelCase_			:      List[str]     						=  tf.convert_to_tensor(__magic_name__   )
																									# point batch size of 1 by default
																									UpperCAmelCase_			:      str     						=  tf.expand_dims(__magic_name__       ,     1   ) if len(input_points.shape   ) != 4 else input_points
																			encoding_image_processor.update({'''input_points''': input_points}   )
													if input_labels is not None:
																			if return_tensors == "pt":
																									UpperCAmelCase_			:      Dict     						=  torch.from_numpy(__magic_name__   )
																									# point batch size of 1 by default
																									UpperCAmelCase_			:      Any     						=  input_labels.unsqueeze(1   ) if len(input_labels.shape   ) != 3 else input_labels
																			elif return_tensors == "tf":
																									UpperCAmelCase_			:      int     						=  tf.convert_to_tensor(__magic_name__   )
																									# point batch size of 1 by default
																									UpperCAmelCase_			:      Any     						=  tf.expand_dims(__magic_name__       ,     1   ) if len(input_labels.shape   ) != 3 else input_labels
																			encoding_image_processor.update({'''input_labels''': input_labels}   )

													return encoding_image_processor

							def     UpperCAmelCase__	(							self							:     int       ,     __magic_name__							:     Any       ,     __magic_name__							:     Dict   )					->       Dict:







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  max([point.shape[0] for point in input_points]   )
													UpperCAmelCase_			:      Any     						=  []
													for i, point in enumerate(__magic_name__   ):
																			if point.shape[0] != expected_nb_points:
																									UpperCAmelCase_			:      Optional[Any]     						=  np.concatenate(
																									    [point, np.zeros((expected_nb_points - point.shape[0], 2)   ) + self.point_pad_value]       ,     axis=0   )
																									UpperCAmelCase_			:      str     						=  np.append(input_labels[i]       ,     [self.point_pad_value]   )
																			processed_input_points.append(__magic_name__   )
													UpperCAmelCase_			:      Optional[Any]     						=  processed_input_points
													return input_points, input_labels

							def     UpperCAmelCase__	(							self							:     str       ,     __magic_name__							:     int       ,     __magic_name__							:     np.ndarray       ,     __magic_name__							:     Any       ,     __magic_name__							:     Optional[int]=False   )					->       np.ndarray:







													"""simple docstring"""
													UpperCAmelCase_						,       UpperCAmelCase_			:      Any     						=  original_size
													UpperCAmelCase_						,       UpperCAmelCase_			:      Tuple     						=  self.image_processor._get_preprocess_shape(__magic_name__       ,     longest_edge=__magic_name__   )
													UpperCAmelCase_			:      Optional[int]     						=  deepcopy(__magic_name__   ).astype(__magic_name__   )

													if is_bounding_box:
																			UpperCAmelCase_			:      Dict     						=  coords.reshape(-1       ,     2       ,     2   )

													UpperCAmelCase_			:      Optional[Any]     						=  coords[..., 0] * (new_w / old_w)
													UpperCAmelCase_			:      str     						=  coords[..., 1] * (new_h / old_h)

													if is_bounding_box:
																			UpperCAmelCase_			:      List[str]     						=  coords.reshape(-1       ,     4   )

													return coords

							def     UpperCAmelCase__	(							self							:     List[str]       ,     __magic_name__							:     Any=None       ,     __magic_name__							:     Optional[Any]=None       ,     __magic_name__							:     Tuple=None       ,     )					->       Optional[int]:







													"""simple docstring"""
													if input_points is not None:
																			if hasattr(__magic_name__       ,     '''numpy'''   ):  # Checks for TF or Torch tensor
																									UpperCAmelCase_			:      Union[str, Any]     						=  input_points.numpy().tolist()

																			if not isinstance(__magic_name__       ,     __magic_name__   ) or not isinstance(input_points[0]       ,     __magic_name__   ):
																									raise ValueError('''Input points must be a list of list of floating points.'''   )
																			UpperCAmelCase_			:      int     						=  [np.array(__magic_name__   ) for input_point in input_points]
													else:
																			UpperCAmelCase_			:      List[str]     						=  None

													if input_labels is not None:
																			if hasattr(__magic_name__       ,     '''numpy'''   ):
																									UpperCAmelCase_			:      Optional[int]     						=  input_labels.numpy().tolist()

																			if not isinstance(__magic_name__       ,     __magic_name__   ) or not isinstance(input_labels[0]       ,     __magic_name__   ):
																									raise ValueError('''Input labels must be a list of list integers.'''   )
																			UpperCAmelCase_			:      Union[str, Any]     						=  [np.array(__magic_name__   ) for label in input_labels]
													else:
																			UpperCAmelCase_			:      int     						=  None

													if input_boxes is not None:
																			if hasattr(__magic_name__       ,     '''numpy'''   ):
																									UpperCAmelCase_			:      int     						=  input_boxes.numpy().tolist()

																			if (
																			    not isinstance(__magic_name__       ,     __magic_name__   )
																			    or not isinstance(input_boxes[0]       ,     __magic_name__   )
																			    or not isinstance(input_boxes[0][0]       ,     __magic_name__   )
																			):
																									raise ValueError('''Input boxes must be a list of list of list of floating points.'''   )
																			UpperCAmelCase_			:      Any     						=  [np.array(__magic_name__   ).astype(np.floataa   ) for box in input_boxes]
													else:
																			UpperCAmelCase_			:      int     						=  None

													return input_points, input_labels, input_boxes

							@property
							def     UpperCAmelCase__	(							self							:     Union[str, Any]   )					->       List[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[int]     						=  self.image_processor.model_input_names
													return list(dict.fromkeys(__magic_name__   )   )



							def     UpperCAmelCase__	(							self							:     Any       ,     *__magic_name__							:     Optional[int]       ,     **__magic_name__							:     List[str]   )					->       List[Any]:







													"""simple docstring"""
													return self.image_processor.post_process_masks(*__magic_name__       ,     **__magic_name__   )












'''simple docstring'''







import unittest

import numpy as np
import torch

from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()


class 					__a      (unittest.TestCase     ):

							@property
							def     UpperCAmelCase__	(							self							:     Dict   )					->       str:







													"""simple docstring"""
													torch.manual_seed(0   )
													UpperCAmelCase_			:      Optional[Any]     						=  UNetaDModel(
													    block_out_channels=(32, 64)       ,     layers_per_block=2       ,     sample_size=32       ,     in_channels=3       ,     out_channels=3       ,     down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')       ,     up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')       ,     )
													return model



							def     UpperCAmelCase__	(							self							:     Dict   )					->       Tuple:







													"""simple docstring"""
													UpperCAmelCase_			:      List[Any]     						=  self.dummy_uncond_unet
													UpperCAmelCase_			:      Dict     						=  KarrasVeScheduler()

													UpperCAmelCase_			:      Union[str, Any]     						=  KarrasVePipeline(unet=__magic_name__       ,     scheduler=__magic_name__   )
													pipe.to(__magic_name__   )
													pipe.set_progress_bar_config(disable=__magic_name__   )

													UpperCAmelCase_			:      Dict     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      Optional[int]     						=  pipe(num_inference_steps=2       ,     generator=__magic_name__       ,     output_type='''numpy'''   ).images

													UpperCAmelCase_			:      Tuple     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      str     						=  pipe(num_inference_steps=2       ,     generator=__magic_name__       ,     output_type='''numpy'''       ,     return_dict=__magic_name__   )[0]

													UpperCAmelCase_			:      Union[str, Any]     						=  image[0, -3:, -3:, -1]
													UpperCAmelCase_			:      Optional[Any]     						=  image_from_tuple[0, -3:, -3:, -1]

													assert image.shape == (1, 32, 32, 3)
													UpperCAmelCase_			:      Dict     						=  np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]   )

													assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2
													assert np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 1E-2





@slow
@require_torch
class 					__a      (unittest.TestCase     ):

							def     UpperCAmelCase__	(							self							:     int   )					->       Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      List[str]     						=  '''google/ncsnpp-celebahq-256'''
													UpperCAmelCase_			:      List[str]     						=  UNetaDModel.from_pretrained(__magic_name__   )
													UpperCAmelCase_			:      List[Any]     						=  KarrasVeScheduler()

													UpperCAmelCase_			:      Any     						=  KarrasVePipeline(unet=__magic_name__       ,     scheduler=__magic_name__   )
													pipe.to(__magic_name__   )
													pipe.set_progress_bar_config(disable=__magic_name__   )

													UpperCAmelCase_			:      Dict     						=  torch.manual_seed(0   )
													UpperCAmelCase_			:      Optional[Any]     						=  pipe(num_inference_steps=20       ,     generator=__magic_name__       ,     output_type='''numpy'''   ).images

													UpperCAmelCase_			:      Any     						=  image[0, -3:, -3:, -1]
													assert image.shape == (1, 2_56, 2_56, 3)
													UpperCAmelCase_			:      Optional[Any]     						=  np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6]   )

													assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2





