




"""simple docstring"""






import copy
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


lowercase__  		=		logging.get_logger(__name__)

lowercase__  		=		{
    """microsoft/conditional-detr-resnet-50""": (
        """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json"""
    ),
}






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    """conditional_detr"""
			lowerCamelCase__   =    ["""past_key_values"""]
			lowerCamelCase__   =    {
			    """hidden_size""": """d_model""",
			    """num_attention_heads""": """encoder_attention_heads""",
			}
			def __init__(						self						,   lowercase=True						,   lowercase=None						,   lowercase=3						,   lowercase=300						,   lowercase=6						,   lowercase=2048						,   lowercase=8						,   lowercase=6						,   lowercase=2048						,   lowercase=8						,   lowercase=0.0						,   lowercase=0.0						,   lowercase=True						,   lowercase="relu"						,   lowercase=256						,   lowercase=0.1						,   lowercase=0.0						,   lowercase=0.0						,   lowercase=0.02						,   lowercase=1.0						,   lowercase=False						,   lowercase="sine"						,   lowercase="resnet50"						,   lowercase=True						,   lowercase=False						,   lowercase=2						,   lowercase=5						,   lowercase=2						,   lowercase=1						,   lowercase=1						,   lowercase=2						,   lowercase=5						,   lowercase=2						,   lowercase=0.25						,   **lowercase						,   ):
							if backbone_config is not None and use_timm_backbone:
											raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.'						)

							if not use_timm_backbone:
											if backbone_config is None:
															logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'						)
															_lowerCamelCase  :    List[str]					=					CONFIG_MAPPING['resnet'](out_features=['stage4']						)
											elif isinstance(lowercase						,   lowercase						):
															_lowerCamelCase  :    List[Any]					=					backbone_config.get('model_type'						)
															_lowerCamelCase  :    Any					=					CONFIG_MAPPING[backbone_model_type]
															_lowerCamelCase  :    Tuple					=					config_class.from_dict(lowercase						)

							_lowerCamelCase  :    Any					=					use_timm_backbone
							_lowerCamelCase  :    Tuple					=					backbone_config
							_lowerCamelCase  :    Optional[Any]					=					num_channels
							_lowerCamelCase  :    List[Any]					=					num_queries
							_lowerCamelCase  :    Tuple					=					d_model
							_lowerCamelCase  :    List[Any]					=					encoder_ffn_dim
							_lowerCamelCase  :    Any					=					encoder_layers
							_lowerCamelCase  :    List[Any]					=					encoder_attention_heads
							_lowerCamelCase  :    Dict					=					decoder_ffn_dim
							_lowerCamelCase  :    int					=					decoder_layers
							_lowerCamelCase  :    str					=					decoder_attention_heads
							_lowerCamelCase  :    Union[str, Any]					=					dropout
							_lowerCamelCase  :    Dict					=					attention_dropout
							_lowerCamelCase  :    Optional[Any]					=					activation_dropout
							_lowerCamelCase  :    Dict					=					activation_function
							_lowerCamelCase  :    List[Any]					=					init_std
							_lowerCamelCase  :    List[str]					=					init_xavier_std
							_lowerCamelCase  :    List[str]					=					encoder_layerdrop
							_lowerCamelCase  :    Optional[int]					=					decoder_layerdrop
							_lowerCamelCase  :    Any					=					encoder_layers
							_lowerCamelCase  :    Optional[int]					=					auxiliary_loss
							_lowerCamelCase  :    List[str]					=					position_embedding_type
							_lowerCamelCase  :    int					=					backbone
							_lowerCamelCase  :    Union[str, Any]					=					use_pretrained_backbone
							_lowerCamelCase  :    int					=					dilation
							# Hungarian matcher
							_lowerCamelCase  :    Optional[int]					=					class_cost
							_lowerCamelCase  :    List[str]					=					bbox_cost
							_lowerCamelCase  :    Dict					=					giou_cost
							# Loss coefficients
							_lowerCamelCase  :    Optional[Any]					=					mask_loss_coefficient
							_lowerCamelCase  :    Optional[int]					=					dice_loss_coefficient
							_lowerCamelCase  :    Optional[int]					=					cls_loss_coefficient
							_lowerCamelCase  :    str					=					bbox_loss_coefficient
							_lowerCamelCase  :    Any					=					giou_loss_coefficient
							_lowerCamelCase  :    Optional[Any]					=					focal_alpha
							super().__init__(is_encoder_decoder=lowercase						,   **lowercase						)
			@property
			def       A_					(						self						):
							return self.encoder_attention_heads
			@property
			def       A_					(						self						):
							return self.d_model






			def       A_					(						self						):
							_lowerCamelCase  :    str					=					copy.deepcopy(self.__dict__						)
							if self.backbone_config is not None:
											_lowerCamelCase  :    Dict					=					self.backbone_config.to_dict()
							_lowerCamelCase  :    Dict					=					self.__class__.model_type
							return output






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    version.parse("""1.11"""		)
			@property
			def       A_					(						self						):
							return OrderedDict(
							    [
							        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
							        ('pixel_mask', {0: 'batch'}),
							    ]						)
			@property
			def       A_					(						self						):
							return 1E-5






			@property
			def       A_					(						self						):
							return 12





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






			'''simple docstring'''



			lowerCamelCase__   =    ["""image_processor"""]
			lowerCamelCase__   =    """SamImageProcessor"""
			def __init__(						self						,   lowercase						):
							super().__init__(lowercase						)
							_lowerCamelCase  :    str					=					self.image_processor
							_lowerCamelCase  :    Optional[int]					=					-10
							_lowerCamelCase  :    Optional[Any]					=					self.image_processor.size['longest_edge']
			def __call__(						self						,   lowercase=None						,   lowercase=None						,   lowercase=None						,   lowercase=None						,   lowercase = None						,   **lowercase						,   ):
							_lowerCamelCase  :    int					=					self.image_processor(
							    lowercase						,   return_tensors=lowercase						,   **lowercase						,   )

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

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

							_lowerCamelCase,				_lowerCamelCase,				_lowerCamelCase  :    Optional[Any]					=					self._check_and_preprocess_points(
							    input_points=lowercase						,   input_labels=lowercase						,   input_boxes=lowercase						,   )

							_lowerCamelCase  :    Tuple					=					self._normalize_and_convert(
							    lowercase						,   lowercase						,   input_points=lowercase						,   input_labels=lowercase						,   input_boxes=lowercase						,   return_tensors=lowercase						,   )

							return encoding_image_processor
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase=None						,   lowercase=None						,   lowercase=None						,   lowercase="pt"						,   ):
							if input_points is not None:
											if len(lowercase						) != len(lowercase						):
															_lowerCamelCase  :    str					=					[
															    self._normalize_coordinates(self.target_size						,   lowercase						,   original_sizes[0]						) for point in input_points
															]
											else:
															_lowerCamelCase  :    Optional[Any]					=					[
															    self._normalize_coordinates(self.target_size						,   lowercase						,   lowercase						)
															    for point, original_size in zip(lowercase						,   lowercase						)
															]
											# 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  :    List[str]					=					self._pad_points_and_labels(lowercase						,   lowercase						)

											_lowerCamelCase  :    Optional[int]					=					np.array(lowercase						)

							if input_labels is not None:
											_lowerCamelCase  :    List[Any]					=					np.array(lowercase						)

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

							if input_boxes is not None:
											if return_tensors == "pt":
															_lowerCamelCase  :    List[str]					=					torch.from_numpy(lowercase						)
															# boxes batch size of 1 by default
															_lowerCamelCase  :    str					=					input_boxes.unsqueeze(1						) if len(input_boxes.shape						) != 3 else input_boxes
											elif return_tensors == "tf":
															_lowerCamelCase  :    int					=					tf.convert_to_tensor(lowercase						)
															# boxes batch size of 1 by default
															_lowerCamelCase  :    Union[str, Any]					=					tf.expand_dims(lowercase						,   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  :    Optional[Any]					=					torch.from_numpy(lowercase						)
															# point batch size of 1 by default
															_lowerCamelCase  :    Union[str, Any]					=					input_points.unsqueeze(1						) if len(input_points.shape						) != 4 else input_points
											elif return_tensors == "tf":
															_lowerCamelCase  :    List[str]					=					tf.convert_to_tensor(lowercase						)
															# point batch size of 1 by default
															_lowerCamelCase  :    Union[str, Any]					=					tf.expand_dims(lowercase						,   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  :    Union[str, Any]					=					torch.from_numpy(lowercase						)
															# point batch size of 1 by default
															_lowerCamelCase  :    Optional[Any]					=					input_labels.unsqueeze(1						) if len(input_labels.shape						) != 3 else input_labels
											elif return_tensors == "tf":
															_lowerCamelCase  :    Dict					=					tf.convert_to_tensor(lowercase						)
															# point batch size of 1 by default
															_lowerCamelCase  :    Any					=					tf.expand_dims(lowercase						,   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						,   lowercase						,   lowercase						):
							_lowerCamelCase  :    Optional[int]					=					max([point.shape[0] for point in input_points]						)
							_lowerCamelCase  :    Optional[int]					=					[]
							for i, point in enumerate(lowercase						):
											if point.shape[0] != expected_nb_points:
															_lowerCamelCase  :    Tuple					=					np.concatenate(
															    [point, np.zeros((expected_nb_points - point.shape[0], 2)						) + self.point_pad_value]						,   axis=0						)
															_lowerCamelCase  :    Optional[Any]					=					np.append(input_labels[i]						,   [self.point_pad_value]						)
											processed_input_points.append(lowercase						)
							_lowerCamelCase  :    Any					=					processed_input_points
							return input_points, input_labels
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						,   lowercase=False						):
							_lowerCamelCase,				_lowerCamelCase  :    List[str]					=					original_size
							_lowerCamelCase,				_lowerCamelCase  :    Optional[int]					=					self.image_processor._get_preprocess_shape(lowercase						,   longest_edge=lowercase						)
							_lowerCamelCase  :    Tuple					=					deepcopy(lowercase						).astype(lowercase						)

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

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

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

							return coords
			def       A_					(						self						,   lowercase=None						,   lowercase=None						,   lowercase=None						,   ):
							if input_points is not None:
											if hasattr(lowercase						,   'numpy'						):  # Checks for TF or Torch tensor
															_lowerCamelCase  :    int					=					input_points.numpy().tolist()

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

							if input_labels is not None:
											if hasattr(lowercase						,   'numpy'						):
															_lowerCamelCase  :    Any					=					input_labels.numpy().tolist()

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

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

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

							return input_points, input_labels, input_boxes
			@property
			def       A_					(						self						):
							_lowerCamelCase  :    Optional[Any]					=					self.image_processor.model_input_names
							return list(dict.fromkeys(lowercase						)						)






			def       A_					(						self						,   *lowercase						,   **lowercase						):
							return self.image_processor.post_process_masks(*lowercase						,   **lowercase						)