





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							):
					_a      :						Optional[int]						    =					['image_processor']
					_a      :						Any						    =					'SamImageProcessor'



					def __init__(		self     :     List[str]       ,      lowerCamelCase     :     Tuple						):
							super().__init__(UpperCamelCase__						)
							lowerCamelCase_	:     Any 						=      self.image_processor
							lowerCamelCase_	:     Optional[Any] 						=      -10
							lowerCamelCase_	:     Any 						=      self.image_processor.size['longest_edge']



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

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

							if hasattr(UpperCamelCase__       ,      'numpy'						):  # Checks if Torch or TF tensor
									lowerCamelCase_	:     Union[str, Any] 						=      original_sizes.numpy()

							lowerCamelCase_						,      lowerCamelCase_						,      lowerCamelCase_	:     List[str] 						=      self._check_and_preprocess_points(
							    input_points=UpperCamelCase__       ,      input_labels=UpperCamelCase__       ,      input_boxes=UpperCamelCase__       ,      )

							lowerCamelCase_	:     Any 						=      self._normalize_and_convert(
							    UpperCamelCase__       ,      UpperCamelCase__       ,      input_points=UpperCamelCase__       ,      input_labels=UpperCamelCase__       ,      input_boxes=UpperCamelCase__       ,      return_tensors=UpperCamelCase__       ,      )

							return encoding_image_processor



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

									lowerCamelCase_	:     Optional[Any] 						=      np.array(UpperCamelCase__						)

							if input_labels is not None:
									lowerCamelCase_	:     Any 						=      np.array(UpperCamelCase__						)

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

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



					def   __a     (		self     :     str       ,      lowerCamelCase     :     int       ,      lowerCamelCase     :     np.ndarray       ,      lowerCamelCase     :     Optional[Any]       ,      lowerCamelCase     :     Any=False						):
							lowerCamelCase_						,      lowerCamelCase_	:     str 						=      original_size
							lowerCamelCase_						,      lowerCamelCase_	:     Union[str, Any] 						=      self.image_processor._get_preprocess_shape(UpperCamelCase__       ,      longest_edge=UpperCamelCase__						)
							lowerCamelCase_	:     Union[str, Any] 						=      deepcopy(UpperCamelCase__						).astype(UpperCamelCase__						)

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

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

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

							return coords



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

							if input_labels is not None:
									if hasattr(UpperCamelCase__       ,      'numpy'						):
											lowerCamelCase_	:     Optional[Any] 						=      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.'						)
									lowerCamelCase_	:     Union[str, Any] 						=      [np.array(UpperCamelCase__						) for label in input_labels]
							else:
									lowerCamelCase_	:     List[Any] 						=      None

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

							return input_points, input_labels, input_boxes



					@property
					def   __a     (		self     :     int						):
							lowerCamelCase_	:     List[str] 						=      self.image_processor.model_input_names
							return list(dict.fromkeys(UpperCamelCase__						)						)





					def   __a     (		self     :     Optional[Any]       ,      *lowerCamelCase     :     int       ,      **lowerCamelCase     :     Any						):
							return self.image_processor.post_process_masks(*UpperCamelCase__       ,      **UpperCamelCase__						)

'''simple docstring'''






import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand





def  _SCREAMING_SNAKE_CASE		(      __snake_case							:			Union[str, Any]				):
     return EnvironmentCommand()







class lowercase_       (		_UpperCamelCase			):







   """simple docstring"""

   @staticmethod
   def 	__UpperCAmelCase   (      UpperCamelCase__      :			ArgumentParser     )  ->			List[str]:
        _A    		=  parser.add_parser('env'     )
        download_parser.set_defaults(func=UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			Optional[Any]:
        _A    		=  huggingface_hub.__version__

        _A    		=  'not installed'
        _A    		=  'NA'
        if is_torch_available():
             import torch

             _A    		=  torch.__version__
             _A    		=  torch.cuda.is_available()

        _A    		=  'not installed'
        if is_transformers_available():
             import transformers

             _A    		=  transformers.__version__

        _A    		=  'not installed'
        if is_accelerate_available():
             import accelerate

             _A    		=  accelerate.__version__

        _A    		=  'not installed'
        if is_xformers_available():
             import xformers

             _A    		=  xformers.__version__

        _A    		=  {
            '`diffusers` version': version,
            'Platform': platform.platform(),
            'Python version': platform.python_version(),
            'PyTorch version (GPU?)': f'{pt_version} ({pt_cuda_available})',
            'Huggingface_hub version': hub_version,
            'Transformers version': transformers_version,
            'Accelerate version': accelerate_version,
            'xFormers version': xformers_version,
            'Using GPU in script?': '<fill in>',
            'Using distributed or parallel set-up in script?': '<fill in>',
        }

        print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'     )
        print(self.format_dict(UpperCamelCase__     )     )

        return info

   @staticmethod
   def 	__UpperCAmelCase   (      UpperCamelCase__      :			List[Any]     )  ->			Dict:
        return "\n".join([f'- {prop}: {val}' for prop, val in d.items()]     ) + "\n"



