





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



      """simple docstring"""






      UpperCAmelCase_  :					Any      			=["image_processor"]
      UpperCAmelCase_  :					Optional[Any]      			="SamImageProcessor"







      def __init__(       self ,  UpperCAmelCase      )				->      Dict:






        '''simple docstring'''






        super().__init__(UpperCAmelCase_      )
        __snake_case      : Union[str, Any]						=				self.image_processor
        __snake_case      : str						=				-10
        __snake_case      : Tuple						=				self.image_processor.size["longest_edge"]







      def __call__(       self ,  UpperCAmelCase=None ,  UpperCAmelCase=None ,  UpperCAmelCase=None ,  UpperCAmelCase=None ,  UpperCAmelCase = None ,  **UpperCAmelCase ,  )				->      BatchEncoding:






        '''simple docstring'''






        __snake_case      : Any						=				self.image_processor(
            UpperCAmelCase_ ,  return_tensors=UpperCAmelCase_ ,  **UpperCAmelCase_ ,  )

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

        if hasattr(UpperCAmelCase_ ,  "numpy"      ):  # Checks if Torch or TF tensor
          __snake_case      : Optional[Any]						=				original_sizes.numpy()

        __snake_case      : Any						=				self._check_and_preprocess_points(
            input_points=UpperCAmelCase_ ,  input_labels=UpperCAmelCase_ ,  input_boxes=UpperCAmelCase_ ,  )

        __snake_case      : Optional[int]						=				self._normalize_and_convert(
            UpperCAmelCase_ ,  UpperCAmelCase_ ,  input_points=UpperCAmelCase_ ,  input_labels=UpperCAmelCase_ ,  input_boxes=UpperCAmelCase_ ,  return_tensors=UpperCAmelCase_ ,  )

        return encoding_image_processor







      def   UpperCAmelCase						(       self ,  UpperCAmelCase ,  UpperCAmelCase ,  UpperCAmelCase=None ,  UpperCAmelCase=None ,  UpperCAmelCase=None ,  UpperCAmelCase="pt" ,  )				->      List[str]:






        '''simple docstring'''






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

          __snake_case      : Optional[Any]						=				np.array(UpperCAmelCase_      )

        if input_labels is not None:
          __snake_case      : Tuple						=				np.array(UpperCAmelCase_      )

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

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






        '''simple docstring'''






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







      def   UpperCAmelCase						(       self ,  UpperCAmelCase ,  UpperCAmelCase ,  UpperCAmelCase ,  UpperCAmelCase=False      )				->      np.ndarray:






        '''simple docstring'''






        __snake_case      : str						=				original_size
        __snake_case      : str						=				self.image_processor._get_preprocess_shape(UpperCAmelCase_ ,  longest_edge=UpperCAmelCase_      )
        __snake_case      : Optional[int]						=				deepcopy(UpperCAmelCase_      ).astype(UpperCAmelCase_      )

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

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

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

        return coords







      def   UpperCAmelCase						(       self ,  UpperCAmelCase=None ,  UpperCAmelCase=None ,  UpperCAmelCase=None ,  )				->      Optional[Any]:






        '''simple docstring'''






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

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

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

        return input_points, input_labels, input_boxes







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






        '''simple docstring'''






        __snake_case      : List[Any]						=				self.image_processor.model_input_names
        return list(dict.fromkeys(UpperCAmelCase_      )      )







      def   UpperCAmelCase						(       self ,  *UpperCAmelCase ,  **UpperCAmelCase      )				->      Tuple:






        '''simple docstring'''






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








import os
import unittest

from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer
from transformers.testing_utils import get_tests_dir

from ...test_tokenization_common import TokenizerTesterMixin


__A									=				get_tests_dir("fixtures/test_sentencepiece_bpe.model")



class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ,							unittest.TestCase    ):







 '''simple docstring'''
 lowercase_		=			BartphoTokenizer
 lowercase_		=			False
 lowercase_		=			True

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Tuple:



   '''simple docstring'''



   super().setUp()

   lowerCamelCase__:      int			  =["▁This", "▁is", "▁a", "▁t", "est"]
   lowerCamelCase__:      Tuple			  =dict(zip(UpperCAmelCase_       , range(len(UpperCAmelCase_))))
   lowerCamelCase__:      List[Any]			  ={"unk_token": "<unk>"}

   lowerCamelCase__:      Dict			  =os.path.join(self.tmpdirname       , VOCAB_FILES_NAMES["monolingual_vocab_file"])
   with open(self.monolingual_vocab_file       , "w"       , encoding="utf-8") as fp:
     for token in vocab_tokens:
       fp.write(F"""{token} {vocab_tokens[token]}\n""")

   lowerCamelCase__:      Dict			  =BartphoTokenizer(UpperCAmelCase_       , self.monolingual_vocab_file       , **self.special_tokens_map)
   tokenizer.save_pretrained(self.tmpdirname)

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[int]       , **UpperCAmelCase_				:   Optional[Any])       ->str:



   '''simple docstring'''



   kwargs.update(self.special_tokens_map)
   return BartphoTokenizer.from_pretrained(self.tmpdirname       , **UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_					(self				:   Union[str, Any]       , UpperCAmelCase_				:   Optional[Any])       ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  ="This is a là test"
   lowerCamelCase__:      Optional[Any]			  ="This is a<unk><unk> test"
   return input_text, output_text







 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:      str			  =BartphoTokenizer(UpperCAmelCase_       , self.monolingual_vocab_file       , **self.special_tokens_map)
   lowerCamelCase__:      List[Any]			  ="This is a là test"
   lowerCamelCase__:      Optional[int]			  ="▁This ▁is ▁a ▁l à ▁t est".split()
   lowerCamelCase__:      Optional[int]			  =tokenizer.tokenize(UpperCAmelCase_)
   self.assertListEqual(UpperCAmelCase_       , UpperCAmelCase_)

   lowerCamelCase__:      Tuple			  =tokens + [tokenizer.unk_token]
   lowerCamelCase__:      List[Any]			  =[4, 5, 6, 3, 3, 7, 8, 3]
   self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_)       , UpperCAmelCase_)

