

'''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 							A__    (       A__  ):
  A__		 =				['image_processor']
  A__		 =				'SamImageProcessor'





  def __init__(		self      :	Optional[Any]							,					_a      :	Any )	->    Dict:





       '''simple docstring'''






       super().__init__(_a )
       _SCREAMING_SNAKE_CASE							    =self.image_processor
       _SCREAMING_SNAKE_CASE							    =-10
       _SCREAMING_SNAKE_CASE							    =self.image_processor.size['longest_edge']





  def __call__(		self      :	Any							,					_a      :	Optional[int]=None							,					_a      :	str=None							,					_a      :	str=None							,					_a      :	Any=None							,					_a      :	Optional[Union[str, TensorType]] = None							,					**_a      :	Optional[int]							,					)	->    BatchEncoding:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processor(
           _a							,					return_tensors=_a							,					**_a							,					)

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

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

       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =self._check_and_preprocess_points(
           input_points=_a							,					input_labels=_a							,					input_boxes=_a							,					)

       _SCREAMING_SNAKE_CASE							    =self._normalize_and_convert(
           _a							,					_a							,					input_points=_a							,					input_labels=_a							,					input_boxes=_a							,					return_tensors=_a							,					)

       return encoding_image_processor





  def 						A  (		self      :	List[str]							,					_a      :	str							,					_a      :	Optional[Any]							,					_a      :	Optional[int]=None							,					_a      :	Union[str, Any]=None							,					_a      :	Optional[int]=None							,					_a      :	Union[str, Any]="pt"							,					)	->    Optional[int]:





       '''simple docstring'''






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

            _SCREAMING_SNAKE_CASE							    =np.array(_a )

       if input_labels is not None:
            _SCREAMING_SNAKE_CASE							    =np.array(_a )

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

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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =max([point.shape[0] for point in input_points] )
       _SCREAMING_SNAKE_CASE							    =[]
       for i, point in enumerate(_a ):
            if point.shape[0] != expected_nb_points:
                 _SCREAMING_SNAKE_CASE							    =np.concatenate(
                     [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value]							,					axis=0 )
                 _SCREAMING_SNAKE_CASE							    =np.append(input_labels[i]							,					[self.point_pad_value] )
            processed_input_points.append(_a )
       _SCREAMING_SNAKE_CASE							    =processed_input_points
       return input_points, input_labels





  def 						A  (		self      :	str							,					_a      :	int							,					_a      :	np.ndarray							,					_a      :	str							,					_a      :	List[str]=False )	->    np.ndarray:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =original_size
       _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE							    =self.image_processor._get_preprocess_shape(_a							,					longest_edge=_a )
       _SCREAMING_SNAKE_CASE							    =deepcopy(_a ).astype(_a )

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

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

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

       return coords





  def 						A  (		self      :	List[str]							,					_a      :	Optional[int]=None							,					_a      :	Optional[int]=None							,					_a      :	Union[str, Any]=None							,					)	->    Dict:





       '''simple docstring'''






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

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

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

       return input_points, input_labels, input_boxes





  @property
  def 						A  (		self      :	List[Any] )	->    str:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processor.model_input_names
       return list(dict.fromkeys(_a ) )





  def 						A  (		self      :	Optional[int]							,					*_a      :	str							,					**_a      :	List[Any] )	->    str:





       '''simple docstring'''






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



'''simple docstring'''
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path

import torch_xla.distributed.xla_multiprocessing as xmp


def        _lowerCAmelCase					(						)      ->			Any:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =ArgumentParser(
         description=(
             'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes'
         )				)

     # Optional arguments for the launch helper
     parser.add_argument('--num_cores'							, type=_UpperCamelCase							, default=1							, help='Number of TPU cores to use (1 or 8).'				)

     # positional
     parser.add_argument(
         'training_script'							, type=_UpperCamelCase							, help=(
             'The full path to the single TPU training '
             'program/script to be launched in parallel, '
             'followed by all the arguments for the '
             'training script'
         )							, )

     # rest from the training program
     parser.add_argument('training_script_args'							, nargs=_UpperCamelCase				)

     return parser.parse_args()


def        _lowerCAmelCase					(						)      ->			Optional[int]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =parse_args()

     # Import training_script as a module.
     _SCREAMING_SNAKE_CASE							    =Path(args.training_script				)
     sys.path.append(str(script_fpath.parent.resolve()				)				)
     _SCREAMING_SNAKE_CASE							    =script_fpath.stem
     _SCREAMING_SNAKE_CASE							    =importlib.import_module(_UpperCamelCase				)

     # Patch sys.argv
     _SCREAMING_SNAKE_CASE							    =[args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores				)]

     xmp.spawn(mod._mp_fn							, args=()							, nprocs=args.num_cores				)


if __name__ == "__main__":
     main()
