




"""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    lowercase(	__a					):







 '''simple docstring'''





 lowercase__					   =   ["image_processor"]
 lowercase__					   =   "SamImageProcessor"


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




   '''simple docstring'''



   super().__init__(lowerCamelCase__						)
   _snake_case				:						Optional[int]								=    self.image_processor
   _snake_case				:						List[Any]								=    -10
   _snake_case				:						Union[str, Any]								=    self.image_processor.size["""longest_edge"""]


 def __call__(							self:						List[str], a_:						Any=None, a_:						Optional[int]=None, a_:						Optional[int]=None, a_:						int=None, a_:						Tuple = None, **a_:						Tuple, ):




   '''simple docstring'''



   _snake_case				:						int								=    self.image_processor(
       lowerCamelCase__, return_tensors=lowerCamelCase__, **lowerCamelCase__, )

   # pop arguments that are not used in the foward but used nevertheless
   _snake_case				:						List[Any]								=    encoding_image_processor["""original_sizes"""]

   if hasattr(lowerCamelCase__, """numpy"""						):  # Checks if Torch or TF tensor
     _snake_case				:						Tuple								=    original_sizes.numpy()

   _snake_case						,   _snake_case						,   _snake_case				:						Union[str, Any]								=    self._check_and_preprocess_points(
       input_points=lowerCamelCase__, input_labels=lowerCamelCase__, input_boxes=lowerCamelCase__, )

   _snake_case				:						Any								=    self._normalize_and_convert(
       lowerCamelCase__, lowerCamelCase__, input_points=lowerCamelCase__, input_labels=lowerCamelCase__, input_boxes=lowerCamelCase__, return_tensors=lowerCamelCase__, )

   return encoding_image_processor


 def 					UpperCamelCase_  (							self:						int, a_:						Union[str, Any], a_:						Union[str, Any], a_:						Dict=None, a_:						Union[str, Any]=None, a_:						str=None, a_:						Tuple="pt", ):




   '''simple docstring'''



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

     _snake_case				:						str								=    np.array(lowerCamelCase__						)

   if input_labels is not None:
     _snake_case				:						Optional[int]								=    np.array(lowerCamelCase__						)

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

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




   '''simple docstring'''



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


 def 					UpperCamelCase_  (							self:						Any, a_:						Tuple, a_:						Any, a_:						Union[str, Any], a_:						str=False						):




   '''simple docstring'''



   _snake_case						,   _snake_case				:						Optional[int]								=    original_size
   _snake_case						,   _snake_case				:						str								=    self.image_processor._get_preprocess_shape(lowerCamelCase__, longest_edge=lowerCamelCase__						)
   _snake_case				:						str								=    deepcopy(lowerCamelCase__						).astype(lowerCamelCase__						)

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

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

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

   return coords


 def 					UpperCamelCase_  (							self:						Union[str, Any], a_:						Dict=None, a_:						Union[str, Any]=None, a_:						str=None, ):




   '''simple docstring'''



   if input_points is not None:
     if hasattr(lowerCamelCase__, """numpy"""						):  # Checks for TF or Torch tensor
       _snake_case				:						Any								=    input_points.numpy().tolist()

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

   if input_labels is not None:
     if hasattr(lowerCamelCase__, """numpy"""						):
       _snake_case				:						Optional[Any]								=    input_labels.numpy().tolist()

     if not isinstance(lowerCamelCase__, lowerCamelCase__						) or not isinstance(input_labels[0], lowerCamelCase__						):
       raise ValueError("""Input labels must be a list of list integers."""						)
     _snake_case				:						Any								=    [np.array(lowerCamelCase__						) for label in input_labels]
   else:
     _snake_case				:						Any								=    None

   if input_boxes is not None:
     if hasattr(lowerCamelCase__, """numpy"""						):
       _snake_case				:						Optional[int]								=    input_boxes.numpy().tolist()

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

   return input_points, input_labels, input_boxes


 @property
 def 					UpperCamelCase_  (							self:						List[str]						):




   '''simple docstring'''



   _snake_case				:						List[Any]								=    self.image_processor.model_input_names
   return list(dict.fromkeys(lowerCamelCase__						)						)


 def 					UpperCamelCase_  (							self:						Optional[int], *a_:						Union[str, Any], **a_:						int						):




   '''simple docstring'''



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








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

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block







@dataclass
class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			snake_case_  						=			42







class        __lowerCAmelCase					(			__magic_name__     ,							__magic_name__					):

			"""simple docstring"""







			@register_to_config
			def __init__( self     ,		lowerCamelCase__ = 65_536     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = 2     ,		lowerCamelCase__ = 2     ,		lowerCamelCase__ = 0     ,		lowerCamelCase__ = "fourier"     ,		lowerCamelCase__ = True     ,		lowerCamelCase__ = False     ,		lowerCamelCase__ = 0.0     ,		lowerCamelCase__ = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")     ,		lowerCamelCase__ = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")     ,		lowerCamelCase__ = "UNetMidBlock1D"     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = (32, 32, 64)     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = 8     ,		lowerCamelCase__ = 1     ,		lowerCamelCase__ = False     ,		)       -> Dict:



							'''simple docstring'''
							super().__init__()
							__lowerCamelCase									=       sample_size

							# time
							if time_embedding_type == "fourier":
											__lowerCamelCase									=       GaussianFourierProjection(
											    embedding_size=8     ,		set_W_to_weight=lowerCamelCase__     ,		log=lowerCamelCase__     ,		flip_sin_to_cos=lowerCamelCase__				)
											__lowerCamelCase									=       2 * block_out_channels[0]
							elif time_embedding_type == "positional":
											__lowerCamelCase									=       Timesteps(
											    block_out_channels[0]     ,		flip_sin_to_cos=lowerCamelCase__     ,		downscale_freq_shift=lowerCamelCase__				)
											__lowerCamelCase									=       block_out_channels[0]

							if use_timestep_embedding:
											__lowerCamelCase									=       block_out_channels[0] * 4
											__lowerCamelCase									=       TimestepEmbedding(
											    in_channels=lowerCamelCase__     ,		time_embed_dim=lowerCamelCase__     ,		act_fn=lowerCamelCase__     ,		out_dim=block_out_channels[0]     ,		)

							__lowerCamelCase									=       nn.ModuleList([]				)
							__lowerCamelCase									=       None
							__lowerCamelCase									=       nn.ModuleList([]				)
							__lowerCamelCase									=       None

							# down
							__lowerCamelCase									=       in_channels
							for i, down_block_type in enumerate(lowerCamelCase__				):
											__lowerCamelCase									=       output_channel
											__lowerCamelCase									=       block_out_channels[i]

											if i == 0:
															input_channel += extra_in_channels

											__lowerCamelCase									=       i == len(lowerCamelCase__				) - 1

											__lowerCamelCase									=       get_down_block(
											    lowerCamelCase__     ,		num_layers=lowerCamelCase__     ,		in_channels=lowerCamelCase__     ,		out_channels=lowerCamelCase__     ,		temb_channels=block_out_channels[0]     ,		add_downsample=not is_final_block or downsample_each_block     ,		)
											self.down_blocks.append(lowerCamelCase__				)

							# mid
							__lowerCamelCase									=       get_mid_block(
							    lowerCamelCase__     ,		in_channels=block_out_channels[-1]     ,		mid_channels=block_out_channels[-1]     ,		out_channels=block_out_channels[-1]     ,		embed_dim=block_out_channels[0]     ,		num_layers=lowerCamelCase__     ,		add_downsample=lowerCamelCase__     ,		)

							# up
							__lowerCamelCase									=       list(reversed(lowerCamelCase__				)				)
							__lowerCamelCase									=       reversed_block_out_channels[0]
							if out_block_type is None:
											__lowerCamelCase									=       out_channels
							else:
											__lowerCamelCase									=       block_out_channels[0]

							for i, up_block_type in enumerate(lowerCamelCase__				):
											__lowerCamelCase									=       output_channel
											__lowerCamelCase									=       (
											    reversed_block_out_channels[i + 1] if i < len(lowerCamelCase__				) - 1 else final_upsample_channels
											)

											__lowerCamelCase									=       i == len(lowerCamelCase__				) - 1

											__lowerCamelCase									=       get_up_block(
											    lowerCamelCase__     ,		num_layers=lowerCamelCase__     ,		in_channels=lowerCamelCase__     ,		out_channels=lowerCamelCase__     ,		temb_channels=block_out_channels[0]     ,		add_upsample=not is_final_block     ,		)
											self.up_blocks.append(lowerCamelCase__				)
											__lowerCamelCase									=       output_channel

							# out
							__lowerCamelCase									=       norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4     ,		32				)
							__lowerCamelCase									=       get_out_block(
							    out_block_type=lowerCamelCase__     ,		num_groups_out=lowerCamelCase__     ,		embed_dim=block_out_channels[0]     ,		out_channels=lowerCamelCase__     ,		act_fn=lowerCamelCase__     ,		fc_dim=block_out_channels[-1] // 4     ,		)






			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = True     ,		)       -> Union[UNetaDOutput, Tuple]:



							'''simple docstring'''
							__lowerCamelCase									=       timestep
							if not torch.is_tensor(lowerCamelCase__				):
											__lowerCamelCase									=       torch.tensor([timesteps]     ,		dtype=torch.long     ,		device=sample.device				)
							elif torch.is_tensor(lowerCamelCase__				) and len(timesteps.shape				) == 0:
											__lowerCamelCase									=       timesteps[None].to(sample.device				)

							__lowerCamelCase									=       self.time_proj(lowerCamelCase__				)
							if self.config.use_timestep_embedding:
											__lowerCamelCase									=       self.time_mlp(lowerCamelCase__				)
							else:
											__lowerCamelCase									=       timestep_embed[..., None]
											__lowerCamelCase									=       timestep_embed.repeat([1, 1, sample.shape[2]]				).to(sample.dtype				)
											__lowerCamelCase									=       timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:])				)

							# 2. down
							__lowerCamelCase									=       ()
							for downsample_block in self.down_blocks:
											__lowerCamelCase			,		__lowerCamelCase									=       downsample_block(hidden_states=lowerCamelCase__     ,		temb=lowerCamelCase__				)
											down_block_res_samples += res_samples

							# 3. mid
							if self.mid_block:
											__lowerCamelCase									=       self.mid_block(lowerCamelCase__     ,		lowerCamelCase__				)

							# 4. up
							for i, upsample_block in enumerate(self.up_blocks				):
											__lowerCamelCase									=       down_block_res_samples[-1:]
											__lowerCamelCase									=       down_block_res_samples[:-1]
											__lowerCamelCase									=       upsample_block(lowerCamelCase__     ,		res_hidden_states_tuple=lowerCamelCase__     ,		temb=lowerCamelCase__				)

							# 5. post-process
							if self.out_block:
											__lowerCamelCase									=       self.out_block(lowerCamelCase__     ,		lowerCamelCase__				)

							if not return_dict:
											return (sample,)

							return UNetaDOutput(sample=lowerCamelCase__				)


