


'''simple docstring'''



import copy
import os
from typing import Union

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


A__		:					int												=  logging.get_logger(__name__)

A__		:					Optional[int]												=  {
    """BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json""",
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}





class    UpperCAmelCase_  (_UpperCAmelCase  ):





    """simple docstring"""






    lowerCamelCase  :					Optional[int]							     =			'altclip_text_model'







    def __init__(							self			,     SCREAMING_SNAKE_CASE_=25_00_02			,     SCREAMING_SNAKE_CASE_=10_24			,     SCREAMING_SNAKE_CASE_=24			,     SCREAMING_SNAKE_CASE_=16			,     SCREAMING_SNAKE_CASE_=40_96			,     SCREAMING_SNAKE_CASE_="gelu"			,     SCREAMING_SNAKE_CASE_=0.1			,     SCREAMING_SNAKE_CASE_=0.1			,     SCREAMING_SNAKE_CASE_=5_14			,     SCREAMING_SNAKE_CASE_=1			,     SCREAMING_SNAKE_CASE_=0.0_2			,     SCREAMING_SNAKE_CASE_=0.0_2			,     SCREAMING_SNAKE_CASE_=1E-05			,     SCREAMING_SNAKE_CASE_=1			,     SCREAMING_SNAKE_CASE_=0			,     SCREAMING_SNAKE_CASE_=2			,     SCREAMING_SNAKE_CASE_="absolute"			,     SCREAMING_SNAKE_CASE_=True			,     SCREAMING_SNAKE_CASE_=7_68			,     **SCREAMING_SNAKE_CASE_			,     )				->     Union[str, Any]:
         super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_			,     bos_token_id=SCREAMING_SNAKE_CASE_			,     eos_token_id=SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	int								=		vocab_size
         __lowerCamelCase   :	Dict								=		hidden_size
         __lowerCamelCase   :	Optional[int]								=		num_hidden_layers
         __lowerCamelCase   :	Optional[Any]								=		num_attention_heads
         __lowerCamelCase   :	Dict								=		hidden_act
         __lowerCamelCase   :	str								=		intermediate_size
         __lowerCamelCase   :	Union[str, Any]								=		hidden_dropout_prob
         __lowerCamelCase   :	Tuple								=		attention_probs_dropout_prob
         __lowerCamelCase   :	Dict								=		max_position_embeddings
         __lowerCamelCase   :	Tuple								=		type_vocab_size
         __lowerCamelCase   :	Any								=		initializer_range
         __lowerCamelCase   :	Dict								=		initializer_factor
         __lowerCamelCase   :	str								=		layer_norm_eps
         __lowerCamelCase   :	Dict								=		position_embedding_type
         __lowerCamelCase   :	Tuple								=		use_cache
         __lowerCamelCase   :	List[str]								=		project_dim







class    UpperCAmelCase_  (_UpperCAmelCase  ):





    """simple docstring"""






    lowerCamelCase  :					Any							     =			'altclip_vision_model'







    def __init__(							self			,     SCREAMING_SNAKE_CASE_=7_68			,     SCREAMING_SNAKE_CASE_=30_72			,     SCREAMING_SNAKE_CASE_=5_12			,     SCREAMING_SNAKE_CASE_=12			,     SCREAMING_SNAKE_CASE_=12			,     SCREAMING_SNAKE_CASE_=3			,     SCREAMING_SNAKE_CASE_=2_24			,     SCREAMING_SNAKE_CASE_=32			,     SCREAMING_SNAKE_CASE_="quick_gelu"			,     SCREAMING_SNAKE_CASE_=1E-5			,     SCREAMING_SNAKE_CASE_=0.0			,     SCREAMING_SNAKE_CASE_=0.0_2			,     SCREAMING_SNAKE_CASE_=1.0			,     **SCREAMING_SNAKE_CASE_			,     )				->     str:
         super().__init__(**SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Optional[int]								=		hidden_size
         __lowerCamelCase   :	Union[str, Any]								=		intermediate_size
         __lowerCamelCase   :	Tuple								=		projection_dim
         __lowerCamelCase   :	Optional[Any]								=		num_hidden_layers
         __lowerCamelCase   :	List[Any]								=		num_attention_heads
         __lowerCamelCase   :	Union[str, Any]								=		num_channels
         __lowerCamelCase   :	int								=		patch_size
         __lowerCamelCase   :	Dict								=		image_size
         __lowerCamelCase   :	Optional[Any]								=		initializer_range
         __lowerCamelCase   :	Tuple								=		initializer_factor
         __lowerCamelCase   :	Any								=		attention_dropout
         __lowerCamelCase   :	List[Any]								=		layer_norm_eps
         __lowerCamelCase   :	List[str]								=		hidden_act







    @classmethod
    def       lowercase_				(							cls			,     SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_	)				->     "PretrainedConfig":
         cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase				,       __lowerCamelCase   :	Tuple								=		cls.get_config_dict(SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_	)

         # get the vision config dict if we are loading from AltCLIPConfig
         if config_dict.get('model_type'	) == "altclip":
              __lowerCamelCase   :	Union[str, Any]								=		config_dict['vision_config']

         if "model_type" in config_dict and hasattr(cls			,     'model_type'	) and config_dict["model_type"] != cls.model_type:
              logger.warning(
                  f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
                  f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'	)

         return cls.from_dict(SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_	)







class    UpperCAmelCase_  (_UpperCAmelCase  ):





    """simple docstring"""






    lowerCamelCase  :					List[Any]							     =			'altclip'
    lowerCamelCase  :					Union[str, Any]							     =			True







    def __init__(							self			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_=7_68			,     SCREAMING_SNAKE_CASE_=2.6_5_9_2			,     **SCREAMING_SNAKE_CASE_	)				->     Any:
         # If `_config_dict` exist, we use them for the backward compatibility.
         # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
         # of confusion!).
         __lowerCamelCase   :	Tuple								=		kwargs.pop('text_config_dict'			,     SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	List[str]								=		kwargs.pop('vision_config_dict'			,     SCREAMING_SNAKE_CASE_	)

         super().__init__(**SCREAMING_SNAKE_CASE_	)

         # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
         # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
         # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
         if text_config_dict is not None:
              if text_config is None:
                   __lowerCamelCase   :	Tuple								=		{}

              # This is the complete result when using `text_config_dict`.
              __lowerCamelCase   :	Optional[int]								=		AltCLIPTextConfig(**SCREAMING_SNAKE_CASE_	).to_dict()

              # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
              for key, value in _text_config_dict.items():
                   if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
                        # If specified in `text_config_dict`
                        if key in text_config_dict:
                             __lowerCamelCase   :	Optional[Any]								=		(
                                 f'`{key}` is found in both `text_config_dict` and `text_config` but with different values. '
                                 f'The value `text_config_dict["{key}"]` will be used instead.'
                             )
                        # If inferred from default argument values (just to be super careful)
                        else:
                             __lowerCamelCase   :	Any								=		(
                                 f'`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '
                                 f'value `text_config["{key}"]` will be overriden.'
                             )
                        logger.warning(SCREAMING_SNAKE_CASE_	)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
              text_config.update(_text_config_dict	)

         if vision_config_dict is not None:
              if vision_config is None:
                   __lowerCamelCase   :	str								=		{}

              # This is the complete result when using `vision_config_dict`.
              __lowerCamelCase   :	Dict								=		AltCLIPVisionConfig(**SCREAMING_SNAKE_CASE_	).to_dict()
              # convert keys to string instead of integer
              if "id2label" in _vision_config_dict:
                   __lowerCamelCase   :	List[str]								=		{
                       str(SCREAMING_SNAKE_CASE_	): value for key, value in _vision_config_dict['id2label'].items()
                   }

              # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
              for key, value in _vision_config_dict.items():
                   if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
                        # If specified in `vision_config_dict`
                        if key in vision_config_dict:
                             __lowerCamelCase   :	Any								=		(
                                 f'`{key}` is found in both `vision_config_dict` and `vision_config` but with different '
                                 f'values. The value `vision_config_dict["{key}"]` will be used instead.'
                             )
                        # If inferred from default argument values (just to be super careful)
                        else:
                             __lowerCamelCase   :	Tuple								=		(
                                 f'`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '
                                 f'The value `vision_config["{key}"]` will be overriden.'
                             )
                        logger.warning(SCREAMING_SNAKE_CASE_	)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
              vision_config.update(_vision_config_dict	)

         if text_config is None:
              __lowerCamelCase   :	Optional[Any]								=		{}
              logger.info('`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.'	)

         if vision_config is None:
              __lowerCamelCase   :	Any								=		{}
              logger.info('`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.'	)

         __lowerCamelCase   :	Dict								=		AltCLIPTextConfig(**SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	Optional[int]								=		AltCLIPVisionConfig(**SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Any								=		projection_dim
         __lowerCamelCase   :	List[str]								=		logit_scale_init_value
         __lowerCamelCase   :	List[Any]								=		1.0







    @classmethod
    def       lowercase_				(							cls			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_	)				->     Union[str, Any]:
         return cls(text_config=text_config.to_dict()			,     vision_config=vision_config.to_dict()			,     **SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self	)				->     int:
         __lowerCamelCase   :	Optional[int]								=		copy.deepcopy(self.__dict__	)
         __lowerCamelCase   :	Tuple								=		self.text_config.to_dict()
         __lowerCamelCase   :	Optional[Any]								=		self.vision_config.to_dict()
         __lowerCamelCase   :	Union[str, Any]								=		self.__class__.model_type
         return output










'''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    UpperCAmelCase_  (_UpperCAmelCase  ):





    """simple docstring"""






    lowerCamelCase  :					Dict							     =			['image_processor']
    lowerCamelCase  :					str							     =			'SamImageProcessor'







    def __init__(							self			,     SCREAMING_SNAKE_CASE_	)				->     List[str]:
         super().__init__(SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	Any								=		self.image_processor
         __lowerCamelCase   :	str								=		-10
         __lowerCamelCase   :	List[str]								=		self.image_processor.size['longest_edge']







    def __call__(							self			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_ = None			,     **SCREAMING_SNAKE_CASE_			,     )				->     BatchEncoding:
         __lowerCamelCase   :	Union[str, Any]								=		self.image_processor(
             SCREAMING_SNAKE_CASE_			,     return_tensors=SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_			,     )

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

         if hasattr(SCREAMING_SNAKE_CASE_			,     'numpy'	):  # Checks if Torch or TF tensor
              __lowerCamelCase   :	Dict								=		original_sizes.numpy()

         __lowerCamelCase				,       __lowerCamelCase				,       __lowerCamelCase   :	str								=		self._check_and_preprocess_points(
             input_points=SCREAMING_SNAKE_CASE_			,     input_labels=SCREAMING_SNAKE_CASE_			,     input_boxes=SCREAMING_SNAKE_CASE_			,     )

         __lowerCamelCase   :	Tuple								=		self._normalize_and_convert(
             SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     input_points=SCREAMING_SNAKE_CASE_			,     input_labels=SCREAMING_SNAKE_CASE_			,     input_boxes=SCREAMING_SNAKE_CASE_			,     return_tensors=SCREAMING_SNAKE_CASE_			,     )

         return encoding_image_processor







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

              __lowerCamelCase   :	Optional[int]								=		np.array(SCREAMING_SNAKE_CASE_	)

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

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

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







    def       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_=False	)				->     np.ndarray:
         __lowerCamelCase				,       __lowerCamelCase   :	Tuple								=		original_size
         __lowerCamelCase				,       __lowerCamelCase   :	Optional[Any]								=		self.image_processor._get_preprocess_shape(SCREAMING_SNAKE_CASE_			,     longest_edge=SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	Dict								=		deepcopy(SCREAMING_SNAKE_CASE_	).astype(SCREAMING_SNAKE_CASE_	)

         if is_bounding_box:
              __lowerCamelCase   :	Optional[int]								=		coords.reshape(-1			,     2			,     2	)

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

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

         return coords







    def       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_=None			,     )				->     Optional[Any]:
         if input_points is not None:
              if hasattr(SCREAMING_SNAKE_CASE_			,     'numpy'	):  # Checks for TF or Torch tensor
                   __lowerCamelCase   :	List[str]								=		input_points.numpy().tolist()

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

         if input_labels is not None:
              if hasattr(SCREAMING_SNAKE_CASE_			,     'numpy'	):
                   __lowerCamelCase   :	Union[str, Any]								=		input_labels.numpy().tolist()

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

         if input_boxes is not None:
              if hasattr(SCREAMING_SNAKE_CASE_			,     'numpy'	):
                   __lowerCamelCase   :	int								=		input_boxes.numpy().tolist()

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

         return input_points, input_labels, input_boxes







    @property
    def       lowercase_				(							self	)				->     Dict:
         __lowerCamelCase   :	Any								=		self.image_processor.model_input_names
         return list(dict.fromkeys(SCREAMING_SNAKE_CASE_	)	)







    def       lowercase_				(							self			,     *SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_	)				->     Optional[Any]:
         return self.image_processor.post_process_masks(*SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_	)






