




import inspect
import unittest

from transformers import SwinaSRConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import SwinaSRForImageSuperResolution, SwinaSRModel
 from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
 from PIL import Image

 from transformers import SwinaSRImageProcessor



class     a  :

     '''simple docstring'''





     def __init__(			self     :    Dict      ,					__snake_case     :    Any      ,					__snake_case     :    List[Any]=13      ,					__snake_case     :    Optional[int]=32      ,					__snake_case     :    List[str]=1      ,					__snake_case     :    Tuple=3      ,					__snake_case     :    Any=16      ,					__snake_case     :    str=[1, 2, 1]      ,					__snake_case     :    List[str]=[2, 2, 4]      ,					__snake_case     :    List[str]=2      ,					__snake_case     :    Any=2.0      ,					__snake_case     :    Optional[int]=True      ,					__snake_case     :    List[str]=0.0      ,					__snake_case     :    Dict=0.0      ,					__snake_case     :    str=0.1      ,					__snake_case     :    Union[str, Any]="gelu"      ,					__snake_case     :    Dict=False      ,					__snake_case     :    str=True      ,					__snake_case     :    Any=0.02      ,					__snake_case     :    List[Any]=1E-5      ,					__snake_case     :    int=True      ,					__snake_case     :    Union[str, Any]=None      ,					__snake_case     :    List[Any]=False      ,					__snake_case     :    Union[str, Any]=2      ,					):
         UpperCAmelCase_											=  parent
         UpperCAmelCase_											=  batch_size
         UpperCAmelCase_											=  image_size
         UpperCAmelCase_											=  patch_size
         UpperCAmelCase_											=  num_channels
         UpperCAmelCase_											=  embed_dim
         UpperCAmelCase_											=  depths
         UpperCAmelCase_											=  num_heads
         UpperCAmelCase_											=  window_size
         UpperCAmelCase_											=  mlp_ratio
         UpperCAmelCase_											=  qkv_bias
         UpperCAmelCase_											=  hidden_dropout_prob
         UpperCAmelCase_											=  attention_probs_dropout_prob
         UpperCAmelCase_											=  drop_path_rate
         UpperCAmelCase_											=  hidden_act
         UpperCAmelCase_											=  use_absolute_embeddings
         UpperCAmelCase_											=  patch_norm
         UpperCAmelCase_											=  layer_norm_eps
         UpperCAmelCase_											=  initializer_range
         UpperCAmelCase_											=  is_training
         UpperCAmelCase_											=  scope
         UpperCAmelCase_											=  use_labels
         UpperCAmelCase_											=  upscale

         # here we set some attributes to make tests pass
         UpperCAmelCase_											=  len(__snake_case       )
         UpperCAmelCase_											=  embed_dim
         UpperCAmelCase_											=  (image_size // patch_size) ** 2
     def 						lowerCamelCase_     (			self     :    Dict       ):
         UpperCAmelCase_											=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

         UpperCAmelCase_											=  None
         if self.use_labels:
             UpperCAmelCase_											=  ids_tensor([self.batch_size]      ,					self.type_sequence_label_size       )

         UpperCAmelCase_											=  self.get_config()

         return config, pixel_values, labels
     def 						lowerCamelCase_     (			self     :    str       ):
         return SwinaSRConfig(
             image_size=self.image_size      ,					patch_size=self.patch_size      ,					num_channels=self.num_channels      ,					embed_dim=self.embed_dim      ,					depths=self.depths      ,					num_heads=self.num_heads      ,					window_size=self.window_size      ,					mlp_ratio=self.mlp_ratio      ,					qkv_bias=self.qkv_bias      ,					hidden_dropout_prob=self.hidden_dropout_prob      ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,					drop_path_rate=self.drop_path_rate      ,					hidden_act=self.hidden_act      ,					use_absolute_embeddings=self.use_absolute_embeddings      ,					path_norm=self.patch_norm      ,					layer_norm_eps=self.layer_norm_eps      ,					initializer_range=self.initializer_range      ,					upscale=self.upscale      ,					)
     def 						lowerCamelCase_     (			self     :    str      ,					__snake_case     :    Optional[Any]      ,					__snake_case     :    Dict      ,					__snake_case     :    Dict       ):
         UpperCAmelCase_											=  SwinaSRModel(config=__snake_case       )
         model.to(__snake_case       )
         model.eval()
         UpperCAmelCase_											=  model(__snake_case       )

         self.parent.assertEqual(
             result.last_hidden_state.shape      ,					(self.batch_size, self.embed_dim, self.image_size, self.image_size)       )
     def 						lowerCamelCase_     (			self     :    int      ,					__snake_case     :    Union[str, Any]      ,					__snake_case     :    Tuple      ,					__snake_case     :    List[Any]       ):
         UpperCAmelCase_											=  SwinaSRForImageSuperResolution(__snake_case       )
         model.to(__snake_case       )
         model.eval()
         UpperCAmelCase_											=  model(__snake_case       )

         UpperCAmelCase_											=  self.image_size * self.upscale
         self.parent.assertEqual(
             result.reconstruction.shape      ,					(self.batch_size, self.num_channels, expected_image_size, expected_image_size)       )




     def 						lowerCamelCase_     (			self     :    List[str]       ):
         UpperCAmelCase_											=  self.prepare_config_and_inputs()
         UpperCAmelCase_				,							UpperCAmelCase_				,							UpperCAmelCase_											=  config_and_inputs
         UpperCAmelCase_											=  {'''pixel_values''': pixel_values}
         return config, inputs_dict



@require_torch
class     a  (     _A			,     _A			,     unittest.TestCase    ):

     '''simple docstring'''





     lowerCAmelCase       : int     	=						(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
     lowerCAmelCase       : str     	=						{'feature-extraction': SwinaSRModel} if is_torch_available() else {}

     lowerCAmelCase       : List[str]     	=						False
     lowerCAmelCase       : Optional[Any]     	=						False
     lowerCAmelCase       : List[Any]     	=						False
     lowerCAmelCase       : List[str]     	=						False
     lowerCAmelCase       : Optional[Any]     	=						False
     def 						lowerCamelCase_     (			self     :    int       ):
         UpperCAmelCase_											=  SwinaSRModelTester(self       )
         UpperCAmelCase_											=  ConfigTester(self      ,					config_class=__snake_case      ,					embed_dim=37       )
     def 						lowerCamelCase_     (			self     :    Optional[int]       ):
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()
     def 						lowerCamelCase_     (			self     :    Union[str, Any]       ):
         UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__snake_case       )
     def 						lowerCamelCase_     (			self     :    Optional[Any]       ):
         UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_super_resolution(*__snake_case       )
     @unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.'''       )
     def 						lowerCamelCase_     (			self     :    Optional[Any]       ):
         pass
     @unittest.skip(reason='''Swin2SR does not use inputs_embeds'''       )
     def 						lowerCamelCase_     (			self     :    Optional[int]       ):
         pass
     @unittest.skip(reason='''Swin2SR does not support training yet'''       )
     def 						lowerCamelCase_     (			self     :    Optional[Any]       ):
         pass
     @unittest.skip(reason='''Swin2SR does not support training yet'''       )
     def 						lowerCamelCase_     (			self     :    Dict       ):
         pass
     def 						lowerCamelCase_     (			self     :    Tuple       ):
         UpperCAmelCase_				,							UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             UpperCAmelCase_											=  model_class(__snake_case       )
             self.assertIsInstance(model.get_input_embeddings()      ,					(nn.Module)       )
             UpperCAmelCase_											=  model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(__snake_case      ,					nn.Linear       )       )
     def 						lowerCamelCase_     (			self     :    Dict       ):
         UpperCAmelCase_				,							UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             UpperCAmelCase_											=  model_class(__snake_case       )
             UpperCAmelCase_											=  inspect.signature(model.forward       )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             UpperCAmelCase_											=  [*signature.parameters.keys()]

             UpperCAmelCase_											=  ['''pixel_values''']
             self.assertListEqual(arg_names[:1]      ,					__snake_case       )
     @slow
     def 						lowerCamelCase_     (			self     :    Tuple       ):
         for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCAmelCase_											=  SwinaSRModel.from_pretrained(__snake_case       )
             self.assertIsNotNone(__snake_case       )
     def 						lowerCamelCase_     (			self     :    Any       ):
         UpperCAmelCase_				,							UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs_for_common()

         UpperCAmelCase_											=  _config_zero_init(__snake_case       )
         for model_class in self.all_model_classes:
             UpperCAmelCase_											=  model_class(config=__snake_case       )
             for name, param in model.named_parameters():
                 if "logit_scale" in name:
                     continue
                 if param.requires_grad:
                     self.assertIn(
                         ((param.data.mean() * 1E9).round() / 1E9).item()      ,					[0.0, 1.0]      ,					msg=F'Parameter {name} of model {model_class} seems not properly initialized'      ,					)




     def 						lowerCamelCase_     (			self     :    Any       ):
         UpperCAmelCase_				,							UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase_											=  True

         for model_class in self.all_model_classes:
             UpperCAmelCase_											=  True
             UpperCAmelCase_											=  False
             UpperCAmelCase_											=  True
             UpperCAmelCase_											=  model_class(__snake_case       )
             model.to(__snake_case       )
             model.eval()
             with torch.no_grad():
                 UpperCAmelCase_											=  model(**self._prepare_for_class(__snake_case      ,					__snake_case       )       )
             UpperCAmelCase_											=  outputs.attentions
             UpperCAmelCase_											=  len(self.model_tester.depths       )
             self.assertEqual(len(__snake_case       )      ,					__snake_case       )

             # check that output_attentions also work using config
             del inputs_dict["output_attentions"]
             UpperCAmelCase_											=  True
             UpperCAmelCase_											=  config.window_size**2
             UpperCAmelCase_											=  model_class(__snake_case       )
             model.to(__snake_case       )
             model.eval()
             with torch.no_grad():
                 UpperCAmelCase_											=  model(**self._prepare_for_class(__snake_case      ,					__snake_case       )       )
             UpperCAmelCase_											=  outputs.attentions
             self.assertEqual(len(__snake_case       )      ,					__snake_case       )

             self.assertListEqual(
                 list(attentions[0].shape[-3:]       )      ,					[self.model_tester.num_heads[0], window_size_squared, window_size_squared]      ,					)
             UpperCAmelCase_											=  len(__snake_case       )

             # Check attention is always last and order is fine
             UpperCAmelCase_											=  True
             UpperCAmelCase_											=  True
             UpperCAmelCase_											=  model_class(__snake_case       )
             model.to(__snake_case       )
             model.eval()
             with torch.no_grad():
                 UpperCAmelCase_											=  model(**self._prepare_for_class(__snake_case      ,					__snake_case       )       )

             self.assertEqual(out_len + 1      ,					len(__snake_case       )       )

             UpperCAmelCase_											=  outputs.attentions

             self.assertEqual(len(__snake_case       )      ,					__snake_case       )

             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]       )      ,					[self.model_tester.num_heads[0], window_size_squared, window_size_squared]      ,					)



@require_vision
@require_torch
@slow
class     a  (     unittest.TestCase    ):

     '''simple docstring'''





     def 						lowerCamelCase_     (			self     :    Union[str, Any]       ):
         UpperCAmelCase_											=  SwinaSRImageProcessor()
         UpperCAmelCase_											=  SwinaSRForImageSuperResolution.from_pretrained('''caidas/swin2SR-classical-sr-x2-64'''       ).to(__snake_case       )

         UpperCAmelCase_											=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
         UpperCAmelCase_											=  processor(images=__snake_case      ,					return_tensors='''pt'''       ).to(__snake_case       )

         # forward pass
         with torch.no_grad():
             UpperCAmelCase_											=  model(**__snake_case       )

         # verify the logits
         UpperCAmelCase_											=  torch.Size([1, 3, 9_76, 12_96]       )
         self.assertEqual(outputs.reconstruction.shape      ,					__snake_case       )
         UpperCAmelCase_											=  torch.tensor(
             [[0.5_458, 0.5_546, 0.5_638], [0.5_526, 0.5_565, 0.5_651], [0.5_396, 0.5_426, 0.5_621]]       ).to(__snake_case       )
         self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]      ,					__snake_case      ,					atol=1E-4       )       )











_lowerCamelCase    				=		[
    [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
]




def       SCREAMING_SNAKE_CASE			( __UpperCamelCase    :		int ,  __UpperCamelCase    :		int ,  __UpperCamelCase    :		int ,  __UpperCamelCase    :		int   )						->							bool:
    return 0 <= row < rows and 0 <= col < cols




def       SCREAMING_SNAKE_CASE			( __UpperCamelCase    :		int ,  __UpperCamelCase    :		int ,  __UpperCamelCase    :		set ,  __UpperCamelCase    :		list[list[int]]   )						->							int:
    UpperCAmelCase_											=  len(__UpperCamelCase   )
    UpperCAmelCase_											=  len(mat[0]   )
    if is_safe(__UpperCamelCase ,  __UpperCamelCase ,  __UpperCamelCase ,  __UpperCamelCase   ) and (row, col) not in seen and mat[row][col] == 1:
        seen.add((row, col)   )
        return (
            1
            + depth_first_search(row + 1 ,  __UpperCamelCase ,  __UpperCamelCase ,  __UpperCamelCase   )
            + depth_first_search(row - 1 ,  __UpperCamelCase ,  __UpperCamelCase ,  __UpperCamelCase   )
            + depth_first_search(__UpperCamelCase ,  col + 1 ,  __UpperCamelCase ,  __UpperCamelCase   )
            + depth_first_search(__UpperCamelCase ,  col - 1 ,  __UpperCamelCase ,  __UpperCamelCase   )
        )
    else:
        return 0




def       SCREAMING_SNAKE_CASE			( __UpperCamelCase    :		list[list[int]]   )						->							int:
    UpperCAmelCase_											=  set()

    UpperCAmelCase_											=  0
    for row, line in enumerate(__UpperCamelCase   ):
        for col, item in enumerate(__UpperCamelCase   ):
            if item == 1 and (row, col) not in seen:
                # Maximizing the area
                UpperCAmelCase_											=  max(__UpperCamelCase ,  depth_first_search(__UpperCamelCase ,  __UpperCamelCase ,  __UpperCamelCase ,  __UpperCamelCase   )   )
    return max_area


if __name__ == "__main__":
 import doctest

 print(find_max_area(matrix))  # Output -> 6
 doctest.testmod()





