



"""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        __snake_case       (	_a):
  snake_case__				:   Union[str, Any]  			=						["image_processor"]
  snake_case__				:   Dict  			=						"SamImageProcessor"




  def __init__( self     :						List[str]						,					__lowerCAmelCase     :						Union[str, Any]		):






         """simple docstring"""






         super().__init__(UpperCamelCase__		)
         _lowerCamelCase						:				Any    			= self.image_processor
         _lowerCamelCase						:				Optional[Any]    			= -1_0
         _lowerCamelCase						:				Union[str, Any]    			= self.image_processor.size['''longest_edge''']




  def __call__( self     :						Optional[int]						,					__lowerCAmelCase     :						Optional[int]=None						,					__lowerCAmelCase     :						str=None						,					__lowerCAmelCase     :						str=None						,					__lowerCAmelCase     :						Optional[Any]=None						,					__lowerCAmelCase     :						Optional[Union[str, TensorType]] = None						,					**__lowerCAmelCase     :						Union[str, Any]						,					):






         """simple docstring"""






         _lowerCamelCase						:				List[str]    			= self.image_processor(
             UpperCamelCase__						,					return_tensors=UpperCamelCase__						,					**UpperCamelCase__						,					)

         # pop arguments that are not used in the foward but used nevertheless
         _lowerCamelCase						:				List[str]    			= encoding_image_processor['''original_sizes''']

         if hasattr(UpperCamelCase__						,					'''numpy'''		):  # Checks if Torch or TF tensor
                _lowerCamelCase						:				int    			= original_sizes.numpy()

         _lowerCamelCase			,    _lowerCamelCase			,    _lowerCamelCase						:				int    			= self._check_and_preprocess_points(
             input_points=UpperCamelCase__						,					input_labels=UpperCamelCase__						,					input_boxes=UpperCamelCase__						,					)

         _lowerCamelCase						:				Optional[int]    			= self._normalize_and_convert(
             UpperCamelCase__						,					UpperCamelCase__						,					input_points=UpperCamelCase__						,					input_labels=UpperCamelCase__						,					input_boxes=UpperCamelCase__						,					return_tensors=UpperCamelCase__						,					)

         return encoding_image_processor




  def 						SCREAMING_SNAKE_CASE				( self     :						str						,					__lowerCAmelCase     :						List[str]						,					__lowerCAmelCase     :						Any						,					__lowerCAmelCase     :						Optional[int]=None						,					__lowerCAmelCase     :						Optional[int]=None						,					__lowerCAmelCase     :						Tuple=None						,					__lowerCAmelCase     :						Any="pt"						,					):






         """simple docstring"""






         if input_points is not None:
                if len(UpperCamelCase__		) != len(UpperCamelCase__		):
                       _lowerCamelCase						:				int    			= [
                           self._normalize_coordinates(self.target_size						,					UpperCamelCase__						,					original_sizes[0]		) for point in input_points
                       ]
                else:
                       _lowerCamelCase						:				Tuple    			= [
                           self._normalize_coordinates(self.target_size						,					UpperCamelCase__						,					UpperCamelCase__		)
                           for point, original_size in zip(UpperCamelCase__						,					UpperCamelCase__		)
                       ]
                # 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:
                              _lowerCamelCase			,    _lowerCamelCase						:				Tuple    			= self._pad_points_and_labels(UpperCamelCase__						,					UpperCamelCase__		)

                _lowerCamelCase						:				List[Any]    			= np.array(UpperCamelCase__		)

         if input_labels is not None:
                _lowerCamelCase						:				str    			= np.array(UpperCamelCase__		)

         if input_boxes is not None:
                if len(UpperCamelCase__		) != len(UpperCamelCase__		):
                       _lowerCamelCase						:				int    			= [
                           self._normalize_coordinates(self.target_size						,					UpperCamelCase__						,					original_sizes[0]						,					is_bounding_box=UpperCamelCase__		)
                           for box in input_boxes
                       ]
                else:
                       _lowerCamelCase						:				str    			= [
                           self._normalize_coordinates(self.target_size						,					UpperCamelCase__						,					UpperCamelCase__						,					is_bounding_box=UpperCamelCase__		)
                           for box, original_size in zip(UpperCamelCase__						,					UpperCamelCase__		)
                       ]
                _lowerCamelCase						:				Tuple    			= np.array(UpperCamelCase__		)

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

         return encoding_image_processor




  def 						SCREAMING_SNAKE_CASE				( self     :						Any						,					__lowerCAmelCase     :						Optional[Any]						,					__lowerCAmelCase     :						List[Any]		):






         """simple docstring"""






         _lowerCamelCase						:				Optional[Any]    			= max([point.shape[0] for point in input_points]		)
         _lowerCamelCase						:				List[str]    			= []
         for i, point in enumerate(UpperCamelCase__		):
                if point.shape[0] != expected_nb_points:
                       _lowerCamelCase						:				Dict    			= np.concatenate(
                           [point, np.zeros((expected_nb_points - point.shape[0], 2)		) + self.point_pad_value]						,					axis=0		)
                       _lowerCamelCase						:				Any    			= np.append(input_labels[i]						,					[self.point_pad_value]		)
                processed_input_points.append(UpperCamelCase__		)
         _lowerCamelCase						:				Tuple    			= processed_input_points
         return input_points, input_labels




  def 						SCREAMING_SNAKE_CASE				( self     :						Tuple						,					__lowerCAmelCase     :						int						,					__lowerCAmelCase     :						np.ndarray						,					__lowerCAmelCase     :						Optional[Any]						,					__lowerCAmelCase     :						int=False		):






         """simple docstring"""






         _lowerCamelCase			,    _lowerCamelCase						:				Optional[Any]    			= original_size
         _lowerCamelCase			,    _lowerCamelCase						:				Union[str, Any]    			= self.image_processor._get_preprocess_shape(UpperCamelCase__						,					longest_edge=UpperCamelCase__		)
         _lowerCamelCase						:				Any    			= deepcopy(UpperCamelCase__		).astype(UpperCamelCase__		)

         if is_bounding_box:
                _lowerCamelCase						:				int    			= coords.reshape(-1						,					2						,					2		)

         _lowerCamelCase						:				Dict    			= coords[..., 0] * (new_w / old_w)
         _lowerCamelCase						:				Dict    			= coords[..., 1] * (new_h / old_h)

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

         return coords




  def 						SCREAMING_SNAKE_CASE				( self     :						List[Any]						,					__lowerCAmelCase     :						List[Any]=None						,					__lowerCAmelCase     :						Optional[int]=None						,					__lowerCAmelCase     :						Optional[int]=None						,					):






         """simple docstring"""






         if input_points is not None:
                if hasattr(UpperCamelCase__						,					'''numpy'''		):  # Checks for TF or Torch tensor
                       _lowerCamelCase						:				str    			= input_points.numpy().tolist()

                if not isinstance(UpperCamelCase__						,					UpperCamelCase__		) or not isinstance(input_points[0]						,					UpperCamelCase__		):
                       raise ValueError('''Input points must be a list of list of floating points.'''		)
                _lowerCamelCase						:				Any    			= [np.array(UpperCamelCase__		) for input_point in input_points]
         else:
                _lowerCamelCase						:				Dict    			= None

         if input_labels is not None:
                if hasattr(UpperCamelCase__						,					'''numpy'''		):
                       _lowerCamelCase						:				Union[str, Any]    			= input_labels.numpy().tolist()

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

         if input_boxes is not None:
                if hasattr(UpperCamelCase__						,					'''numpy'''		):
                       _lowerCamelCase						:				Optional[int]    			= input_boxes.numpy().tolist()

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

         return input_points, input_labels, input_boxes




  @property
  def 						SCREAMING_SNAKE_CASE				( self     :						Tuple		):






         """simple docstring"""






         _lowerCamelCase						:				str    			= self.image_processor.model_input_names
         return list(dict.fromkeys(UpperCamelCase__		)		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Optional[int]						,					*__lowerCAmelCase     :						List[Any]						,					**__lowerCAmelCase     :						Optional[Any]		):






         """simple docstring"""






         return self.image_processor.post_process_masks(*UpperCamelCase__						,					**UpperCamelCase__		)







'''simple docstring'''


from dataclasses import dataclass
from typing import Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin

@dataclass
class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  None

class  SCREAMING_SNAKE_CASE (  _a   ,						_a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  2






    @register_to_config
    def __init__(  self      :					Union[str, Any]  ,						UpperCamelCase__      :					float = 0.0_2  ,						UpperCamelCase__      :					float = 1_0_0  ,						UpperCamelCase__      :					float = 1.0_0_7  ,						UpperCamelCase__      :					float = 8_0  ,						UpperCamelCase__      :					float = 0.0_5  ,						UpperCamelCase__      :					float = 5_0  ,						):


       """simple docstring"""







       UpperCamelCase					=  sigma_max

       # setable values
       UpperCamelCase					=  None
       UpperCamelCase					=  None
       UpperCamelCase					=  None  # sigma(t_i)






    def  A       (  self      :					str  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					Optional[int] = None ):


       """simple docstring"""







       return sample






    def  A       (  self      :					Union[str, Any]  ,						UpperCamelCase__      :					int  ,						UpperCamelCase__      :					Union[str, torch.device] = None ):


       """simple docstring"""







       UpperCamelCase					=  num_inference_steps
       UpperCamelCase					=  np.arange(0  ,						self.num_inference_steps )[::-1].copy()
       UpperCamelCase					=  torch.from_numpy(UpperCamelCase__ ).to(UpperCamelCase__ )
       UpperCamelCase					=  [
           (
               self.config.sigma_max**2
               * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1))
           )
           for i in self.timesteps
       ]
       UpperCamelCase					=  torch.tensor(UpperCamelCase__  ,						dtype=torch.floataa  ,						device=UpperCamelCase__ )






    def  A       (  self      :					Dict  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					Optional[torch.Generator] = None ):


       """simple docstring"""







       if self.config.s_min <= sigma <= self.config.s_max:
          UpperCamelCase					=  min(self.config.s_churn / self.num_inference_steps  ,						2**0.5 - 1 )
       else:
          UpperCamelCase					=  0

       # sample eps ~ N(0, S_noise^2 * I)
       UpperCamelCase					=  self.config.s_noise * randn_tensor(sample.shape  ,						generator=UpperCamelCase__ ).to(sample.device )
       UpperCamelCase					=  sigma + gamma * sigma
       UpperCamelCase					=  sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps)

       return sample_hat, sigma_hat






    def  A       (  self      :					str  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					bool = True  ,						):


       """simple docstring"""







       UpperCamelCase					=  sample_hat + sigma_hat * model_output
       UpperCamelCase					=  (sample_hat - pred_original_sample) / sigma_hat
       UpperCamelCase					=  sample_hat + (sigma_prev - sigma_hat) * derivative

       if not return_dict:
          return (sample_prev, derivative)

       return KarrasVeOutput(
           prev_sample=UpperCamelCase__  ,						derivative=UpperCamelCase__  ,						pred_original_sample=UpperCamelCase__ )






    def  A       (  self      :					List[Any]  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					bool = True  ,						):


       """simple docstring"""







       UpperCamelCase					=  sample_prev + sigma_prev * model_output
       UpperCamelCase					=  (sample_prev - pred_original_sample) / sigma_prev
       UpperCamelCase					=  sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr)

       if not return_dict:
          return (sample_prev, derivative)

       return KarrasVeOutput(
           prev_sample=UpperCamelCase__  ,						derivative=UpperCamelCase__  ,						pred_original_sample=UpperCamelCase__ )






    def  A       (  self      :					Optional[Any]  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					int  ,						UpperCamelCase__      :					str ):


       """simple docstring"""







       raise NotImplementedError()

