
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      UpperCamelCase_			:







						'''simple docstring'''



						def __init__( self       :Tuple		,						lowerCAmelCase__       :Optional[int]		,						lowerCAmelCase__       :Tuple=13		,						lowerCAmelCase__       :Optional[Any]=32		,						lowerCAmelCase__       :Any=2		,						lowerCAmelCase__       :Any=3		,						lowerCAmelCase__       :Tuple=16		,						lowerCAmelCase__       :List[str]=[1, 2, 1]		,						lowerCAmelCase__       :List[str]=[2, 2, 4]		,						lowerCAmelCase__       :Union[str, Any]=2		,						lowerCAmelCase__       :Optional[Any]=2.0		,						lowerCAmelCase__       :List[str]=True		,						lowerCAmelCase__       :Tuple=0.0		,						lowerCAmelCase__       :List[str]=0.0		,						lowerCAmelCase__       :Tuple=0.1		,						lowerCAmelCase__       :List[str]="gelu"		,						lowerCAmelCase__       :Union[str, Any]=False		,						lowerCAmelCase__       :Optional[Any]=True		,						lowerCAmelCase__       :Dict=0.02		,						lowerCAmelCase__       :List[str]=1E-5		,						lowerCAmelCase__       :Optional[int]=True		,						lowerCAmelCase__       :Dict=None		,						lowerCAmelCase__       :Optional[int]=True		,						lowerCAmelCase__       :int=10		,						lowerCAmelCase__       :List[Any]=8		,						)     ->Tuple:
										lowercase						    =			parent
										lowercase						    =			batch_size
										lowercase						    =			image_size
										lowercase						    =			patch_size
										lowercase						    =			num_channels
										lowercase						    =			embed_dim
										lowercase						    =			depths
										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						    =			patch_norm
										lowercase						    =			layer_norm_eps
										lowercase						    =			initializer_range
										lowercase						    =			is_training
										lowercase						    =			scope
										lowercase						    =			use_labels
										lowercase						    =			type_sequence_label_size
										lowercase						    =			encoder_stride





						def 					SCREAMING_SNAKE_CASE( self       :Dict    )     ->int:
										lowercase						    =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

										lowercase						    =			self.get_config()

										return config, pixel_values, labels





						def 					SCREAMING_SNAKE_CASE( self       :Tuple    )     ->int:
										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 					SCREAMING_SNAKE_CASE( self       :Optional[int]		,						lowerCAmelCase__       :Any		,						lowerCAmelCase__       :Tuple		,						lowerCAmelCase__       :List[Any]    )     ->str:
										lowercase						    =			DonutSwinModel(config=lowerCamelCase__    )
										model.to(lowerCamelCase__    )
										model.eval()
										lowercase						    =			model(lowerCamelCase__    )

										lowercase						    =			((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths    ) - 1))
										lowercase						    =			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 					SCREAMING_SNAKE_CASE( self       :str    )     ->Dict:
										lowercase						    =			self.prepare_config_and_inputs()
										(
										    (
										    lowercase						
										)    ,  (
										    lowercase						
										)    ,  (
										    lowercase						
										)    ,  						
										)						    =			config_and_inputs
										lowercase						    =			{"pixel_values": pixel_values}
										return config, inputs_dict





@require_torch
class      UpperCamelCase_			(			__UpperCAmelCase		,						__UpperCAmelCase		,						unittest.TestCase		):







						'''simple docstring'''



						UpperCamelCase			:     List[str]							      =				(DonutSwinModel,) if is_torch_available() else ()
						UpperCamelCase			:     Any							      =				{"""feature-extraction""": DonutSwinModel} if is_torch_available() else {}
						UpperCamelCase			:     int							      =				True

						UpperCamelCase			:     Union[str, Any]							      =				False
						UpperCamelCase			:     Any							      =				False
						UpperCamelCase			:     int							      =				False





						def 					SCREAMING_SNAKE_CASE( self       :Any    )     ->Union[str, Any]:
										lowercase						    =			DonutSwinModelTester(self    )
										lowercase						    =			ConfigTester(self		,						config_class=lowerCamelCase__		,						embed_dim=37    )





						def 					SCREAMING_SNAKE_CASE( self       :List[str]    )     ->Union[str, Any]:
										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 					SCREAMING_SNAKE_CASE( self       :int    )     ->Optional[Any]:
										return





						def 					SCREAMING_SNAKE_CASE( self       :List[Any]    )     ->Any:
										lowercase						    =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCamelCase__    )





						def 					SCREAMING_SNAKE_CASE( self       :int    )     ->str:
										pass





						def 					SCREAMING_SNAKE_CASE( self       :Dict    )     ->Optional[int]:
										lowercase    ,  lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														lowercase						    =			model_class(lowerCamelCase__    )
														self.assertIsInstance(model.get_input_embeddings()		,						(nn.Module)    )
														lowercase						    =			model.get_output_embeddings()
														self.assertTrue(x is None or isinstance(lowerCamelCase__		,						nn.Linear    )    )





						def 					SCREAMING_SNAKE_CASE( self       :List[str]    )     ->List[str]:
										lowercase    ,  lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()

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

														lowercase						    =			["pixel_values"]
														self.assertListEqual(arg_names[:1]		,						lowerCamelCase__    )





						def 					SCREAMING_SNAKE_CASE( self       :int    )     ->str:
										lowercase    ,  lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()
										lowercase						    =			True

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

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

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

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

														if hasattr(self.model_tester		,						"num_hidden_states_types"    ):
																		lowercase						    =			self.model_tester.num_hidden_states_types
														else:
																		# also another +1 for reshaped_hidden_states
																		lowercase						    =			2
														self.assertEqual(out_len + added_hidden_states		,						len(lowerCamelCase__    )    )

														lowercase						    =			outputs.attentions

														self.assertEqual(len(lowerCamelCase__    )		,						lowerCamelCase__    )

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





						def 					SCREAMING_SNAKE_CASE( self       :Union[str, Any]		,						lowerCAmelCase__       :str		,						lowerCAmelCase__       :str		,						lowerCAmelCase__       :Dict		,						lowerCAmelCase__       :str    )     ->Dict:
										lowercase						    =			model_class(lowerCamelCase__    )
										model.to(lowerCamelCase__    )
										model.eval()

										with torch.no_grad():
														lowercase						    =			model(**self._prepare_for_class(lowerCamelCase__		,						lowerCamelCase__    )    )

										lowercase						    =			outputs.hidden_states

										lowercase						    =			getattr(
										    self.model_tester		,						"expected_num_hidden_layers"		,						len(self.model_tester.depths    ) + 1    )
										self.assertEqual(len(lowerCamelCase__    )		,						lowerCamelCase__    )

										# DonutSwin has a different seq_length
										lowercase						    =			(
										    config.patch_size
										    if isinstance(config.patch_size		,						collections.abc.Iterable    )
										    else (config.patch_size, config.patch_size)
										)

										lowercase						    =			(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]		,						)

										lowercase						    =			outputs.reshaped_hidden_states
										self.assertEqual(len(lowerCamelCase__    )		,						lowerCamelCase__    )

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





						def 					SCREAMING_SNAKE_CASE( self       :Any    )     ->str:
										lowercase    ,  lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()

										lowercase						    =			(
										    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:
														lowercase						    =			True
														self.check_hidden_states_output(lowerCamelCase__		,						lowerCamelCase__		,						lowerCamelCase__		,						lowerCamelCase__    )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														lowercase						    =			True

														self.check_hidden_states_output(lowerCamelCase__		,						lowerCamelCase__		,						lowerCamelCase__		,						lowerCamelCase__    )





						def 					SCREAMING_SNAKE_CASE( self       :Any    )     ->List[Any]:
										lowercase    ,  lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()
										lowercase						    =			3

										lowercase						    =			(
										    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)
										)
										lowercase						    =			(
										    config.patch_size
										    if isinstance(config.patch_size		,						collections.abc.Iterable    )
										    else (config.patch_size, config.patch_size)
										)

										lowercase						    =			image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
										lowercase						    =			image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

										for model_class in self.all_model_classes:
														lowercase						    =			True
														self.check_hidden_states_output(lowerCamelCase__		,						lowerCamelCase__		,						lowerCamelCase__		,						(padded_height, padded_width)    )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														lowercase						    =			True
														self.check_hidden_states_output(lowerCamelCase__		,						lowerCamelCase__		,						lowerCamelCase__		,						(padded_height, padded_width)    )





						@slow
						def 					SCREAMING_SNAKE_CASE( self       :Optional[Any]    )     ->List[Any]:



										for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowercase						    =			DonutSwinModel.from_pretrained(lowerCamelCase__    )
														self.assertIsNotNone(lowerCamelCase__    )





						def 					SCREAMING_SNAKE_CASE( self       :Union[str, Any]    )     ->Optional[int]:
										lowercase    ,  lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()

										lowercase						    =			_config_zero_init(lowerCamelCase__    )
										for model_class in self.all_model_classes:
														lowercase						    =			model_class(config=lowerCamelCase__    )
														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'''		,						)




from __future__ import annotations

import random
import string





class      UpperCamelCase_			:







						'''simple docstring'''



						def __init__( self       :Dict		,						lowerCAmelCase__       :str | None = None    )     ->None:
										lowercase						    =			passcode or self.__passcode_creator()
										lowercase						    =			self.__make_key_list()
										lowercase						    =			self.__make_shift_key()





						def __str__( self       :Dict    )     ->str:
										return "".join(self.__passcode    )





						def 					SCREAMING_SNAKE_CASE( self       :str		,						lowerCAmelCase__       :list[int]    )     ->list[int]:
										for i in range(1		,						len(lowerCAmelCase__    )		,						2    ):
														iterlist[i] *= -1
										return iterlist





						def 					SCREAMING_SNAKE_CASE( self       :int    )     ->list[str]:
										lowercase						    =			string.ascii_letters + string.digits
										lowercase						    =			[random.choice(lowerCAmelCase__    ) for _ in range(random.randint(10		,						20    )    )]
										return password





						def 					SCREAMING_SNAKE_CASE( self       :Union[str, Any]    )     ->list[str]:
										lowercase						    =			(
										    string.ascii_letters + string.digits + string.punctuation + " \t\n"
										)

										lowercase						    =			[]

										# creates points known as breakpoints to break the key_list_options at those
										# points and pivot each substring
										lowercase						    =			sorted(set(self.__passcode    )    )
										lowercase						    =			[]

										# algorithm for creating a new shuffled list, keys_l, out of key_list_options
										for i in key_list_options:
														temp_list.extend(lowerCAmelCase__    )

														# checking breakpoints at which to pivot temporary sublist and add it into
														# keys_l
														if i in breakpoints or i == key_list_options[-1]:
																		keys_l.extend(temp_list[::-1]    )
																		temp_list.clear()

        # returning a shuffled keys_l to prevent brute force guessing of shift key
										return keys_l





						def 					SCREAMING_SNAKE_CASE( self       :Optional[int]    )     ->int:
										lowercase						    =			sum(self.__neg_pos([ord(lowerCAmelCase__    ) for x in self.__passcode]    )    )
										return num if num > 0 else len(self.__passcode    )





						def 					SCREAMING_SNAKE_CASE( self       :str		,						lowerCAmelCase__       :str    )     ->str:
										lowercase						    =			""

										# decoding shift like Caesar cipher algorithm implementing negative shift or
										# reverse shift or left shift
										for i in encoded_message:
														lowercase						    =			self.__key_list.index(lowerCAmelCase__    )
														decoded_message += self.__key_list[
														    (position - self.__shift_key) % -len(self.__key_list    )
														]

										return decoded_message





						def 					SCREAMING_SNAKE_CASE( self       :Dict		,						lowerCAmelCase__       :str    )     ->str:
										lowercase						    =			""

										# encoding shift like Caesar cipher algorithm implementing positive shift or
										# forward shift or right shift
										for i in plaintext:
														lowercase						    =			self.__key_list.index(lowerCAmelCase__    )
														encoded_message += self.__key_list[
														    (position + self.__shift_key) % len(self.__key_list    )
														]

										return encoded_message




def    __snake_case       (  __magic_name__ = "Hello, this is a modified Caesar cipher"	):







				'''simple docstring'''


				lowercase						    =			ShuffledShiftCipher()
				return cipa.decrypt(cipa.encrypt(__magic_name__	)	)


if __name__ == "__main__":
						import doctest

						doctest.testmod()
