


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


  def __init__(			self:						Tuple							,__lowerCAmelCase:						List[Any]    ):







     '''simple docstring'''







     super().__init__(__lowerCAmelCase    )
     _lowerCamelCase   :				int							=     self.image_processor
     _lowerCamelCase   :				str							=     -10
     _lowerCamelCase   :				Optional[Any]							=     self.image_processor.size["longest_edge"]


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







     '''simple docstring'''







     _lowerCamelCase   :				Union[str, Any]							=     self.image_processor(
         __lowerCAmelCase							,return_tensors=__lowerCAmelCase							,**__lowerCAmelCase							,)

     # pop arguments that are not used in the foward but used nevertheless
     _lowerCamelCase   :				Union[str, Any]							=     encoding_image_processor["original_sizes"]

     if hasattr(__lowerCAmelCase							,"numpy"    ):  # Checks if Torch or TF tensor
        _lowerCamelCase   :				Dict							=     original_sizes.numpy()

     _lowerCamelCase,					_lowerCamelCase,					_lowerCamelCase   :				Dict							=     self._check_and_preprocess_points(
         input_points=__lowerCAmelCase							,input_labels=__lowerCAmelCase							,input_boxes=__lowerCAmelCase							,)

     _lowerCamelCase   :				Optional[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:						Optional[int]							,__lowerCAmelCase:						Tuple							,__lowerCAmelCase:						str							,__lowerCAmelCase:						Tuple=None							,__lowerCAmelCase:						Optional[Any]=None							,__lowerCAmelCase:						Union[str, Any]=None							,__lowerCAmelCase:						Union[str, Any]="pt"							,):







     '''simple docstring'''







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

        _lowerCamelCase   :				List[str]							=     np.array(__lowerCAmelCase    )

     if input_labels is not None:
        _lowerCamelCase   :				Union[str, Any]							=     np.array(__lowerCAmelCase    )

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

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







     '''simple docstring'''







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


  def 							_lowercase					(			self:						Any							,__lowerCAmelCase:						int							,__lowerCAmelCase:						np.ndarray							,__lowerCAmelCase:						List[str]							,__lowerCAmelCase:						List[str]=False    ):







     '''simple docstring'''







     _lowerCamelCase,					_lowerCamelCase   :				int							=     original_size
     _lowerCamelCase,					_lowerCamelCase   :				Dict							=     self.image_processor._get_preprocess_shape(__lowerCAmelCase							,longest_edge=__lowerCAmelCase    )
     _lowerCamelCase   :				Dict							=     deepcopy(__lowerCAmelCase    ).astype(__lowerCAmelCase    )

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

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

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

     return coords


  def 							_lowercase					(			self:						int							,__lowerCAmelCase:						List[Any]=None							,__lowerCAmelCase:						Optional[int]=None							,__lowerCAmelCase:						str=None							,):







     '''simple docstring'''







     if input_points is not None:
        if hasattr(__lowerCAmelCase							,"numpy"    ):  # Checks for TF or Torch tensor
           _lowerCamelCase   :				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."    )
        _lowerCamelCase   :				Union[str, Any]							=     [np.array(__lowerCAmelCase    ) for input_point in input_points]
     else:
        _lowerCamelCase   :				Dict							=     None

     if input_labels is not None:
        if hasattr(__lowerCAmelCase							,"numpy"    ):
           _lowerCamelCase   :				Any							=     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."    )
        _lowerCamelCase   :				Any							=     [np.array(__lowerCAmelCase    ) for label in input_labels]
     else:
        _lowerCamelCase   :				Tuple							=     None

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

     return input_points, input_labels, input_boxes


  @property
  def 							_lowercase					(			self:						int    ):







     '''simple docstring'''







     _lowerCamelCase   :				List[str]							=     self.image_processor.model_input_names
     return list(dict.fromkeys(__lowerCAmelCase    )    )






  def 							_lowercase					(			self:						List[str]							,*__lowerCAmelCase:						int							,**__lowerCAmelCase:						Tuple    ):







     '''simple docstring'''







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






'''simple docstring'''






import functools
import operator

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


lowerCAmelCase									=   logging.get_logger(__name__)

lowerCAmelCase									=   {
    """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}
class 		lowerCamelCase	(   _A							):
	snake_case_   = "sew-d"



	def __init__( self		,   a_=32		,   a_=768		,   a_=12		,   a_=12		,   a_=3_072		,   a_=2		,   a_=512		,   a_=256		,   a_=True		,   a_=True		,   a_=("p2c", "c2p")		,   a_="layer_norm"		,   a_="gelu_python"		,   a_=0.1		,   a_=0.1		,   a_=0.1		,   a_=0.0		,   a_=0.1		,   a_=0.02		,   a_=1e-7		,   a_=1e-5		,   a_="group"		,   a_="gelu"		,   a_=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)		,   a_=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)		,   a_=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)		,   a_=False		,   a_=128		,   a_=16		,   a_=True		,   a_=0.05		,   a_=10		,   a_=2		,   a_=0.0		,   a_=10		,   a_=0		,   a_="mean"		,   a_=False		,   a_=False		,   a_=256		,   a_=0		,   a_=1		,   a_=2		,   **a_		,   ):
			super().__init__(**a_		,   pad_token_id=a_		,   bos_token_id=a_		,   eos_token_id=a_						)
			lowerCAmelCase  :     Optional[int]       						= hidden_size
			lowerCAmelCase  :     Optional[int]       						= feat_extract_norm
			lowerCAmelCase  :     str       						= feat_extract_activation
			lowerCAmelCase  :     Dict       						= list(a_						)
			lowerCAmelCase  :     int       						= list(a_						)
			lowerCAmelCase  :     Any       						= list(a_						)
			lowerCAmelCase  :     Optional[Any]       						= conv_bias
			lowerCAmelCase  :     Tuple       						= num_conv_pos_embeddings
			lowerCAmelCase  :     int       						= num_conv_pos_embedding_groups
			lowerCAmelCase  :     Optional[int]       						= len(self.conv_dim						)
			lowerCAmelCase  :     Dict       						= num_hidden_layers
			lowerCAmelCase  :     str       						= intermediate_size
			lowerCAmelCase  :     Any       						= squeeze_factor
			lowerCAmelCase  :     Optional[int]       						= max_position_embeddings
			lowerCAmelCase  :     Tuple       						= position_buckets
			lowerCAmelCase  :     Union[str, Any]       						= share_att_key
			lowerCAmelCase  :     str       						= relative_attention
			lowerCAmelCase  :     List[str]       						= norm_rel_ebd
			lowerCAmelCase  :     int       						= list(a_						)
			lowerCAmelCase  :     str       						= hidden_act
			lowerCAmelCase  :     Dict       						= num_attention_heads
			lowerCAmelCase  :     Optional[Any]       						= hidden_dropout
			lowerCAmelCase  :     int       						= attention_dropout
			lowerCAmelCase  :     Optional[int]       						= activation_dropout
			lowerCAmelCase  :     Any       						= feat_proj_dropout
			lowerCAmelCase  :     Optional[int]       						= final_dropout
			lowerCAmelCase  :     Union[str, Any]       						= layer_norm_eps
			lowerCAmelCase  :     str       						= feature_layer_norm_eps
			lowerCAmelCase  :     Tuple       						= initializer_range
			lowerCAmelCase  :     int       						= vocab_size

			if (
			    (len(self.conv_stride						) != self.num_feat_extract_layers)
			    or (len(self.conv_kernel						) != self.num_feat_extract_layers)
			    or (len(self.conv_dim						) != self.num_feat_extract_layers)
			):
					raise ValueError(
					    "Configuration for convolutional layers is incorrect."
					    "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"
					    F'''but is `len(config.conv_dim) = {len(self.conv_dim						)}`, `len(config.conv_stride)'''
					    F'''= {len(self.conv_stride						)}`, `len(config.conv_kernel) = {len(self.conv_kernel						)}`.'''						)

			# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
			lowerCAmelCase  :     List[str]       						= apply_spec_augment
			lowerCAmelCase  :     List[Any]       						= mask_time_prob
			lowerCAmelCase  :     Tuple       						= mask_time_length
			lowerCAmelCase  :     List[Any]       						= mask_time_min_masks
			lowerCAmelCase  :     List[str]       						= mask_feature_prob
			lowerCAmelCase  :     Union[str, Any]       						= mask_feature_length
			lowerCAmelCase  :     List[Any]       						= mask_feature_min_masks

			# ctc loss
			lowerCAmelCase  :     Any       						= ctc_loss_reduction
			lowerCAmelCase  :     str       						= ctc_zero_infinity

			# sequence classification
			lowerCAmelCase  :     Dict       						= use_weighted_layer_sum
			lowerCAmelCase  :     Tuple       						= classifier_proj_size





	@property
	def 	_lowerCamelCase     ( self						):
			return functools.reduce(operator.mul		,   self.conv_stride		,   1						)



