


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			(_a						):
       _lowercase											=     ["""image_processor"""]
       _lowercase											=     """SamImageProcessor"""







       def __init__(			self: Dict,A_: Union[str, Any]					):






            '''simple docstring'''




            super().__init__(A_					)
            __UpperCamelCase =			self.image_processor
            __UpperCamelCase =			-10
            __UpperCamelCase =			self.image_processor.size['longest_edge']







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






            '''simple docstring'''




            __UpperCamelCase =			self.image_processor(
                A_,return_tensors=A_,**A_,)

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

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

            __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase =			self._check_and_preprocess_points(
                input_points=A_,input_labels=A_,input_boxes=A_,)

            __UpperCamelCase =			self._normalize_and_convert(
                A_,A_,input_points=A_,input_labels=A_,input_boxes=A_,return_tensors=A_,)

            return encoding_image_processor







       def 		snake_case_	(			self: Tuple,A_: Any,A_: str,A_: Dict=None,A_: Dict=None,A_: int=None,A_: List[Any]="pt",):






            '''simple docstring'''




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

                 __UpperCamelCase =			np.array(A_					)

            if input_labels is not None:
                 __UpperCamelCase =			np.array(A_					)

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

            if input_boxes is not None:
                 if return_tensors == "pt":
                      __UpperCamelCase =			torch.from_numpy(A_					)
                      # 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(A_					)
                      # boxes batch size of 1 by default
                      __UpperCamelCase =			tf.expand_dims(A_,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(A_					)
                      # 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(A_					)
                      # point batch size of 1 by default
                      __UpperCamelCase =			tf.expand_dims(A_,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(A_					)
                      # 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(A_					)
                      # point batch size of 1 by default
                      __UpperCamelCase =			tf.expand_dims(A_,1					) if len(input_labels.shape					) != 3 else input_labels
                 encoding_image_processor.update({'input_labels': input_labels}					)

            return encoding_image_processor







       def 		snake_case_	(			self: List[str],A_: int,A_: Optional[Any]					):






            '''simple docstring'''




            __UpperCamelCase =			max([point.shape[0] for point in input_points]					)
            __UpperCamelCase =			[]
            for i, point in enumerate(A_					):
                 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(A_					)
            __UpperCamelCase =			processed_input_points
            return input_points, input_labels







       def 		snake_case_	(			self: Optional[int],A_: int,A_: np.ndarray,A_: Union[str, Any],A_: int=False					):






            '''simple docstring'''




            __UpperCamelCase,    __UpperCamelCase =			original_size
            __UpperCamelCase,    __UpperCamelCase =			self.image_processor._get_preprocess_shape(A_,longest_edge=A_					)
            __UpperCamelCase =			deepcopy(A_					).astype(A_					)

            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 		snake_case_	(			self: Dict,A_: Optional[Any]=None,A_: List[str]=None,A_: Tuple=None,):






            '''simple docstring'''




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

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

            if input_labels is not None:
                 if hasattr(A_,'numpy'					):
                      __UpperCamelCase =			input_labels.numpy().tolist()

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

            if input_boxes is not None:
                 if hasattr(A_,'numpy'					):
                      __UpperCamelCase =			input_boxes.numpy().tolist()

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

            return input_points, input_labels, input_boxes







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






            '''simple docstring'''




            __UpperCamelCase =			self.image_processor.model_input_names
            return list(dict.fromkeys(A_					)					)







       def 		snake_case_	(			self: int,*A_: int,**A_: Tuple					):






            '''simple docstring'''




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







import warnings

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_		 =					logging.get_logger(__name__)

UpperCAmelCase_		 =					{
    """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/config.json""",
    """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/config.json""",
}


class 	lowerCamelCase__	(       _A):



 """simple docstring"""

 a__					: Any =  "xlnet"
 a__					: Dict =  ["mems"]
 a__					: List[str] =  {
     "n_token": "vocab_size",  # Backward compatibility
     "hidden_size": "d_model",
     "num_attention_heads": "n_head",
     "num_hidden_layers": "n_layer",
 }

 def __init__(    self					:					int			,						__lowerCAmelCase					:					Dict=3_20_00			,						__lowerCAmelCase					:					List[str]=10_24			,						__lowerCAmelCase					:					Dict=24			,						__lowerCAmelCase					:					Optional[Any]=16			,						__lowerCAmelCase					:					Dict=40_96			,						__lowerCAmelCase					:					Any="gelu"			,						__lowerCAmelCase					:					int=True			,						__lowerCAmelCase					:					List[str]="bi"			,						__lowerCAmelCase					:					Dict=0.02			,						__lowerCAmelCase					:					Union[str, Any]=1E-12			,						__lowerCAmelCase					:					Optional[Any]=0.1			,						__lowerCAmelCase					:					Optional[Any]=5_12			,						__lowerCAmelCase					:					List[str]=None			,						__lowerCAmelCase					:					Tuple=True			,						__lowerCAmelCase					:					Tuple=False			,						__lowerCAmelCase					:					Optional[Any]=False			,						__lowerCAmelCase					:					Union[str, Any]=-1			,						__lowerCAmelCase					:					Optional[Any]=False			,						__lowerCAmelCase					:					Any="last"			,						__lowerCAmelCase					:					List[Any]=True			,						__lowerCAmelCase					:					Tuple="tanh"			,						__lowerCAmelCase					:					int=0.1			,						__lowerCAmelCase					:					str=5			,						__lowerCAmelCase					:					str=5			,						__lowerCAmelCase					:					List[str]=5			,						__lowerCAmelCase					:					List[str]=1			,						__lowerCAmelCase					:					Optional[int]=2			,						**__lowerCAmelCase					:					List[str]			,						)   ->	Tuple:
    _A      =       vocab_size
    _A      =       d_model
    _A      =       n_layer
    _A      =       n_head
    if d_model % n_head != 0:
       raise ValueError(f'''\'d_model % n_head\' ({d_model % n_head}) should be equal to 0'''      )
    if "d_head" in kwargs:
       if kwargs["d_head"] != d_model // n_head:
          raise ValueError(
              f'''`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})'''      )
    _A      =       d_model // n_head
    _A      =       ff_activation
    _A      =       d_inner
    _A      =       untie_r
    _A      =       attn_type

    _A      =       initializer_range
    _A      =       layer_norm_eps

    _A      =       dropout
    _A      =       mem_len
    _A      =       reuse_len
    _A      =       bi_data
    _A      =       clamp_len
    _A      =       same_length

    _A      =       summary_type
    _A      =       summary_use_proj
    _A      =       summary_activation
    _A      =       summary_last_dropout
    _A      =       start_n_top
    _A      =       end_n_top

    _A      =       bos_token_id
    _A      =       pad_token_id
    _A      =       eos_token_id

    if "use_cache" in kwargs:
       warnings.warn(
           '''The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`'''
           ''' instead.'''			,						__lowerCAmelCase			,						)
       _A      =       kwargs['''use_cache''']

    _A      =       use_mems_eval
    _A      =       use_mems_train
    super().__init__(pad_token_id=__lowerCAmelCase			,						bos_token_id=__lowerCAmelCase			,						eos_token_id=__lowerCAmelCase			,						**__lowerCAmelCase      )

 @property
 def     snake_case_      (    self					:					Optional[Any]      )   ->	Union[str, Any]:
    logger.info(f'''The model {self.model_type} is one of the few models that has no sequence length limit.'''      )
    return -1

 @max_position_embeddings.setter
 def     snake_case_      (    self					:					Tuple			,						__lowerCAmelCase					:					Optional[Any]      )   ->	Dict:
    # Message copied from Transformer-XL documentation
    raise NotImplementedError(
        f'''The model {self.model_type} is one of the few models that has no sequence length limit.'''      )



