




"""simple docstring"""




import collections
import inspect
import unittest

from transformers import DonutSwinConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_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 DonutSwinModel
  from transformers.models.donut.modeling_donut_swin import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST
class 							lowerCamelCase		:







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







   def       a_							(							self ):
       UpperCamelCase				:   Dict          =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

       UpperCamelCase				:   Optional[Any]          =							None
       if self.use_labels:
           UpperCamelCase				:   str          =							ids_tensor([self.batch_size]    ,      self.type_sequence_label_size )

       UpperCamelCase				:   Optional[int]          =							self.get_config()

       return config, pixel_values, labels







   def       a_							(							self ):
       return DonutSwinConfig(
           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    ,      encoder_stride=self.encoder_stride    ,      )







   def       a_							(							self    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_ ):
       UpperCamelCase				:   Optional[int]          =							DonutSwinModel(config=SCREAMING_SNAKE_CASE_ )
       model.to(SCREAMING_SNAKE_CASE_ )
       model.eval()
       UpperCamelCase				:   Union[str, Any]          =							model(SCREAMING_SNAKE_CASE_ )

       UpperCamelCase				:   str          =							((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
       UpperCamelCase				:   int          =							int(config.embed_dim * 2 ** (len(config.depths ) - 1) )

       self.parent.assertEqual(result.last_hidden_state.shape    ,      (self.batch_size, expected_seq_len, expected_dim) )







   def       a_							(							self ):
       UpperCamelCase				:   str          =							self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase
       )       ,							(
           UpperCamelCase
       )       ,							(
           UpperCamelCase
       )       ,							
       )				:   Dict          =							config_and_inputs
       UpperCamelCase				:   List[Any]          =							{"""pixel_values""": pixel_values}
       return config, inputs_dict







@require_torch
class 							lowerCamelCase		( _UpperCAmelCase	,  _UpperCAmelCase	,  unittest.TestCase				):
   lowercase       :  str      =				(DonutSwinModel,) if is_torch_available() else ()
   lowercase       :  Optional[Any]      =				{'feature-extraction': DonutSwinModel} if is_torch_available() else {}
   lowercase       :  Dict      =				True

   lowercase       :  Optional[Any]      =				False
   lowercase       :  Dict      =				False
   lowercase       :  List[Any]      =				False







   def       a_							(							self ):
       UpperCamelCase				:   Union[str, Any]          =							DonutSwinModelTester(self )
       UpperCamelCase				:   Union[str, Any]          =							ConfigTester(self    ,      config_class=SCREAMING_SNAKE_CASE_    ,      embed_dim=37 )







   def       a_							(							self ):
       self.create_and_test_config_common_properties()
       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       a_							(							self ):
       return







   def       a_							(							self ):
       UpperCamelCase				:   Optional[int]          =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )







   def       a_							(							self ):
       # DonutSwin does not use inputs_embeds
       pass







   def       a_							(							self ):
       UpperCamelCase       ,							UpperCamelCase				:   Optional[int]          =							self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase				:   List[str]          =							model_class(SCREAMING_SNAKE_CASE_ )
           self.assertIsInstance(model.get_input_embeddings()    ,      (nn.Module) )
           UpperCamelCase				:   Tuple          =							model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_    ,      nn.Linear ) )







   def       a_							(							self ):
       UpperCamelCase       ,							UpperCamelCase				:   List[Any]          =							self.model_tester.prepare_config_and_inputs_for_common()

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

           UpperCamelCase				:   Optional[int]          =							["""pixel_values"""]
           self.assertListEqual(arg_names[:1]    ,      SCREAMING_SNAKE_CASE_ )







   def       a_							(							self ):
       UpperCamelCase       ,							UpperCamelCase				:   int          =							self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase				:   Dict          =							True

       for model_class in self.all_model_classes:
           UpperCamelCase				:   Tuple          =							True
           UpperCamelCase				:   Dict          =							False
           UpperCamelCase				:   List[Any]          =							True
           UpperCamelCase				:   List[Any]          =							model_class(SCREAMING_SNAKE_CASE_ )
           model.to(SCREAMING_SNAKE_CASE_ )
           model.eval()
           with torch.no_grad():
               UpperCamelCase				:   Tuple          =							model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_ ) )
           UpperCamelCase				:   List[str]          =							outputs.attentions
           UpperCamelCase				:   List[str]          =							len(self.model_tester.depths )
           self.assertEqual(len(SCREAMING_SNAKE_CASE_ )    ,      SCREAMING_SNAKE_CASE_ )

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

           self.assertListEqual(
               list(attentions[0].shape[-3:] )    ,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]    ,      )
           UpperCamelCase				:   Optional[Any]          =							len(SCREAMING_SNAKE_CASE_ )

           # Check attention is always last and order is fine
           UpperCamelCase				:   Any          =							True
           UpperCamelCase				:   int          =							True
           UpperCamelCase				:   Optional[Any]          =							model_class(SCREAMING_SNAKE_CASE_ )
           model.to(SCREAMING_SNAKE_CASE_ )
           model.eval()
           with torch.no_grad():
               UpperCamelCase				:   Dict          =							model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_ ) )

           if hasattr(self.model_tester    ,      """num_hidden_states_types""" ):
               UpperCamelCase				:   List[Any]          =							self.model_tester.num_hidden_states_types
           else:
               # also another +1 for reshaped_hidden_states
               UpperCamelCase				:   List[Any]          =							2
           self.assertEqual(out_len + added_hidden_states    ,      len(SCREAMING_SNAKE_CASE_ ) )

           UpperCamelCase				:   int          =							outputs.attentions

           self.assertEqual(len(SCREAMING_SNAKE_CASE_ )    ,      SCREAMING_SNAKE_CASE_ )

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







   def       a_							(							self    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_ ):
       UpperCamelCase				:   Dict          =							model_class(SCREAMING_SNAKE_CASE_ )
       model.to(SCREAMING_SNAKE_CASE_ )
       model.eval()

       with torch.no_grad():
           UpperCamelCase				:   Any          =							model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_ ) )

       UpperCamelCase				:   Tuple          =							outputs.hidden_states

       UpperCamelCase				:   List[str]          =							getattr(
           self.model_tester    ,      """expected_num_hidden_layers"""    ,      len(self.model_tester.depths ) + 1 )
       self.assertEqual(len(SCREAMING_SNAKE_CASE_ )    ,      SCREAMING_SNAKE_CASE_ )

       # DonutSwin has a different seq_length
       UpperCamelCase				:   Optional[Any]          =							(
           config.patch_size
           if isinstance(config.patch_size    ,      collections.abc.Iterable )
           else (config.patch_size, config.patch_size)
       )

       UpperCamelCase				:   int          =							(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

       self.assertListEqual(
           list(hidden_states[0].shape[-2:] )    ,      [num_patches, self.model_tester.embed_dim]    ,      )

       UpperCamelCase				:   Optional[Any]          =							outputs.reshaped_hidden_states
       self.assertEqual(len(SCREAMING_SNAKE_CASE_ )    ,      SCREAMING_SNAKE_CASE_ )

       UpperCamelCase       ,							UpperCamelCase       ,							UpperCamelCase       ,							UpperCamelCase				:   Any          =							reshaped_hidden_states[0].shape
       UpperCamelCase				:   Optional[Any]          =							(
           reshaped_hidden_states[0].view(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      height * width ).permute(0    ,      2    ,      1 )
       )
       self.assertListEqual(
           list(reshaped_hidden_states.shape[-2:] )    ,      [num_patches, self.model_tester.embed_dim]    ,      )







   def       a_							(							self ):
       UpperCamelCase       ,							UpperCamelCase				:   Optional[int]          =							self.model_tester.prepare_config_and_inputs_for_common()

       UpperCamelCase				:   Union[str, Any]          =							(
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size    ,      collections.abc.Iterable )
           else (self.model_tester.image_size, self.model_tester.image_size)
       )

       for model_class in self.all_model_classes:
           UpperCamelCase				:   List[Any]          =							True
           self.check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_ )

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           UpperCamelCase				:   List[str]          =							True

           self.check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_ )







   def       a_							(							self ):
       UpperCamelCase       ,							UpperCamelCase				:   List[Any]          =							self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase				:   Any          =							3

       UpperCamelCase				:   List[Any]          =							(
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size    ,      collections.abc.Iterable )
           else (self.model_tester.image_size, self.model_tester.image_size)
       )
       UpperCamelCase				:   int          =							(
           config.patch_size
           if isinstance(config.patch_size    ,      collections.abc.Iterable )
           else (config.patch_size, config.patch_size)
       )

       UpperCamelCase				:   int          =							image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       UpperCamelCase				:   str          =							image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes:
           UpperCamelCase				:   str          =							True
           self.check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      (padded_height, padded_width) )

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           UpperCamelCase				:   int          =							True
           self.check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      (padded_height, padded_width) )







   @slow
   def       a_							(							self ):
       for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase				:   str          =							DonutSwinModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )







   def       a_							(							self ):
       UpperCamelCase       ,							UpperCamelCase				:   str          =							self.model_tester.prepare_config_and_inputs_for_common()

       UpperCamelCase				:   str          =							_config_zero_init(SCREAMING_SNAKE_CASE_ )
       for model_class in self.all_model_classes:
           UpperCamelCase				:   Any          =							model_class(config=SCREAMING_SNAKE_CASE_ )
           for name, param in model.named_parameters():
               if "embeddings" not in name and 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'    ,      )










"""simple docstring"""




import numpy as np
import PIL
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from PIL import Image
def 					A_			(		snake_case_     :       List[str]						,snake_case_     :       Union[str, Any]=2_5_6    ):







    '''simple docstring'''
    UpperCamelCase				:   Optional[int]          =							min(img.size    )

    if s < target_image_size:
        raise ValueError(f'min dim for image {s} < {target_image_size}'    )

    UpperCamelCase				:   Dict          =							target_image_size / s
    UpperCamelCase				:   Any          =							(round(r * img.size[1]    ), round(r * img.size[0]    ))
    UpperCamelCase				:   Union[str, Any]          =							TF.resize(snake_case_						,snake_case_						,interpolation=PIL.Image.LANCZOS    )
    UpperCamelCase				:   Optional[int]          =							TF.center_crop(snake_case_						,output_size=2 * [target_image_size]    )
    UpperCamelCase				:   Optional[Any]          =							torch.unsqueeze(T.ToTensor()(snake_case_    )						,0    )
    return img
def 					A_			(		snake_case_     :       List[Any]    ):







    '''simple docstring'''
    UpperCamelCase				:   Any          =							2.0 * x - 1.0
    return x
def 					A_			(		snake_case_     :       Tuple						,snake_case_     :       Optional[Any]=True						,snake_case_     :       Dict="RGB"    ):







    '''simple docstring'''
    UpperCamelCase				:   Dict          =							x.detach().cpu()
    if process:
        UpperCamelCase				:   str          =							post_process_tensor(snake_case_    )
    UpperCamelCase				:   List[Any]          =							x.numpy()
    if process:
        UpperCamelCase				:   Optional[int]          =							(2_5_5 * x).astype(np.uinta    )
    UpperCamelCase				:   List[Any]          =							Image.fromarray(snake_case_    )
    if not x.mode == mode:
        UpperCamelCase				:   Any          =							x.convert(snake_case_    )
    return x
def 					A_			(		snake_case_     :       int    ):







    '''simple docstring'''
    UpperCamelCase				:   int          =							torch.clamp(snake_case_						,-1.0						,1.0    )
    UpperCamelCase				:   Optional[Any]          =							(x + 1.0) / 2.0
    UpperCamelCase				:   Dict          =							x.permute(1						,2						,0    )
    return x


def 					A_			(		snake_case_     :       int    ):







    '''simple docstring'''
    UpperCamelCase				:   Optional[Any]          =							post_process_tensor(x.squeeze()    )
    return x.permute(2						,0						,1    ).unsqueeze(0    )




