


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






						def __init__(      self		:  Optional[Any]    ,     lowercase_		:  Any    ,     lowercase_		:  Dict=13    ,     lowercase_		:  List[Any]=32    ,     lowercase_		:  Dict=2    ,     lowercase_		:  Any=3    ,     lowercase_		:  List[str]=16    ,     lowercase_		:  Optional[Any]=[1, 2, 1]    ,     lowercase_		:  Optional[Any]=[2, 2, 4]    ,     lowercase_		:  List[str]=2    ,     lowercase_		:  Any=2.0    ,     lowercase_		:  Any=True    ,     lowercase_		:  List[Any]=0.0    ,     lowercase_		:  Dict=0.0    ,     lowercase_		:  List[Any]=0.1    ,     lowercase_		:  Union[str, Any]="gelu"    ,     lowercase_		:  Optional[int]=False    ,     lowercase_		:  Optional[Any]=True    ,     lowercase_		:  str=0.02    ,     lowercase_		:  Tuple=1E-5    ,     lowercase_		:  str=True    ,     lowercase_		:  Tuple=None    ,     lowercase_		:  Union[str, Any]=True    ,     lowercase_		:  Optional[Any]=10    ,     lowercase_		:  List[Any]=8    ,     )      ->		Union[str, Any]:
													"""simple docstring"""




													_lowerCamelCase :	int						=parent
													_lowerCamelCase :	List[str]						=batch_size
													_lowerCamelCase :	str						=image_size
													_lowerCamelCase :	List[str]						=patch_size
													_lowerCamelCase :	Tuple						=num_channels
													_lowerCamelCase :	List[str]						=embed_dim
													_lowerCamelCase :	int						=depths
													_lowerCamelCase :	Optional[Any]						=num_heads
													_lowerCamelCase :	Optional[int]						=window_size
													_lowerCamelCase :	Union[str, Any]						=mlp_ratio
													_lowerCamelCase :	Tuple						=qkv_bias
													_lowerCamelCase :	List[str]						=hidden_dropout_prob
													_lowerCamelCase :	str						=attention_probs_dropout_prob
													_lowerCamelCase :	List[Any]						=drop_path_rate
													_lowerCamelCase :	Any						=hidden_act
													_lowerCamelCase :	Optional[Any]						=use_absolute_embeddings
													_lowerCamelCase :	List[Any]						=patch_norm
													_lowerCamelCase :	List[str]						=layer_norm_eps
													_lowerCamelCase :	str						=initializer_range
													_lowerCamelCase :	Union[str, Any]						=is_training
													_lowerCamelCase :	List[Any]						=scope
													_lowerCamelCase :	str						=use_labels
													_lowerCamelCase :	Any						=type_sequence_label_size
													_lowerCamelCase :	Union[str, Any]						=encoder_stride






						def  lowerCamelCase (      self		:  Union[str, Any]				)      ->		List[Any]:
													"""simple docstring"""




													_lowerCamelCase :	Optional[Any]						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

													_lowerCamelCase :	Dict						=self.get_config()

													return config, pixel_values, labels






						def  lowerCamelCase (      self		:  List[str]				)      ->		Union[str, Any]:
													"""simple docstring"""




													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  lowerCamelCase (      self		:  Union[str, Any]    ,     lowercase_		:  int    ,     lowercase_		:  Optional[int]    ,     lowercase_		:  List[Any]				)      ->		List[Any]:
													"""simple docstring"""




													_lowerCamelCase :	str						=DonutSwinModel(config=lowercase_				)
													model.to(lowercase_				)
													model.eval()
													_lowerCamelCase :	Union[str, Any]						=model(lowercase_				)

													_lowerCamelCase :	List[str]						=((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths				) - 1))
													_lowerCamelCase :	str						=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  lowerCamelCase (      self		:  int				)      ->		List[Any]:
													"""simple docstring"""




													_lowerCamelCase :	Tuple						=self.prepare_config_and_inputs()
													(
													    _lowerCamelCase  
													) :	Dict						=config_and_inputs
													_lowerCamelCase :	Optional[int]						={'pixel_values': pixel_values}
													return config, inputs_dict




@require_torch
class A						(     UpperCamelCase_					,							UpperCamelCase_					,							unittest.TestCase  ):
						UpperCamelCase__							:						List[str]   =(DonutSwinModel,) if is_torch_available() else ()
						UpperCamelCase__							:						Union[str, Any]   ={'feature-extraction': DonutSwinModel} if is_torch_available() else {}
						UpperCamelCase__							:						Any   =True

						UpperCamelCase__							:						Optional[Any]   =False
						UpperCamelCase__							:						Any   =False
						UpperCamelCase__							:						Tuple   =False






						def  lowerCamelCase (      self		:  List[Any]				)      ->		Tuple:
													"""simple docstring"""




													_lowerCamelCase :	Optional[Any]						=DonutSwinModelTester(self				)
													_lowerCamelCase :	Tuple						=ConfigTester(self    ,     config_class=lowercase_    ,     embed_dim=37				)






						def  lowerCamelCase (      self		:  Optional[int]				)      ->		Optional[int]:
													"""simple docstring"""




													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  lowerCamelCase (      self		:  List[str]				)      ->		int:
													"""simple docstring"""




													return






						def  lowerCamelCase (      self		:  List[str]				)      ->		Optional[int]:
													"""simple docstring"""




													_lowerCamelCase :	List[str]						=self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*lowercase_				)






						def  lowerCamelCase (      self		:  int				)      ->		str:
													"""simple docstring"""




													pass






						def  lowerCamelCase (      self		:  Any				)      ->		List[Any]:
													"""simple docstring"""




													_lowerCamelCase :	Any						=self.model_tester.prepare_config_and_inputs_for_common()

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






						def  lowerCamelCase (      self		:  List[str]				)      ->		Optional[int]:
													"""simple docstring"""




													_lowerCamelCase :	Union[str, Any]						=self.model_tester.prepare_config_and_inputs_for_common()

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

																				_lowerCamelCase :	Union[str, Any]						=['pixel_values']
																				self.assertListEqual(arg_names[:1]    ,     lowercase_				)






						def  lowerCamelCase (      self		:  Any				)      ->		Optional[int]:
													"""simple docstring"""




													_lowerCamelCase :	Any						=self.model_tester.prepare_config_and_inputs_for_common()
													_lowerCamelCase :	Optional[int]						=True

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

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

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

																				# Check attention is always last and order is fine
																				_lowerCamelCase :	str						=True
																				_lowerCamelCase :	Dict						=True
																				_lowerCamelCase :	Any						=model_class(lowercase_				)
																				model.to(lowercase_				)
																				model.eval()
																				with torch.no_grad():
																											_lowerCamelCase :	int						=model(**self._prepare_for_class(lowercase_    ,     lowercase_				)				)

																				if hasattr(self.model_tester    ,     'num_hidden_states_types'				):
																											_lowerCamelCase :	Any						=self.model_tester.num_hidden_states_types
																				else:
																											# also another +1 for reshaped_hidden_states
																											_lowerCamelCase :	Optional[Any]						=2
																				self.assertEqual(out_len + added_hidden_states    ,     len(lowercase_				)				)

																				_lowerCamelCase :	Any						=outputs.attentions

																				self.assertEqual(len(lowercase_				)    ,     lowercase_				)

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






						def  lowerCamelCase (      self		:  Dict    ,     lowercase_		:  Dict    ,     lowercase_		:  List[str]    ,     lowercase_		:  int    ,     lowercase_		:  Optional[Any]				)      ->		int:
													"""simple docstring"""




													_lowerCamelCase :	List[str]						=model_class(lowercase_				)
													model.to(lowercase_				)
													model.eval()

													with torch.no_grad():
																				_lowerCamelCase :	List[str]						=model(**self._prepare_for_class(lowercase_    ,     lowercase_				)				)

													_lowerCamelCase :	Any						=outputs.hidden_states

													_lowerCamelCase :	List[Any]						=getattr(
													    self.model_tester    ,     'expected_num_hidden_layers'    ,     len(self.model_tester.depths				) + 1				)
													self.assertEqual(len(lowercase_				)    ,     lowercase_				)

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

													_lowerCamelCase :	List[Any]						=(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]    ,     )

													_lowerCamelCase :	List[str]						=outputs.reshaped_hidden_states
													self.assertEqual(len(lowercase_				)    ,     lowercase_				)

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






						def  lowerCamelCase (      self		:  Optional[int]				)      ->		Optional[Any]:
													"""simple docstring"""




													_lowerCamelCase :	int						=self.model_tester.prepare_config_and_inputs_for_common()

													_lowerCamelCase :	Optional[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:
																				_lowerCamelCase :	Union[str, Any]						=True
																				self.check_hidden_states_output(lowercase_    ,     lowercase_    ,     lowercase_    ,     lowercase_				)

																				# check that output_hidden_states also work using config
																				del inputs_dict["output_hidden_states"]
																				_lowerCamelCase :	Optional[int]						=True

																				self.check_hidden_states_output(lowercase_    ,     lowercase_    ,     lowercase_    ,     lowercase_				)






						def  lowerCamelCase (      self		:  Optional[int]				)      ->		Tuple:
													"""simple docstring"""




													_lowerCamelCase :	List[str]						=self.model_tester.prepare_config_and_inputs_for_common()
													_lowerCamelCase :	Union[str, Any]						=3

													_lowerCamelCase :	List[str]						=(
													    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)
													)
													_lowerCamelCase :	str						=(
													    config.patch_size
													    if isinstance(config.patch_size    ,     collections.abc.Iterable				)
													    else (config.patch_size, config.patch_size)
													)

													_lowerCamelCase :	Dict						=image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
													_lowerCamelCase :	Optional[Any]						=image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

													for model_class in self.all_model_classes:
																				_lowerCamelCase :	Tuple						=True
																				self.check_hidden_states_output(lowercase_    ,     lowercase_    ,     lowercase_    ,     (padded_height, padded_width)				)

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






						@slow
						def  lowerCamelCase (      self		:  Tuple				)      ->		Optional[Any]:
													"""simple docstring"""




													for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				_lowerCamelCase :	Optional[Any]						=DonutSwinModel.from_pretrained(lowercase_				)
																				self.assertIsNotNone(lowercase_				)






						def  lowerCamelCase (      self		:  str				)      ->		Tuple:
													"""simple docstring"""




													_lowerCamelCase :	List[Any]						=self.model_tester.prepare_config_and_inputs_for_common()

													_lowerCamelCase :	List[Any]						=_config_zero_init(lowercase_				)
													for model_class in self.all_model_classes:
																				_lowerCamelCase :	int						=model_class(config=lowercase_				)
																				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 dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import is_torch_available, is_transformers_available


if is_transformers_available() and is_torch_available():
 from .image_encoder import PaintByExampleImageEncoder
 from .pipeline_paint_by_example import PaintByExamplePipeline


