


"""simple docstring"""

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    lowerCamelCase__						(		unittest.TestCase    ):
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase									=	tempfile.mkdtemp()
       __lowercase									=	SamImageProcessor()
       __lowercase									=	SamProcessor(__a							)
       processor.save_pretrained(self.tmpdirname							)
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]      ,       **A_	:	List[str]							):






       '''simple docstring'''


       return AutoProcessor.from_pretrained(self.tmpdirname      ,       **__a							).image_processor
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       shutil.rmtree(self.tmpdirname							)
      def SCREAMING_SNAKE_CASE_	(		self	:	List[str]							):






       '''simple docstring'''


       __lowercase									=	[np.random.randint(2_5_5      ,       size=(3, 3_0, 4_0_0)      ,       dtype=np.uinta							)]

       __lowercase									=	[Image.fromarray(np.moveaxis(__a      ,       0      ,       -1							)							) for x in image_inputs]

       return image_inputs
      def SCREAMING_SNAKE_CASE_	(		self	:	Union[str, Any]							):






       '''simple docstring'''


       __lowercase									=	SamProcessor(image_processor=self.get_image_processor()							)
       processor.save_pretrained(self.tmpdirname							)

       __lowercase									=	self.get_image_processor(do_normalize=__a      ,       padding_value=1.0							)

       __lowercase									=	SamProcessor.from_pretrained(self.tmpdirname      ,       do_normalize=__a      ,       padding_value=1.0							)

       self.assertEqual(processor.image_processor.to_json_string()      ,       image_processor_add_kwargs.to_json_string()							)
       self.assertIsInstance(processor.image_processor      ,       __a							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase									=	self.get_image_processor()

       __lowercase									=	SamProcessor(image_processor=__a							)

       __lowercase									=	self.prepare_image_inputs()

       __lowercase									=	image_processor(__a      ,       return_tensors="""np"""							)
       __lowercase									=	processor(images=__a      ,       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	:	Tuple							):






       '''simple docstring'''


       __lowercase									=	self.get_image_processor()

       __lowercase									=	SamProcessor(image_processor=__a							)
       __lowercase									=	[torch.ones((1, 3, 5, 5)							)]

       __lowercase									=	[[1_7_6_4, 2_6_4_6]]

       __lowercase									=	[[6_8_3, 1_0_2_4]]
       __lowercase									=	processor.post_process_masks(__a      ,       __a      ,       __a							)
       self.assertEqual(masks[0].shape      ,       (1, 3, 1_7_6_4, 2_6_4_6)							)

       __lowercase									=	processor.post_process_masks(
           __a      ,       torch.tensor(__a							)      ,       torch.tensor(__a							)							)
       self.assertEqual(masks[0].shape      ,       (1, 3, 1_7_6_4, 2_6_4_6)							)

       # should also work with np
       __lowercase									=	[np.ones((1, 3, 5, 5)							)]
       __lowercase									=	processor.post_process_masks(__a      ,       np.array(__a							)      ,       np.array(__a							)							)

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

       __lowercase									=	[[1, 0], [0, 1]]
       with self.assertRaises(__a							):
        __lowercase									=	processor.post_process_masks(__a      ,       np.array(__a							)      ,       np.array(__a							)							)






@require_vision
@require_tf
class    lowerCamelCase__						(		unittest.TestCase    ):
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       __lowercase									=	tempfile.mkdtemp()
       __lowercase									=	SamImageProcessor()
       __lowercase									=	SamProcessor(__a							)
       processor.save_pretrained(self.tmpdirname							)
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]      ,       **A_	:	str							):






       '''simple docstring'''


       return AutoProcessor.from_pretrained(self.tmpdirname      ,       **__a							).image_processor
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


       shutil.rmtree(self.tmpdirname							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[Any]							):






       '''simple docstring'''


       __lowercase									=	[np.random.randint(2_5_5      ,       size=(3, 3_0, 4_0_0)      ,       dtype=np.uinta							)]

       __lowercase									=	[Image.fromarray(np.moveaxis(__a      ,       0      ,       -1							)							) for x in image_inputs]

       return image_inputs
      def SCREAMING_SNAKE_CASE_	(		self	:	Tuple							):






       '''simple docstring'''


       __lowercase									=	SamProcessor(image_processor=self.get_image_processor()							)
       processor.save_pretrained(self.tmpdirname							)

       __lowercase									=	self.get_image_processor(do_normalize=__a      ,       padding_value=1.0							)

       __lowercase									=	SamProcessor.from_pretrained(self.tmpdirname      ,       do_normalize=__a      ,       padding_value=1.0							)

       self.assertEqual(processor.image_processor.to_json_string()      ,       image_processor_add_kwargs.to_json_string()							)
       self.assertIsInstance(processor.image_processor      ,       __a							)
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       __lowercase									=	self.get_image_processor()

       __lowercase									=	SamProcessor(image_processor=__a							)

       __lowercase									=	self.prepare_image_inputs()

       __lowercase									=	image_processor(__a      ,       return_tensors="""np"""							)
       __lowercase									=	processor(images=__a      ,       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	:	Any							):






       '''simple docstring'''


       __lowercase									=	self.get_image_processor()

       __lowercase									=	SamProcessor(image_processor=__a							)
       __lowercase									=	[tf.ones((1, 3, 5, 5)							)]

       __lowercase									=	[[1_7_6_4, 2_6_4_6]]

       __lowercase									=	[[6_8_3, 1_0_2_4]]
       __lowercase									=	processor.post_process_masks(__a      ,       __a      ,       __a      ,       return_tensors="""tf"""							)
       self.assertEqual(masks[0].shape      ,       (1, 3, 1_7_6_4, 2_6_4_6)							)

       __lowercase									=	processor.post_process_masks(
           __a      ,       tf.convert_to_tensor(__a							)      ,       tf.convert_to_tensor(__a							)      ,       return_tensors="""tf"""      ,       )
       self.assertEqual(masks[0].shape      ,       (1, 3, 1_7_6_4, 2_6_4_6)							)

       # should also work with np
       __lowercase									=	[np.ones((1, 3, 5, 5)							)]
       __lowercase									=	processor.post_process_masks(
           __a      ,       np.array(__a							)      ,       np.array(__a							)      ,       return_tensors="""tf"""							)

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

       __lowercase									=	[[1, 0], [0, 1]]
       with self.assertRaises(tf.errors.InvalidArgumentError							):
        __lowercase									=	processor.post_process_masks(
            __a      ,       np.array(__a							)      ,       np.array(__a							)      ,       return_tensors="""tf"""							)






@require_vision
@require_torchvision
class    lowerCamelCase__						(		unittest.TestCase    ):
      def SCREAMING_SNAKE_CASE_	(		self	:	Any							):






       '''simple docstring'''


       __lowercase									=	tempfile.mkdtemp()
       __lowercase									=	SamImageProcessor()
       __lowercase									=	SamProcessor(__a							)
       processor.save_pretrained(self.tmpdirname							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict      ,       **A_	:	Optional[Any]							):






       '''simple docstring'''


       return AutoProcessor.from_pretrained(self.tmpdirname      ,       **__a							).image_processor
      def SCREAMING_SNAKE_CASE_	(		self	:	int							):






       '''simple docstring'''


       shutil.rmtree(self.tmpdirname							)
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       __lowercase									=	[np.random.randint(2_5_5      ,       size=(3, 3_0, 4_0_0)      ,       dtype=np.uinta							)]

       __lowercase									=	[Image.fromarray(np.moveaxis(__a      ,       0      ,       -1							)							) for x in image_inputs]

       return image_inputs
      @is_pt_tf_cross_test
      def SCREAMING_SNAKE_CASE_	(		self	:	Any							):






       '''simple docstring'''


       __lowercase									=	self.get_image_processor()

       __lowercase									=	SamProcessor(image_processor=__a							)
       __lowercase									=	np.random.randint(0      ,       2      ,       size=(1, 3, 5, 5)							).astype(np.floataa							)
       __lowercase									=	[tf.convert_to_tensor(__a							)]
       __lowercase									=	[torch.tensor(__a							)]

       __lowercase									=	[[1_7_6_4, 2_6_4_6]]

       __lowercase									=	[[6_8_3, 1_0_2_4]]
       __lowercase									=	processor.post_process_masks(
           __a      ,       __a      ,       __a      ,       return_tensors="""tf"""							)
       __lowercase									=	processor.post_process_masks(
           __a      ,       __a      ,       __a      ,       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	:	str							):






       '''simple docstring'''


       __lowercase									=	self.get_image_processor()

       __lowercase									=	SamProcessor(image_processor=__a							)

       __lowercase									=	self.prepare_image_inputs()

       __lowercase									=	image_processor(__a      ,       return_tensors="""pt"""							)["pixel_values"].numpy()
       __lowercase									=	processor(images=__a      ,       return_tensors="""pt"""							)["pixel_values"].numpy()

       __lowercase									=	image_processor(__a      ,       return_tensors="""tf"""							)["pixel_values"].numpy()
       __lowercase									=	processor(images=__a      ,       return_tensors="""tf"""							)["pixel_values"].numpy()

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




"""simple docstring"""

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


UpperCAmelCase__  							=logging.get_logger(__name__)

UpperCAmelCase__  							={
    "microsoft/swinv2-tiny-patch4-window8-256": (
        "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json"
    ),
}





class    lowerCamelCase__						(		_a    ):
      a :     List[Any]											=		"""swinv2"""

      a :     Any											=		{
          """num_attention_heads""": """num_heads""",
          """num_hidden_layers""": """num_layers""",
      }
      def __init__(		self	:	List[str]      ,       A_	:	Any=2_2_4      ,       A_	:	int=4      ,       A_	:	Optional[int]=3      ,       A_	:	List[Any]=9_6      ,       A_	:	List[Any]=[2, 2, 6, 2]      ,       A_	:	List[str]=[3, 6, 1_2, 2_4]      ,       A_	:	Union[str, Any]=7      ,       A_	:	int=4.0      ,       A_	:	List[str]=True      ,       A_	:	str=0.0      ,       A_	:	Any=0.0      ,       A_	:	Union[str, Any]=0.1      ,       A_	:	Optional[Any]="gelu"      ,       A_	:	int=False      ,       A_	:	List[Any]=0.02      ,       A_	:	Tuple=1e-5      ,       A_	:	Tuple=3_2      ,       **A_	:	int      ,       ):






       '''simple docstring'''


       super().__init__(**A_							)

       __lowercase									=	image_size
       __lowercase									=	patch_size
       __lowercase									=	num_channels
       __lowercase									=	embed_dim
       __lowercase									=	depths
       __lowercase									=	len(A_							)
       __lowercase									=	num_heads
       __lowercase									=	window_size
       __lowercase									=	mlp_ratio
       __lowercase									=	qkv_bias
       __lowercase									=	hidden_dropout_prob
       __lowercase									=	attention_probs_dropout_prob
       __lowercase									=	drop_path_rate
       __lowercase									=	hidden_act
       __lowercase									=	use_absolute_embeddings
       __lowercase									=	layer_norm_eps
       __lowercase									=	initializer_range
       __lowercase									=	encoder_stride
       # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
       # this indicates the channel dimension after the last stage of the model
       __lowercase									=	int(embed_dim * 2 ** (len(A_							) - 1)							)
       __lowercase									=	(0, 0, 0, 0)
