

"""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"""







 __UpperCAmelCase	:					Union[str, Any]   		=	["image_processor"]
 __UpperCAmelCase	:					Optional[Any]   		=	"SamImageProcessor"


 def __init__(			self							:			Any,					UpperCAmelCase__							:			Dict	):
    super().__init__(UpperCAmelCase__	)
    __lowercase								=						self.image_processor
    __lowercase								=						-1_0
    __lowercase								=						self.image_processor.size["longest_edge"]


 def __call__(			self							:			Dict,					UpperCAmelCase__							:			int=None,					UpperCAmelCase__							:			List[str]=None,					UpperCAmelCase__							:			List[str]=None,					UpperCAmelCase__							:			Union[str, Any]=None,					UpperCAmelCase__							:			Optional[Union[str, TensorType]] = None,					**UpperCAmelCase__							:			Tuple,					):
    __lowercase								=						self.image_processor(
        UpperCAmelCase__,					return_tensors=UpperCAmelCase__,					**UpperCAmelCase__,					)

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

    if hasattr(UpperCAmelCase__,					"numpy"	):  # Checks if Torch or TF tensor
       __lowercase								=						original_sizes.numpy()

    __lowercase		,__lowercase		,__lowercase								=						self._check_and_preprocess_points(
        input_points=UpperCAmelCase__,					input_labels=UpperCAmelCase__,					input_boxes=UpperCAmelCase__,					)

    __lowercase								=						self._normalize_and_convert(
        UpperCAmelCase__,					UpperCAmelCase__,					input_points=UpperCAmelCase__,					input_labels=UpperCAmelCase__,					input_boxes=UpperCAmelCase__,					return_tensors=UpperCAmelCase__,					)

    return encoding_image_processor


 def 					_lowercase (			self							:			Union[str, Any],					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			List[Any]=None,					UpperCAmelCase__							:			Optional[int]=None,					UpperCAmelCase__							:			Optional[Any]=None,					UpperCAmelCase__							:			int="pt",					):
    if input_points is not None:
       if len(UpperCAmelCase__	) != len(UpperCAmelCase__	):
          __lowercase								=						[
              self._normalize_coordinates(self.target_size,					UpperCAmelCase__,					original_sizes[0]	) for point in input_points
          ]
       else:
          __lowercase								=						[
              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:
             __lowercase		,__lowercase								=						self._pad_points_and_labels(UpperCAmelCase__,					UpperCAmelCase__	)

       __lowercase								=						np.array(UpperCAmelCase__	)

    if input_labels is not None:
       __lowercase								=						np.array(UpperCAmelCase__	)

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

    if input_boxes is not None:
       if return_tensors == "pt":
          __lowercase								=						torch.from_numpy(UpperCAmelCase__	)
          # boxes batch size of 1 by default
          __lowercase								=						input_boxes.unsqueeze(1	) if len(input_boxes.shape	) != 3 else input_boxes
       elif return_tensors == "tf":
          __lowercase								=						tf.convert_to_tensor(UpperCAmelCase__	)
          # boxes batch size of 1 by default
          __lowercase								=						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":
          __lowercase								=						torch.from_numpy(UpperCAmelCase__	)
          # point batch size of 1 by default
          __lowercase								=						input_points.unsqueeze(1	) if len(input_points.shape	) != 4 else input_points
       elif return_tensors == "tf":
          __lowercase								=						tf.convert_to_tensor(UpperCAmelCase__	)
          # point batch size of 1 by default
          __lowercase								=						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":
          __lowercase								=						torch.from_numpy(UpperCAmelCase__	)
          # point batch size of 1 by default
          __lowercase								=						input_labels.unsqueeze(1	) if len(input_labels.shape	) != 3 else input_labels
       elif return_tensors == "tf":
          __lowercase								=						tf.convert_to_tensor(UpperCAmelCase__	)
          # point batch size of 1 by default
          __lowercase								=						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 					_lowercase (			self							:			Tuple,					UpperCAmelCase__							:			int,					UpperCAmelCase__							:			Optional[Any]	):
    __lowercase								=						max([point.shape[0] for point in input_points]	)
    __lowercase								=						[]
    for i, point in enumerate(UpperCAmelCase__	):
       if point.shape[0] != expected_nb_points:
          __lowercase								=						np.concatenate(
              [point, np.zeros((expected_nb_points - point.shape[0], 2)	) + self.point_pad_value],					axis=0	)
          __lowercase								=						np.append(input_labels[i],					[self.point_pad_value]	)
       processed_input_points.append(UpperCAmelCase__	)
    __lowercase								=						processed_input_points
    return input_points, input_labels


 def 					_lowercase (			self							:			List[Any],					UpperCAmelCase__							:			int,					UpperCAmelCase__							:			np.ndarray,					UpperCAmelCase__							:			Any,					UpperCAmelCase__							:			Tuple=False	):
    __lowercase		,__lowercase								=						original_size
    __lowercase		,__lowercase								=						self.image_processor._get_preprocess_shape(UpperCAmelCase__,					longest_edge=UpperCAmelCase__	)
    __lowercase								=						deepcopy(UpperCAmelCase__	).astype(UpperCAmelCase__	)

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

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

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

    return coords


 def 					_lowercase (			self							:			Tuple,					UpperCAmelCase__							:			List[Any]=None,					UpperCAmelCase__							:			Optional[int]=None,					UpperCAmelCase__							:			List[Any]=None,					):
    if input_points is not None:
       if hasattr(UpperCAmelCase__,					"numpy"	):  # Checks for TF or Torch tensor
          __lowercase								=						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."	)
       __lowercase								=						[np.array(UpperCAmelCase__	) for input_point in input_points]
    else:
       __lowercase								=						None

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

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

    return input_points, input_labels, input_boxes


 @property
 def 					_lowercase (			self							:			Optional[Any]	):
    __lowercase								=						self.image_processor.model_input_names
    return list(dict.fromkeys(UpperCAmelCase__	)	)



 def 					_lowercase (			self							:			Optional[int],					*UpperCAmelCase__							:			List[str],					**UpperCAmelCase__							:			Union[str, Any]	):
    return self.image_processor.post_process_masks(*UpperCAmelCase__,					**UpperCAmelCase__	)






from collections import OrderedDict
from typing import Mapping

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


__snake_case								=  logging.get_logger(__name__)

__snake_case								=  {
    """facebook/xmod-base""": """https://huggingface.co/facebook/xmod-base/resolve/main/config.json""",
    """facebook/xmod-large-prenorm""": """https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json""",
    """facebook/xmod-base-13-125k""": """https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json""",
    """facebook/xmod-base-30-125k""": """https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json""",
    """facebook/xmod-base-30-195k""": """https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json""",
    """facebook/xmod-base-60-125k""": """https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json""",
    """facebook/xmod-base-60-265k""": """https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json""",
    """facebook/xmod-base-75-125k""": """https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json""",
    """facebook/xmod-base-75-269k""": """https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json""",
}




class 						lowercase__  (						_UpperCAmelCase  ):
	A__    :   int				       ="""xmod"""
	def __init__(			self							:   Optional[Any]       ,   UpperCAmelCase_							:   Optional[int]=30522       ,   UpperCAmelCase_							:   Union[str, Any]=768       ,   UpperCAmelCase_							:   List[str]=12       ,   UpperCAmelCase_							:   List[str]=12       ,   UpperCAmelCase_							:   List[str]=3072       ,   UpperCAmelCase_							:   Dict="gelu"       ,   UpperCAmelCase_							:   str=0.1       ,   UpperCAmelCase_							:   Dict=0.1       ,   UpperCAmelCase_							:   Optional[Any]=512       ,   UpperCAmelCase_							:   Any=2       ,   UpperCAmelCase_							:   Optional[Any]=0.02       ,   UpperCAmelCase_							:   Optional[Any]=1e-1_2       ,   UpperCAmelCase_							:   Any=1       ,   UpperCAmelCase_							:   Dict=0       ,   UpperCAmelCase_							:   Optional[int]=2       ,   UpperCAmelCase_							:   Tuple="absolute"       ,   UpperCAmelCase_							:   Union[str, Any]=True       ,   UpperCAmelCase_							:   Dict=None       ,   UpperCAmelCase_							:   Union[str, Any]=False       ,   UpperCAmelCase_							:   int=2       ,   UpperCAmelCase_							:   int=False       ,   UpperCAmelCase_							:   Optional[int]=True       ,   UpperCAmelCase_							:   List[Any]=True       ,   UpperCAmelCase_							:   Union[str, Any]=("en_XX",)       ,   UpperCAmelCase_							:   int=None       ,   **UpperCAmelCase_							:   str       ,   ):
						super().__init__(pad_token_id=UpperCAmelCase_       ,   bos_token_id=UpperCAmelCase_       ,   eos_token_id=UpperCAmelCase_       ,   **UpperCAmelCase_							)

						SCREAMING_SNAKE_CASE__													= vocab_size
						SCREAMING_SNAKE_CASE__													= hidden_size
						SCREAMING_SNAKE_CASE__													= num_hidden_layers
						SCREAMING_SNAKE_CASE__													= num_attention_heads
						SCREAMING_SNAKE_CASE__													= hidden_act
						SCREAMING_SNAKE_CASE__													= intermediate_size
						SCREAMING_SNAKE_CASE__													= hidden_dropout_prob
						SCREAMING_SNAKE_CASE__													= attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE__													= max_position_embeddings
						SCREAMING_SNAKE_CASE__													= type_vocab_size
						SCREAMING_SNAKE_CASE__													= initializer_range
						SCREAMING_SNAKE_CASE__													= layer_norm_eps
						SCREAMING_SNAKE_CASE__													= position_embedding_type
						SCREAMING_SNAKE_CASE__													= use_cache
						SCREAMING_SNAKE_CASE__													= classifier_dropout
						SCREAMING_SNAKE_CASE__													= pre_norm
						SCREAMING_SNAKE_CASE__													= adapter_reduction_factor
						SCREAMING_SNAKE_CASE__													= adapter_layer_norm
						SCREAMING_SNAKE_CASE__													= adapter_reuse_layer_norm
						SCREAMING_SNAKE_CASE__													= ln_before_adapter
						SCREAMING_SNAKE_CASE__													= list(UpperCAmelCase_							)
						SCREAMING_SNAKE_CASE__													= default_language





class 						lowercase__  (						_UpperCAmelCase  ):
	@property
	def      A_				(			self							:   List[Any]							):
						if self.task == "multiple-choice":
											SCREAMING_SNAKE_CASE__													= {0: 'batch', 1: 'choice', 2: 'sequence'}
						else:
											SCREAMING_SNAKE_CASE__													= {0: 'batch', 1: 'sequence'}
						return OrderedDict(
						    [
						        ('input_ids', dynamic_axis),
						        ('attention_mask', dynamic_axis),
						    ]							)





