


import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
   from PIL import Image

   from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
   import torch

if is_tf_available():
   import tensorflow as tf
@require_vision
@require_torchvision
class  SCREAMING_SNAKE_CASE__  (				unittest.TestCase			):
      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     )		->			Optional[int]:
             a_					:		Optional[Any]							=  tempfile.mkdtemp()
             a_					:		Any							=  SamImageProcessor()
             a_					:		int							=  SamProcessor(SCREAMING_SNAKE_CASE__     )
             processor.save_pretrained(self.tmpdirname     )
      def        SCREAMING_SNAKE_CASE							(       self				:       str     ,							**SCREAMING_SNAKE_CASE__				:       Any     )		->			Dict:
             return AutoProcessor.from_pretrained(self.tmpdirname     ,							**SCREAMING_SNAKE_CASE__     ).image_processor
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     )		->			Dict:
             shutil.rmtree(self.tmpdirname     )
      def        SCREAMING_SNAKE_CASE							(       self				:       List[Any]     )		->			Optional[Any]:
             a_					:		Tuple							=  [np.random.randint(2_5_5     ,							size=(3, 3_0, 4_0_0)     ,							dtype=np.uinta     )]

             a_					:		List[Any]							=  [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__     ,							0     ,							-1     )     ) for x in image_inputs]

             return image_inputs
      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     )		->			Union[str, Any]:
             a_					:		Dict							=  SamProcessor(image_processor=self.get_image_processor()     )
             processor.save_pretrained(self.tmpdirname     )

             a_					:		Tuple							=  self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__     ,							padding_value=1.0     )

             a_					:		List[str]							=  SamProcessor.from_pretrained(self.tmpdirname     ,							do_normalize=SCREAMING_SNAKE_CASE__     ,							padding_value=1.0     )

             self.assertEqual(processor.image_processor.to_json_string()     ,							image_processor_add_kwargs.to_json_string()     )
             self.assertIsInstance(processor.image_processor     ,							SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       List[Any]     )		->			Tuple:
             a_					:		Tuple							=  self.get_image_processor()

             a_					:		Union[str, Any]							=  SamProcessor(image_processor=SCREAMING_SNAKE_CASE__     )

             a_					:		Union[str, Any]							=  self.prepare_image_inputs()

             a_					:		Union[str, Any]							=  image_processor(SCREAMING_SNAKE_CASE__     ,							return_tensors='np'     )
             a_					:		int							=  processor(images=SCREAMING_SNAKE_CASE__     ,							return_tensors='np'     )

             input_feat_extract.pop('original_sizes'     )  # pop original_sizes as it is popped in the processor
             input_feat_extract.pop('reshaped_input_sizes'     )  # pop original_sizes as it is popped in the processor

             for key in input_feat_extract.keys():
                    self.assertAlmostEqual(input_feat_extract[key].sum()     ,							input_processor[key].sum()     ,							delta=1E-2     )

      @require_torch
      def        SCREAMING_SNAKE_CASE							(       self				:       List[Any]     )		->			List[Any]:
             a_					:		Optional[Any]							=  self.get_image_processor()

             a_					:		str							=  SamProcessor(image_processor=SCREAMING_SNAKE_CASE__     )
             a_					:		str							=  [torch.ones((1, 3, 5, 5)     )]

             a_					:		List[Any]							=  [[1_7_6_4, 2_6_4_6]]

             a_					:		Optional[int]							=  [[6_8_3, 1_0_2_4]]
             a_					:		Any							=  processor.post_process_masks(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )
             self.assertEqual(masks[0].shape     ,							(1, 3, 1_7_6_4, 2_6_4_6)     )

             a_					:		List[str]							=  processor.post_process_masks(
                 SCREAMING_SNAKE_CASE__     ,							torch.tensor(SCREAMING_SNAKE_CASE__     )     ,							torch.tensor(SCREAMING_SNAKE_CASE__     )     )
             self.assertEqual(masks[0].shape     ,							(1, 3, 1_7_6_4, 2_6_4_6)     )

             # should also work with np
             a_					:		Optional[Any]							=  [np.ones((1, 3, 5, 5)     )]
             a_					:		List[Any]							=  processor.post_process_masks(SCREAMING_SNAKE_CASE__     ,							np.array(SCREAMING_SNAKE_CASE__     )     ,							np.array(SCREAMING_SNAKE_CASE__     )     )

             self.assertEqual(masks[0].shape     ,							(1, 3, 1_7_6_4, 2_6_4_6)     )

             a_					:		Optional[int]							=  [[1, 0], [0, 1]]
             with self.assertRaises(SCREAMING_SNAKE_CASE__     ):
                    a_					:		Tuple							=  processor.post_process_masks(SCREAMING_SNAKE_CASE__     ,							np.array(SCREAMING_SNAKE_CASE__     )     ,							np.array(SCREAMING_SNAKE_CASE__     )     )
@require_vision
@require_tf
class  SCREAMING_SNAKE_CASE__  (				unittest.TestCase			):
      def        SCREAMING_SNAKE_CASE							(       self				:       Any     )		->			Any:
             a_					:		Any							=  tempfile.mkdtemp()
             a_					:		str							=  SamImageProcessor()
             a_					:		Dict							=  SamProcessor(SCREAMING_SNAKE_CASE__     )
             processor.save_pretrained(self.tmpdirname     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Any     ,							**SCREAMING_SNAKE_CASE__				:       Dict     )		->			List[Any]:
             return AutoProcessor.from_pretrained(self.tmpdirname     ,							**SCREAMING_SNAKE_CASE__     ).image_processor
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     )		->			str:
             shutil.rmtree(self.tmpdirname     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     )		->			List[Any]:
             a_					:		Optional[Any]							=  [np.random.randint(2_5_5     ,							size=(3, 3_0, 4_0_0)     ,							dtype=np.uinta     )]

             a_					:		Optional[int]							=  [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__     ,							0     ,							-1     )     ) for x in image_inputs]

             return image_inputs
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     )		->			str:
             a_					:		List[str]							=  SamProcessor(image_processor=self.get_image_processor()     )
             processor.save_pretrained(self.tmpdirname     )

             a_					:		Union[str, Any]							=  self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__     ,							padding_value=1.0     )

             a_					:		Tuple							=  SamProcessor.from_pretrained(self.tmpdirname     ,							do_normalize=SCREAMING_SNAKE_CASE__     ,							padding_value=1.0     )

             self.assertEqual(processor.image_processor.to_json_string()     ,							image_processor_add_kwargs.to_json_string()     )
             self.assertIsInstance(processor.image_processor     ,							SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     )		->			Dict:
             a_					:		Optional[int]							=  self.get_image_processor()

             a_					:		Optional[int]							=  SamProcessor(image_processor=SCREAMING_SNAKE_CASE__     )

             a_					:		List[str]							=  self.prepare_image_inputs()

             a_					:		str							=  image_processor(SCREAMING_SNAKE_CASE__     ,							return_tensors='np'     )
             a_					:		List[str]							=  processor(images=SCREAMING_SNAKE_CASE__     ,							return_tensors='np'     )

             input_feat_extract.pop('original_sizes'     )  # pop original_sizes as it is popped in the processor
             input_feat_extract.pop('reshaped_input_sizes'     )  # pop reshaped_input_sizes as it is popped in the processor

             for key in input_feat_extract.keys():
                    self.assertAlmostEqual(input_feat_extract[key].sum()     ,							input_processor[key].sum()     ,							delta=1E-2     )

      @require_tf
      def        SCREAMING_SNAKE_CASE							(       self				:       str     )		->			Optional[int]:
             a_					:		Optional[int]							=  self.get_image_processor()

             a_					:		List[Any]							=  SamProcessor(image_processor=SCREAMING_SNAKE_CASE__     )
             a_					:		Union[str, Any]							=  [tf.ones((1, 3, 5, 5)     )]

             a_					:		List[Any]							=  [[1_7_6_4, 2_6_4_6]]

             a_					:		int							=  [[6_8_3, 1_0_2_4]]
             a_					:		Optional[int]							=  processor.post_process_masks(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							return_tensors='tf'     )
             self.assertEqual(masks[0].shape     ,							(1, 3, 1_7_6_4, 2_6_4_6)     )

             a_					:		Optional[Any]							=  processor.post_process_masks(
                 SCREAMING_SNAKE_CASE__     ,							tf.convert_to_tensor(SCREAMING_SNAKE_CASE__     )     ,							tf.convert_to_tensor(SCREAMING_SNAKE_CASE__     )     ,							return_tensors='tf'     ,							)
             self.assertEqual(masks[0].shape     ,							(1, 3, 1_7_6_4, 2_6_4_6)     )

             # should also work with np
             a_					:		Tuple							=  [np.ones((1, 3, 5, 5)     )]
             a_					:		Any							=  processor.post_process_masks(
                 SCREAMING_SNAKE_CASE__     ,							np.array(SCREAMING_SNAKE_CASE__     )     ,							np.array(SCREAMING_SNAKE_CASE__     )     ,							return_tensors='tf'     )

             self.assertEqual(masks[0].shape     ,							(1, 3, 1_7_6_4, 2_6_4_6)     )

             a_					:		Any							=  [[1, 0], [0, 1]]
             with self.assertRaises(tf.errors.InvalidArgumentError     ):
                    a_					:		List[Any]							=  processor.post_process_masks(
                        SCREAMING_SNAKE_CASE__     ,							np.array(SCREAMING_SNAKE_CASE__     )     ,							np.array(SCREAMING_SNAKE_CASE__     )     ,							return_tensors='tf'     )
@require_vision
@require_torchvision
class  SCREAMING_SNAKE_CASE__  (				unittest.TestCase			):
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     )		->			Any:
             a_					:		List[str]							=  tempfile.mkdtemp()
             a_					:		Tuple							=  SamImageProcessor()
             a_					:		Optional[int]							=  SamProcessor(SCREAMING_SNAKE_CASE__     )
             processor.save_pretrained(self.tmpdirname     )
      def        SCREAMING_SNAKE_CASE							(       self				:       int     ,							**SCREAMING_SNAKE_CASE__				:       str     )		->			Union[str, Any]:
             return AutoProcessor.from_pretrained(self.tmpdirname     ,							**SCREAMING_SNAKE_CASE__     ).image_processor
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     )		->			int:
             shutil.rmtree(self.tmpdirname     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     )		->			Dict:
             a_					:		Optional[int]							=  [np.random.randint(2_5_5     ,							size=(3, 3_0, 4_0_0)     ,							dtype=np.uinta     )]

             a_					:		int							=  [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__     ,							0     ,							-1     )     ) for x in image_inputs]

             return image_inputs
      @is_pt_tf_cross_test
      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     )		->			List[Any]:
             a_					:		Optional[Any]							=  self.get_image_processor()

             a_					:		Tuple							=  SamProcessor(image_processor=SCREAMING_SNAKE_CASE__     )
             a_					:		List[str]							=  np.random.randint(0     ,							2     ,							size=(1, 3, 5, 5)     ).astype(np.floataa     )
             a_					:		Any							=  [tf.convert_to_tensor(SCREAMING_SNAKE_CASE__     )]
             a_					:		Dict							=  [torch.tensor(SCREAMING_SNAKE_CASE__     )]

             a_					:		Any							=  [[1_7_6_4, 2_6_4_6]]

             a_					:		List[str]							=  [[6_8_3, 1_0_2_4]]
             a_					:		int							=  processor.post_process_masks(
                 SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							return_tensors='tf'     )
             a_					:		str							=  processor.post_process_masks(
                 SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							return_tensors='pt'     )

             self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()     )     )

      @is_pt_tf_cross_test
      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     )		->			List[Any]:
             a_					:		Any							=  self.get_image_processor()

             a_					:		Any							=  SamProcessor(image_processor=SCREAMING_SNAKE_CASE__     )

             a_					:		str							=  self.prepare_image_inputs()

             a_					:		Optional[Any]							=  image_processor(SCREAMING_SNAKE_CASE__     ,							return_tensors='pt'     )['pixel_values'].numpy()
             a_					:		Dict							=  processor(images=SCREAMING_SNAKE_CASE__     ,							return_tensors='pt'     )['pixel_values'].numpy()

             a_					:		Optional[int]							=  image_processor(SCREAMING_SNAKE_CASE__     ,							return_tensors='tf'     )['pixel_values'].numpy()
             a_					:		List[Any]							=  processor(images=SCREAMING_SNAKE_CASE__     ,							return_tensors='tf'     )['pixel_values'].numpy()

             self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )     )
             self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )     )
             self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )     )










"""simple docstring"""



import copy
import json
import os
import tempfile

from transformers import is_torch_available

from .test_configuration_utils import config_common_kwargs

class        a     (   a_	):







    def __init__(			self							,		_lowerCamelCase							,		_lowerCamelCase=None							,		_lowerCamelCase=True							,		_lowerCamelCase=None							,		**_lowerCamelCase       ):
      lowercase							    =       parent
      lowercase							    =       config_class
      lowercase							    =       has_text_modality
      lowercase							    =       kwargs
      lowercase							    =       common_properties







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )
      lowercase							    =       (
          ['hidden_size', 'num_attention_heads', 'num_hidden_layers']
          if self.common_properties is None
          else self.common_properties
      )

      # Add common fields for text models
      if self.has_text_modality:
        common_properties.extend(['vocab_size']       )

      # Test that config has the common properties as getters
      for prop in common_properties:
        self.parent.assertTrue(hasattr(_lowerCamelCase							,		_lowerCamelCase       )							,		msg=F'`{prop}` does not exist'       )

      # Test that config has the common properties as setter
      for idx, name in enumerate(_lowerCamelCase       ):
        try:
          setattr(_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase       )
          self.parent.assertEqual(
              getattr(_lowerCamelCase							,		_lowerCamelCase       )							,		_lowerCamelCase							,		msg=F'`{name} value {idx} expected, but was {getattr(_lowerCamelCase							,		_lowerCamelCase       )}'       )
        except NotImplementedError:
          # Some models might not be able to implement setters for common_properties
          # In that case, a NotImplementedError is raised
          pass

        # Test if config class can be called with Config(prop_name=..)
      for idx, name in enumerate(_lowerCamelCase       ):
        try:
          lowercase							    =       self.config_class(**{name: idx}       )
          self.parent.assertEqual(
              getattr(_lowerCamelCase							,		_lowerCamelCase       )							,		_lowerCamelCase							,		msg=F'`{name} value {idx} expected, but was {getattr(_lowerCamelCase							,		_lowerCamelCase       )}'       )
        except NotImplementedError:
          # Some models might not be able to implement setters for common_properties
          # In that case, a NotImplementedError is raised
          pass







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )
      lowercase							    =       json.loads(config.to_json_string()       )
      for key, value in self.inputs_dict.items():
        self.parent.assertEqual(obj[key]							,		_lowerCamelCase       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )

      with tempfile.TemporaryDirectory() as tmpdirname:
        lowercase							    =       os.path.join(_lowerCamelCase							,		'config.json'       )
        config_first.to_json_file(_lowerCamelCase       )
        lowercase							    =       self.config_class.from_json_file(_lowerCamelCase       )

      self.parent.assertEqual(config_second.to_dict()							,		config_first.to_dict()       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )

      with tempfile.TemporaryDirectory() as tmpdirname:
        config_first.save_pretrained(_lowerCamelCase       )
        lowercase							    =       self.config_class.from_pretrained(_lowerCamelCase       )

      self.parent.assertEqual(config_second.to_dict()							,		config_first.to_dict()       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict       )

      lowercase							    =       'test'
      with tempfile.TemporaryDirectory() as tmpdirname:
        lowercase							    =       os.path.join(_lowerCamelCase							,		_lowerCamelCase       )
        config_first.save_pretrained(_lowerCamelCase       )
        lowercase							    =       self.config_class.from_pretrained(_lowerCamelCase							,		subfolder=_lowerCamelCase       )

      self.parent.assertEqual(config_second.to_dict()							,		config_first.to_dict()       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       self.config_class(**self.inputs_dict							,		num_labels=5       )
      self.parent.assertEqual(len(config.idalabel       )							,		5       )
      self.parent.assertEqual(len(config.labelaid       )							,		5       )

      lowercase							    =       3
      self.parent.assertEqual(len(config.idalabel       )							,		3       )
      self.parent.assertEqual(len(config.labelaid       )							,		3       )







    def 			UpperCamelCase_      (			self       ):
      if self.config_class.is_composition:
        return
      lowercase							    =       self.config_class()
      self.parent.assertIsNotNone(_lowerCamelCase       )







    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       copy.deepcopy(_lowerCamelCase       )
      lowercase							    =       self.config_class(**_lowerCamelCase       )
      lowercase							    =       []
      for key, value in config_common_kwargs.items():
        if key == "torch_dtype":
          if not is_torch_available():
            continue
          else:
            import torch

            if config.torch_dtype != torch.floataa:
              wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa)       )
        elif getattr(_lowerCamelCase							,		_lowerCamelCase       ) != value:
          wrong_values.append((key, getattr(_lowerCamelCase							,		_lowerCamelCase       ), value)       )

      if len(_lowerCamelCase       ) > 0:
        lowercase							    =       '\n'.join([F'- {v[0]}: got {v[1]} instead of {v[2]}' for v in wrong_values]       )
        raise ValueError(F'The following keys were not properly set in the config:\n{errors}'       )







    def 			UpperCamelCase_      (			self       ):
      self.create_and_test_config_common_properties()
      self.create_and_test_config_to_json_string()
      self.create_and_test_config_to_json_file()
      self.create_and_test_config_from_and_save_pretrained()
      self.create_and_test_config_from_and_save_pretrained_subfolder()
      self.create_and_test_config_with_num_labels()
      self.check_config_can_be_init_without_params()
      self.check_config_arguments_init()


