





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






       def __init__(   self    ,  a__     ):
              super().__init__(a__     )
              _UpperCAmelCase     =     self.image_processor
              _UpperCAmelCase     =     -10
              _UpperCAmelCase     =     self.image_processor.size['longest_edge']






       def __call__(   self    ,  a__=None    ,  a__=None    ,  a__=None    ,  a__=None    ,  a__ = None    ,  **a__    ,  ):
              _UpperCAmelCase     =     self.image_processor(
                  a__    ,  return_tensors=a__    ,  **a__    ,  )

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

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

              _UpperCAmelCase    ,							_UpperCAmelCase    ,							_UpperCAmelCase     =     self._check_and_preprocess_points(
                  input_points=a__    ,  input_labels=a__    ,  input_boxes=a__    ,  )

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

                     _UpperCAmelCase     =     np.array(a__     )

              if input_labels is not None:
                     _UpperCAmelCase     =     np.array(a__     )

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

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






       def 							__A (   self    ,  a__    ,  a__    ,  a__    ,  a__=False     ):
              _UpperCAmelCase    ,							_UpperCAmelCase     =     original_size
              _UpperCAmelCase    ,							_UpperCAmelCase     =     self.image_processor._get_preprocess_shape(a__    ,  longest_edge=a__     )
              _UpperCAmelCase     =     deepcopy(a__     ).astype(a__     )

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

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

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

              return coords






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

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

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

              return input_points, input_labels, input_boxes






       @property
       def 							__A (   self     ):
              _UpperCAmelCase     =     self.image_processor.model_input_names
              return list(dict.fromkeys(a__     )     )






       def 							__A (   self    ,  *a__    ,  **a__     ):
              return self.image_processor.post_process_masks(*a__    ,  **a__     )













"""simple docstring"""






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


lowerCAmelCase_			=							logging.get_logger(__name__)

lowerCAmelCase_			=							{
    '''microsoft/trocr-base-handwritten''': (
        '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json'''
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}



class 	lowerCAmelCase					(      snake_case							):
       lowerCAmelCase__						 =  """trocr"""
       lowerCAmelCase__						 =  ["""past_key_values"""]
       lowerCAmelCase__						 =  {
           """num_attention_heads""": """decoder_attention_heads""",
           """hidden_size""": """d_model""",
           """num_hidden_layers""": """decoder_layers""",
       }






       def __init__(   self    ,  a__=5_02_65    ,  a__=10_24    ,  a__=12    ,  a__=16    ,  a__=40_96    ,  a__="gelu"    ,  a__=5_12    ,  a__=0.1    ,  a__=0.0    ,  a__=0.0    ,  a__=2    ,  a__=0.02    ,  a__=0.0    ,  a__=True    ,  a__=False    ,  a__=True    ,  a__=True    ,  a__=1    ,  a__=0    ,  a__=2    ,  **a__    ,  ):
              _UpperCAmelCase     =     vocab_size
              _UpperCAmelCase     =     d_model
              _UpperCAmelCase     =     decoder_layers
              _UpperCAmelCase     =     decoder_attention_heads
              _UpperCAmelCase     =     decoder_ffn_dim
              _UpperCAmelCase     =     activation_function
              _UpperCAmelCase     =     max_position_embeddings
              _UpperCAmelCase     =     dropout
              _UpperCAmelCase     =     attention_dropout
              _UpperCAmelCase     =     activation_dropout
              _UpperCAmelCase     =     init_std
              _UpperCAmelCase     =     decoder_layerdrop
              _UpperCAmelCase     =     use_cache
              _UpperCAmelCase     =     scale_embedding
              _UpperCAmelCase     =     use_learned_position_embeddings
              _UpperCAmelCase     =     layernorm_embedding

              super().__init__(
                  pad_token_id=a__    ,  bos_token_id=a__    ,  eos_token_id=a__    ,  decoder_start_token_id=a__    ,  **a__    ,  )






