


'''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 		snake_case				(    __lowerCamelCase						):

				"""simple docstring"""




				_lowerCAmelCase           =    ['image_processor']
				_lowerCAmelCase           =    'SamImageProcessor'





				def __init__(	self       ,    lowerCamelCase )    ->      List[Any]:







					"""simple docstring"""






					super().__init__(lowerCamelCase )
					snake_case__			:			Tuple             =		self.image_processor
					snake_case__			:			Optional[int]             =		-10
					snake_case__			:			int             =		self.image_processor.size['''longest_edge''']





				def __call__(	self       ,    lowerCamelCase=None       ,    lowerCamelCase=None       ,    lowerCamelCase=None       ,    lowerCamelCase=None       ,    lowerCamelCase = None       ,    **lowerCamelCase       ,    )    ->      BatchEncoding:







					"""simple docstring"""






					snake_case__			:			str             =		self.image_processor(
					    lowerCamelCase       ,    return_tensors=lowerCamelCase       ,    **lowerCamelCase       ,    )

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

					if hasattr(lowerCamelCase       ,    '''numpy''' ):  # Checks if Torch or TF tensor
						snake_case__			:			List[Any]             =		original_sizes.numpy()

					snake_case__      ,snake_case__      ,snake_case__			:			Optional[int]             =		self._check_and_preprocess_points(
					    input_points=lowerCamelCase       ,    input_labels=lowerCamelCase       ,    input_boxes=lowerCamelCase       ,    )

					snake_case__			:			List[Any]             =		self._normalize_and_convert(
					    lowerCamelCase       ,    lowerCamelCase       ,    input_points=lowerCamelCase       ,    input_labels=lowerCamelCase       ,    input_boxes=lowerCamelCase       ,    return_tensors=lowerCamelCase       ,    )

					return encoding_image_processor





				def    lowercase__							(	self       ,    lowerCamelCase       ,    lowerCamelCase       ,    lowerCamelCase=None       ,    lowerCamelCase=None       ,    lowerCamelCase=None       ,    lowerCamelCase="pt"       ,    )    ->      Dict:







					"""simple docstring"""






					if input_points is not None:
						if len(lowerCamelCase ) != len(lowerCamelCase ):
							snake_case__			:			Optional[int]             =		[
							    self._normalize_coordinates(self.target_size       ,    lowerCamelCase       ,    original_sizes[0] ) for point in input_points
							]
						else:
							snake_case__			:			Any             =		[
							    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__			:			Optional[Any]             =		np.array(lowerCamelCase )

					if input_labels is not None:
						snake_case__			:			Optional[Any]             =		np.array(lowerCamelCase )

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

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







					"""simple docstring"""






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





				def    lowercase__							(	self       ,    lowerCamelCase       ,    lowerCamelCase       ,    lowerCamelCase       ,    lowerCamelCase=False )    ->      np.ndarray:







					"""simple docstring"""






					snake_case__      ,snake_case__			:			List[Any]             =		original_size
					snake_case__      ,snake_case__			:			List[Any]             =		self.image_processor._get_preprocess_shape(lowerCamelCase       ,    longest_edge=lowerCamelCase )
					snake_case__			:			Optional[int]             =		deepcopy(lowerCamelCase ).astype(lowerCamelCase )

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

					snake_case__			:			Dict             =		coords[..., 0] * (new_w / old_w)
					snake_case__			:			Union[str, Any]             =		coords[..., 1] * (new_h / old_h)

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

					return coords





				def    lowercase__							(	self       ,    lowerCamelCase=None       ,    lowerCamelCase=None       ,    lowerCamelCase=None       ,    )    ->      Dict:







					"""simple docstring"""






					if input_points is not None:
						if hasattr(lowerCamelCase       ,    '''numpy''' ):  # Checks for TF or Torch tensor
							snake_case__			:			Optional[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__			:			List[Any]             =		[np.array(lowerCamelCase ) for input_point in input_points]
					else:
						snake_case__			:			List[str]             =		None

					if input_labels is not None:
						if hasattr(lowerCamelCase       ,    '''numpy''' ):
							snake_case__			:			int             =		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__			:			int             =		None

					if input_boxes is not None:
						if hasattr(lowerCamelCase       ,    '''numpy''' ):
							snake_case__			:			List[str]             =		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__			:			List[str]             =		[np.array(lowerCamelCase ).astype(np.floataa ) for box in input_boxes]
					else:
						snake_case__			:			Any             =		None

					return input_points, input_labels, input_boxes





				@property
				def    lowercase__							(	self )    ->      Union[str, Any]:







					"""simple docstring"""






					snake_case__			:			Dict             =		self.image_processor.model_input_names
					return list(dict.fromkeys(lowerCamelCase ) )





				def    lowercase__							(	self       ,    *lowerCamelCase       ,    **lowerCamelCase )    ->      List[str]:







					"""simple docstring"""






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










'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


lowercase_									=    {
    "configuration_blip": [
        "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "BlipConfig",
        "BlipTextConfig",
        "BlipVisionConfig",
    ],
    "processing_blip": ["BlipProcessor"],
}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    ["BlipImageProcessor"]


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    [
      "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
      "BlipModel",
      "BlipPreTrainedModel",
      "BlipForConditionalGeneration",
      "BlipForQuestionAnswering",
      "BlipVisionModel",
      "BlipTextModel",
      "BlipForImageTextRetrieval",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    [
      "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
      "TFBlipModel",
      "TFBlipPreTrainedModel",
      "TFBlipForConditionalGeneration",
      "TFBlipForQuestionAnswering",
      "TFBlipVisionModel",
      "TFBlipTextModel",
      "TFBlipForImageTextRetrieval",
  ]

if TYPE_CHECKING:
  from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
  from .processing_blip import BlipProcessor

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_blip import BlipImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_blip import (
        BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
        BlipForConditionalGeneration,
        BlipForImageTextRetrieval,
        BlipForQuestionAnswering,
        BlipModel,
        BlipPreTrainedModel,
        BlipTextModel,
        BlipVisionModel,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_blip import (
        TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFBlipForConditionalGeneration,
        TFBlipForImageTextRetrieval,
        TFBlipForQuestionAnswering,
        TFBlipModel,
        TFBlipPreTrainedModel,
        TFBlipTextModel,
        TFBlipVisionModel,
    )

else:
  import sys

  lowercase_									=    _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



