



'''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  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  ["""image_processor"""]
    _SCREAMING_SNAKE_CASE	  =  """SamImageProcessor"""






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


       """simple docstring"""







       super().__init__(UpperCamelCase__ )
       UpperCamelCase					=  self.image_processor
       UpperCamelCase					=  -1_0
       UpperCamelCase					=  self.image_processor.size['longest_edge']






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


       """simple docstring"""







       UpperCamelCase					=  self.image_processor(
           UpperCamelCase__  ,						return_tensors=UpperCamelCase__  ,						**UpperCamelCase__  ,						)

       # pop arguments that are not used in the foward but used nevertheless
       UpperCamelCase					=  encoding_image_processor['original_sizes']

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

       UpperCamelCase				,      UpperCamelCase				,      UpperCamelCase					=  self._check_and_preprocess_points(
           input_points=UpperCamelCase__  ,						input_labels=UpperCamelCase__  ,						input_boxes=UpperCamelCase__  ,						)

       UpperCamelCase					=  self._normalize_and_convert(
           UpperCamelCase__  ,						UpperCamelCase__  ,						input_points=UpperCamelCase__  ,						input_labels=UpperCamelCase__  ,						input_boxes=UpperCamelCase__  ,						return_tensors=UpperCamelCase__  ,						)

       return encoding_image_processor






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


       """simple docstring"""







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

          UpperCamelCase					=  np.array(UpperCamelCase__ )

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

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

       if input_boxes is not None:
          if return_tensors == "pt":
             UpperCamelCase					=  torch.from_numpy(UpperCamelCase__ )
             # boxes batch size of 1 by default
             UpperCamelCase					=  input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes
          elif return_tensors == "tf":
             UpperCamelCase					=  tf.convert_to_tensor(UpperCamelCase__ )
             # boxes batch size of 1 by default
             UpperCamelCase					=  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":
             UpperCamelCase					=  torch.from_numpy(UpperCamelCase__ )
             # point batch size of 1 by default
             UpperCamelCase					=  input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points
          elif return_tensors == "tf":
             UpperCamelCase					=  tf.convert_to_tensor(UpperCamelCase__ )
             # point batch size of 1 by default
             UpperCamelCase					=  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":
             UpperCamelCase					=  torch.from_numpy(UpperCamelCase__ )
             # point batch size of 1 by default
             UpperCamelCase					=  input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels
          elif return_tensors == "tf":
             UpperCamelCase					=  tf.convert_to_tensor(UpperCamelCase__ )
             # point batch size of 1 by default
             UpperCamelCase					=  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  A       (  self      :					Any  ,						UpperCamelCase__      :					Optional[Any]  ,						UpperCamelCase__      :					List[Any] ):


       """simple docstring"""







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






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


       """simple docstring"""







       UpperCamelCase				,      UpperCamelCase					=  original_size
       UpperCamelCase				,      UpperCamelCase					=  self.image_processor._get_preprocess_shape(UpperCamelCase__  ,						longest_edge=UpperCamelCase__ )
       UpperCamelCase					=  deepcopy(UpperCamelCase__ ).astype(UpperCamelCase__ )

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

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

       if is_bounding_box:
          UpperCamelCase					=  coords.reshape(-1  ,						4 )

       return coords






    def  A       (  self      :					List[Any]  ,						UpperCamelCase__      :					List[Any]=None  ,						UpperCamelCase__      :					Optional[int]=None  ,						UpperCamelCase__      :					Optional[int]=None  ,						):


       """simple docstring"""







       if input_points is not None:
          if hasattr(UpperCamelCase__  ,						'numpy' ):  # Checks for TF or Torch tensor
             UpperCamelCase					=  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.' )
          UpperCamelCase					=  [np.array(UpperCamelCase__ ) for input_point in input_points]
       else:
          UpperCamelCase					=  None

       if input_labels is not None:
          if hasattr(UpperCamelCase__  ,						'numpy' ):
             UpperCamelCase					=  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.' )
          UpperCamelCase					=  [np.array(UpperCamelCase__ ) for label in input_labels]
       else:
          UpperCamelCase					=  None

       if input_boxes is not None:
          if hasattr(UpperCamelCase__  ,						'numpy' ):
             UpperCamelCase					=  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.' )
          UpperCamelCase					=  [np.array(UpperCamelCase__ ).astype(np.floataa ) for box in input_boxes]
       else:
          UpperCamelCase					=  None

       return input_points, input_labels, input_boxes






    @property
    def  A       (  self      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  self.image_processor.model_input_names
       return list(dict.fromkeys(UpperCamelCase__ ) )






    def  A       (  self      :					Optional[int]  ,						*UpperCamelCase__      :					List[Any]  ,						**UpperCamelCase__      :					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()

