




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	(   UpperCamelCase__   ):




    """simple docstring"""

    snake_case__ =				["image_processor"]
    snake_case__ =				"SamImageProcessor"


    def __init__(	self					:					str       ,     SCREAMING_SNAKE_CASE__					:					str       )				->	str:
         super().__init__(SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			self.image_processor
         lowerCAmelCase__          =			-10
         lowerCAmelCase__          =			self.image_processor.size["longest_edge"]


    def __call__(	self					:					List[Any]       ,     SCREAMING_SNAKE_CASE__					:					Optional[int]=None       ,     SCREAMING_SNAKE_CASE__					:					Optional[Any]=None       ,     SCREAMING_SNAKE_CASE__					:					Any=None       ,     SCREAMING_SNAKE_CASE__					:					List[str]=None       ,     SCREAMING_SNAKE_CASE__					:					Optional[Union[str, TensorType]] = None       ,     **SCREAMING_SNAKE_CASE__					:					Tuple       ,     )				->	BatchEncoding:
         lowerCAmelCase__          =			self.image_processor(
             SCREAMING_SNAKE_CASE__       ,     return_tensors=SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       ,     )

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

         if hasattr(SCREAMING_SNAKE_CASE__       ,     "numpy"       ):  # Checks if Torch or TF tensor
              lowerCAmelCase__          =			original_sizes.numpy()

         lowerCAmelCase__     ,		lowerCAmelCase__     ,		lowerCAmelCase__          =			self._check_and_preprocess_points(
             input_points=SCREAMING_SNAKE_CASE__       ,     input_labels=SCREAMING_SNAKE_CASE__       ,     input_boxes=SCREAMING_SNAKE_CASE__       ,     )

         lowerCAmelCase__          =			self._normalize_and_convert(
             SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     input_points=SCREAMING_SNAKE_CASE__       ,     input_labels=SCREAMING_SNAKE_CASE__       ,     input_boxes=SCREAMING_SNAKE_CASE__       ,     return_tensors=SCREAMING_SNAKE_CASE__       ,     )

         return encoding_image_processor


    def        a				(	self					:					Tuple       ,     SCREAMING_SNAKE_CASE__					:					Tuple       ,     SCREAMING_SNAKE_CASE__					:					List[str]       ,     SCREAMING_SNAKE_CASE__					:					List[str]=None       ,     SCREAMING_SNAKE_CASE__					:					str=None       ,     SCREAMING_SNAKE_CASE__					:					Dict=None       ,     SCREAMING_SNAKE_CASE__					:					Optional[int]="pt"       ,     )				->	str:
         if input_points is not None:
              if len(SCREAMING_SNAKE_CASE__       ) != len(SCREAMING_SNAKE_CASE__       ):
                   lowerCAmelCase__          =			[
                       self._normalize_coordinates(self.target_size       ,     SCREAMING_SNAKE_CASE__       ,     original_sizes[0]       ) for point in input_points
                   ]
              else:
                   lowerCAmelCase__          =			[
                       self._normalize_coordinates(self.target_size       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
                       for point, original_size in zip(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
                   ]
              # 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__          =			self._pad_points_and_labels(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )

              lowerCAmelCase__          =			np.array(SCREAMING_SNAKE_CASE__       )

         if input_labels is not None:
              lowerCAmelCase__          =			np.array(SCREAMING_SNAKE_CASE__       )

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

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


    def        a				(	self					:					Dict       ,     SCREAMING_SNAKE_CASE__					:					int       ,     SCREAMING_SNAKE_CASE__					:					np.ndarray       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]=False       )				->	np.ndarray:
         lowerCAmelCase__     ,		lowerCAmelCase__          =			original_size
         lowerCAmelCase__     ,		lowerCAmelCase__          =			self.image_processor._get_preprocess_shape(SCREAMING_SNAKE_CASE__       ,     longest_edge=SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			deepcopy(SCREAMING_SNAKE_CASE__       ).astype(SCREAMING_SNAKE_CASE__       )

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

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

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

         return coords


    def        a				(	self					:					List[Any]       ,     SCREAMING_SNAKE_CASE__					:					Optional[Any]=None       ,     SCREAMING_SNAKE_CASE__					:					Optional[Any]=None       ,     SCREAMING_SNAKE_CASE__					:					Dict=None       ,     )				->	Dict:
         if input_points is not None:
              if hasattr(SCREAMING_SNAKE_CASE__       ,     "numpy"       ):  # Checks for TF or Torch tensor
                   lowerCAmelCase__          =			input_points.numpy().tolist()

              if not isinstance(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ) or not isinstance(input_points[0]       ,     SCREAMING_SNAKE_CASE__       ):
                   raise ValueError("Input points must be a list of list of floating points."       )
              lowerCAmelCase__          =			[np.array(SCREAMING_SNAKE_CASE__       ) for input_point in input_points]
         else:
              lowerCAmelCase__          =			None

         if input_labels is not None:
              if hasattr(SCREAMING_SNAKE_CASE__       ,     "numpy"       ):
                   lowerCAmelCase__          =			input_labels.numpy().tolist()

              if not isinstance(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ) or not isinstance(input_labels[0]       ,     SCREAMING_SNAKE_CASE__       ):
                   raise ValueError("Input labels must be a list of list integers."       )
              lowerCAmelCase__          =			[np.array(SCREAMING_SNAKE_CASE__       ) for label in input_labels]
         else:
              lowerCAmelCase__          =			None

         if input_boxes is not None:
              if hasattr(SCREAMING_SNAKE_CASE__       ,     "numpy"       ):
                   lowerCAmelCase__          =			input_boxes.numpy().tolist()

              if (
                  not isinstance(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
                  or not isinstance(input_boxes[0]       ,     SCREAMING_SNAKE_CASE__       )
                  or not isinstance(input_boxes[0][0]       ,     SCREAMING_SNAKE_CASE__       )
              ):
                   raise ValueError("Input boxes must be a list of list of list of floating points."       )
              lowerCAmelCase__          =			[np.array(SCREAMING_SNAKE_CASE__       ).astype(np.floataa       ) for box in input_boxes]
         else:
              lowerCAmelCase__          =			None

         return input_points, input_labels, input_boxes


    @property
    def        a				(	self					:					Optional[Any]       )				->	List[str]:
         lowerCAmelCase__          =			self.image_processor.model_input_names
         return list(dict.fromkeys(SCREAMING_SNAKE_CASE__       )       )


    def        a				(	self					:					Tuple       ,     *SCREAMING_SNAKE_CASE__					:					Dict       ,     **SCREAMING_SNAKE_CASE__					:					List[str]       )				->	int:
         return self.image_processor.post_process_masks(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )






import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin





class 			__lowerCamelCase	(   UpperCamelCase__   ):




    """simple docstring"""

    snake_case__ =				"Speech2TextFeatureExtractor"
    snake_case__ =				"Speech2TextTokenizer"


    def __init__(	self					:					int       ,     SCREAMING_SNAKE_CASE__					:					Dict       ,     SCREAMING_SNAKE_CASE__					:					Tuple       )				->	Optional[Any]:
         super().__init__(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			self.feature_extractor
         lowerCAmelCase__          =			False


    def __call__(	self					:					str       ,     *SCREAMING_SNAKE_CASE__					:					int       ,     **SCREAMING_SNAKE_CASE__					:					int       )				->	Optional[Any]:
         # For backward compatibility
         if self._in_target_context_manager:
              return self.current_processor(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )

         if "raw_speech" in kwargs:
              warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."       )
              lowerCAmelCase__          =			kwargs.pop("raw_speech"       )
         else:
              lowerCAmelCase__          =			kwargs.pop("audio"       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			kwargs.pop("sampling_rate"       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			kwargs.pop("text"       ,     SCREAMING_SNAKE_CASE__       )
         if len(SCREAMING_SNAKE_CASE__       ) > 0:
              lowerCAmelCase__          =			args[0]
              lowerCAmelCase__          =			args[1:]

         if audio is None and text is None:
              raise ValueError("You need to specify either an `audio` or `text` input to process."       )

         if audio is not None:
              lowerCAmelCase__          =			self.feature_extractor(SCREAMING_SNAKE_CASE__       ,     *SCREAMING_SNAKE_CASE__       ,     sampling_rate=SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )
         if text is not None:
              lowerCAmelCase__          =			self.tokenizer(SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )

         if text is None:
              return inputs
         elif audio is None:
              return encodings
         else:
              lowerCAmelCase__          =			encodings["input_ids"]
              return inputs


    def        a				(	self					:					str       ,     *SCREAMING_SNAKE_CASE__					:					Dict       ,     **SCREAMING_SNAKE_CASE__					:					int       )				->	Union[str, Any]:
         return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )


    def        a				(	self					:					Dict       ,     *SCREAMING_SNAKE_CASE__					:					Optional[int]       ,     **SCREAMING_SNAKE_CASE__					:					Optional[int]       )				->	Optional[Any]:
         return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )


    @contextmanager
    def        a				(	self					:					Union[str, Any]       )				->	Any:
         warnings.warn(
             "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
             "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
             "your audio inputs, or in a separate call."       )
         lowerCAmelCase__          =			True
         lowerCAmelCase__          =			self.tokenizer
         yield
         lowerCAmelCase__          =			self.feature_extractor
         lowerCAmelCase__          =			False
