


"""simple docstring"""






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import SwinaSRImageProcessor
 from transformers.image_transforms import get_image_size


class 	A_       (     unittest.TestCase   ):





  """simple docstring"""

  def __init__(						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase=7  ,					__UpperCAmelCase=3  ,					__UpperCAmelCase=18  ,					__UpperCAmelCase=30  ,					__UpperCAmelCase=4_00  ,					__UpperCAmelCase=True  ,					__UpperCAmelCase=1 / 2_55  ,					__UpperCAmelCase=True  ,					__UpperCAmelCase=8  ,					)				->					int:
     a   :	Optional[int]						=    parent
     a   :	Optional[Any]						=    batch_size
     a   :	int						=    num_channels
     a   :	Union[str, Any]						=    image_size
     a   :	int						=    min_resolution
     a   :	Union[str, Any]						=    max_resolution
     a   :	List[str]						=    do_rescale
     a   :	Optional[int]						=    rescale_factor
     a   :	str						=    do_pad
     a   :	Tuple						=    pad_size
  def 							lowercase_     (						self						)				->					int:
     return {
         "do_rescale": self.do_rescale,
         "rescale_factor": self.rescale_factor,
         "do_pad": self.do_pad,
         "pad_size": self.pad_size,
     }






  def 							lowercase_     (						self  ,					__UpperCAmelCase=False  ,					__UpperCAmelCase=False  ,					__UpperCAmelCase=False						)				->					Union[str, Any]:
     assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

     if equal_resolution:
        a   :	Dict						=    []
        for i in range(self.batch_size						):
           image_inputs.append(
               np.random.randint(
                   2_55  ,					size=(self.num_channels, self.max_resolution, self.max_resolution)  ,					dtype=np.uinta						)						)
     else:
        a   :	List[Any]						=    []
        for i in range(self.batch_size						):
           a	, a   :	List[Any]						=    np.random.choice(np.arange(self.min_resolution  ,					self.max_resolution						)  ,					2						)
           image_inputs.append(np.random.randint(2_55  ,					size=(self.num_channels, width, height)  ,					dtype=np.uinta						)						)

     if not numpify and not torchify:
        # PIL expects the channel dimension as last dimension
        a   :	int						=    [Image.fromarray(np.moveaxis(__lowerCamelCase  ,					0  ,					-1						)						) for x in image_inputs]

     if torchify:
        a   :	Tuple						=    [torch.from_numpy(__lowerCamelCase						) for x in image_inputs]

     return image_inputs



@require_torch
@require_vision
class 	A_       (     snake_case_      ,  unittest.TestCase   ):





  """simple docstring"""

  lowercase		:	Optional[int]   =						SwinaSRImageProcessor if is_vision_available() else None
  def 							lowercase_     (						self						)				->					Optional[int]:
     a   :	List[Any]						=    SwinaSRImageProcessingTester(self						)
  @property
  def 							lowercase_     (						self						)				->					int:
     return self.image_processor_tester.prepare_image_processor_dict()
  def 							lowercase_     (						self						)				->					Optional[Any]:
     a   :	Optional[int]						=    self.image_processing_class(**self.image_processor_dict						)
     self.assertTrue(hasattr(__lowerCamelCase  ,					'do_rescale'						)						)
     self.assertTrue(hasattr(__lowerCamelCase  ,					'rescale_factor'						)						)
     self.assertTrue(hasattr(__lowerCamelCase  ,					'do_pad'						)						)
     self.assertTrue(hasattr(__lowerCamelCase  ,					'pad_size'						)						)
  def 							lowercase_     (						self						)				->					Dict:
     pass
  def 							lowercase_     (						self  ,					__UpperCAmelCase						)				->					Optional[int]:
     a	, a   :	Tuple						=    get_image_size(__lowerCamelCase						)
     a   :	Optional[int]						=    self.image_processor_tester.pad_size

     a   :	Dict						=    (old_height // size + 1) * size - old_height
     a   :	int						=    (old_width // size + 1) * size - old_width
     return old_height + pad_height, old_width + pad_width
  def 							lowercase_     (						self						)				->					Any:
     # Initialize image_processor
     a   :	Union[str, Any]						=    self.image_processing_class(**self.image_processor_dict						)
     # create random PIL images
     a   :	Union[str, Any]						=    self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase						)
     for image in image_inputs:
        self.assertIsInstance(__lowerCamelCase  ,					Image.Image						)

     # Test not batched input
     a   :	Any						=    image_processor(image_inputs[0]  ,					return_tensors='pt'						).pixel_values
     a	, a   :	Union[str, Any]						=    self.calculate_expected_size(np.array(image_inputs[0]						)						)
     self.assertEqual(
         encoded_images.shape  ,					(
             1,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         )  ,					)
  def 							lowercase_     (						self						)				->					Optional[Any]:
     # Initialize image_processor
     a   :	Optional[Any]						=    self.image_processing_class(**self.image_processor_dict						)
     # create random numpy tensors
     a   :	Tuple						=    self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase  ,					numpify=__lowerCamelCase						)
     for image in image_inputs:
        self.assertIsInstance(__lowerCamelCase  ,					np.ndarray						)

     # Test not batched input
     a   :	Optional[int]						=    image_processor(image_inputs[0]  ,					return_tensors='pt'						).pixel_values
     a	, a   :	Any						=    self.calculate_expected_size(image_inputs[0]						)
     self.assertEqual(
         encoded_images.shape  ,					(
             1,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         )  ,					)






  def 							lowercase_     (						self						)				->					int:
     # Initialize image_processor
     a   :	Any						=    self.image_processing_class(**self.image_processor_dict						)
     # create random PyTorch tensors
     a   :	Any						=    self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase  ,					torchify=__lowerCamelCase						)
     for image in image_inputs:
        self.assertIsInstance(__lowerCamelCase  ,					torch.Tensor						)

     # Test not batched input
     a   :	Optional[Any]						=    image_processor(image_inputs[0]  ,					return_tensors='pt'						).pixel_values
     a	, a   :	Union[str, Any]						=    self.calculate_expected_size(image_inputs[0]						)
     self.assertEqual(
         encoded_images.shape  ,					(
             1,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         )  ,					)













"""simple docstring"""

import copy

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


lowercase           =							logging.get_logger(__name__)

lowercase           =							{
    '''facebook/sam-vit-huge''': '''https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json''',
    '''facebook/sam-vit-large''': '''https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json''',
    '''facebook/sam-vit-base''': '''https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json''',
}

class     A_				(   snake_case_	):







				def __init__(				self				:    List[Any]    ,     __lowerCamelCase				:    str=2_5_6    ,     __lowerCamelCase				:    str=1_0_2_4    ,     __lowerCamelCase				:    Optional[Any]=1_6    ,     __lowerCamelCase				:    Union[str, Any]=1_6    ,     __lowerCamelCase				:    str=4    ,     __lowerCamelCase				:    Union[str, Any]="gelu"    ,     __lowerCamelCase				:    Optional[int]=1e-6    ,     **__lowerCamelCase				:    str    ,     )					->       List[Any]:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  hidden_size
										__magic_name__      =  image_size
										__magic_name__      =  patch_size
										__magic_name__      =  image_size // patch_size
										__magic_name__      =  mask_input_channels
										__magic_name__      =  num_point_embeddings
										__magic_name__      =  hidden_act
										__magic_name__      =  layer_norm_eps





class     A_				(   snake_case_	):







				def __init__(				self				:    List[str]    ,     __lowerCamelCase				:    Optional[Any]=2_5_6    ,     __lowerCamelCase				:    int="relu"    ,     __lowerCamelCase				:    List[str]=2_0_4_8    ,     __lowerCamelCase				:    Optional[Any]=2    ,     __lowerCamelCase				:    Optional[Any]=8    ,     __lowerCamelCase				:    Optional[Any]=2    ,     __lowerCamelCase				:    Dict=3    ,     __lowerCamelCase				:    Optional[int]=3    ,     __lowerCamelCase				:    Tuple=2_5_6    ,     __lowerCamelCase				:    List[str]=1e-6    ,     **__lowerCamelCase				:    Any    ,     )					->       str:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  hidden_size
										__magic_name__      =  hidden_act
										__magic_name__      =  mlp_dim
										__magic_name__      =  num_hidden_layers
										__magic_name__      =  num_attention_heads
										__magic_name__      =  attention_downsample_rate
										__magic_name__      =  num_multimask_outputs
										__magic_name__      =  iou_head_depth
										__magic_name__      =  iou_head_hidden_dim
										__magic_name__      =  layer_norm_eps





class     A_				(   snake_case_	):







				def __init__(				self				:    Union[str, Any]    ,     __lowerCamelCase				:    str=7_6_8    ,     __lowerCamelCase				:    Optional[int]=2_5_6    ,     __lowerCamelCase				:    Tuple=1_2    ,     __lowerCamelCase				:    int=1_2    ,     __lowerCamelCase				:    int=3    ,     __lowerCamelCase				:    int=1_0_2_4    ,     __lowerCamelCase				:    Any=1_6    ,     __lowerCamelCase				:    Tuple="gelu"    ,     __lowerCamelCase				:    Dict=1e-06    ,     __lowerCamelCase				:    List[Any]=0.0    ,     __lowerCamelCase				:    Optional[Any]=1e-10    ,     __lowerCamelCase				:    str=True    ,     __lowerCamelCase				:    List[str]=4.0    ,     __lowerCamelCase				:    Union[str, Any]=True    ,     __lowerCamelCase				:    str=True    ,     __lowerCamelCase				:    Optional[Any]=1_4    ,     __lowerCamelCase				:    str=[2, 5, 8, 1_1]    ,     __lowerCamelCase				:    List[Any]=1_2_8    ,     __lowerCamelCase				:    Dict=None    ,     **__lowerCamelCase				:    List[str]    ,     )					->       Optional[int]:
										super().__init__(**__lowerCamelCase						)

										__magic_name__      =  hidden_size
										__magic_name__      =  output_channels
										__magic_name__      =  num_hidden_layers
										__magic_name__      =  num_attention_heads
										__magic_name__      =  num_channels
										__magic_name__      =  image_size
										__magic_name__      =  patch_size
										__magic_name__      =  hidden_act
										__magic_name__      =  layer_norm_eps
										__magic_name__      =  attention_dropout
										__magic_name__      =  initializer_range
										__magic_name__      =  qkv_bias
										__magic_name__      =  mlp_ratio
										__magic_name__      =  use_abs_pos
										__magic_name__      =  use_rel_pos
										__magic_name__      =  window_size
										__magic_name__      =  global_attn_indexes
										__magic_name__      =  num_pos_feats
										__magic_name__      =  int(hidden_size * mlp_ratio						) if mlp_dim is None else mlp_dim





class     A_				(   snake_case_	):
				UpperCAmelCase__										=					'''sam'''
				UpperCAmelCase__										=					True







				def __init__(				self				:    Optional[Any]    ,     __lowerCamelCase				:    Dict=None    ,     __lowerCamelCase				:    Dict=None    ,     __lowerCamelCase				:    Optional[Any]=None    ,     __lowerCamelCase				:    int=0.02    ,     **__lowerCamelCase				:    List[Any]    ,     )					->       List[str]:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  vision_config if vision_config is not None else {}
										__magic_name__      =  prompt_encoder_config if prompt_encoder_config is not None else {}
										__magic_name__      =  mask_decoder_config if mask_decoder_config is not None else {}

										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  vision_config.to_dict()
										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  prompt_encoder_config.to_dict()
										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  mask_decoder_config.to_dict()

										__magic_name__      =  SamVisionConfig(**__lowerCamelCase						)
										__magic_name__      =  SamPromptEncoderConfig(**__lowerCamelCase						)
										__magic_name__      =  SamMaskDecoderConfig(**__lowerCamelCase						)
										__magic_name__      =  initializer_range







				def      _snake_case       (				self				:    Optional[int]						)					->       str:
										__magic_name__      =  copy.deepcopy(self.__dict__						)
										__magic_name__      =  self.vision_config.to_dict()
										__magic_name__      =  self.prompt_encoder_config.to_dict()
										__magic_name__      =  self.mask_decoder_config.to_dict()
										__magic_name__      =  self.__class__.model_type
										return output



