
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	:

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

					def        _lowerCAmelCase	(			self      :					str					):
											lowercase       :    str											=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

											lowercase       :    Any											=  self.get_config()

											return config, pixel_values, labels

					def        _lowerCAmelCase	(			self      :					str					):
											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      :					Dict ,      lowerCAmelCase      :					Optional[Any] ,      lowerCAmelCase      :					Optional[int] ,      lowerCAmelCase      :					int					):
											lowercase       :    str											=  DonutSwinModel(config=lowerCAmelCase					)
											model.to(lowerCAmelCase					)
											model.eval()
											lowercase       :    int											=  model(lowerCAmelCase					)

											lowercase       :    List[Any]											=  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths					) - 1))
											lowercase       :    Dict											=  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      :					Any					):
											lowercase       :    int											=  self.prepare_config_and_inputs()
											(
											    (
											    lowercase
											)				,				(
											    lowercase
											)				,				(
											    lowercase
											)				,				
											)       :    List[Any]											=  config_and_inputs
											lowercase       :    Dict											=  {'''pixel_values''': pixel_values}
											return config, inputs_dict







@require_torch
class 							UpperCAmelCase	(   __lowerCamelCase						, __lowerCamelCase						, unittest.TestCase					):
					a__: Dict			  =				(DonutSwinModel,) if is_torch_available() else ()
					a__: List[str]			  =				{"""feature-extraction""": DonutSwinModel} if is_torch_available() else {}
					a__: str			  =				True

					a__: List[Any]			  =				False
					a__: Union[str, Any]			  =				False
					a__: Tuple			  =				False

					def        _lowerCAmelCase	(			self      :					str					):
											lowercase       :    Tuple											=  DonutSwinModelTester(self					)
											lowercase       :    Union[str, Any]											=  ConfigTester(self ,      config_class=lowerCAmelCase ,      embed_dim=37					)

					def        _lowerCAmelCase	(			self      :					int					):
											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      :					Optional[Any]					):
											return

					def        _lowerCAmelCase	(			self      :					List[Any]					):
											lowercase       :    Dict											=  self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*lowerCAmelCase					)

					def        _lowerCAmelCase	(			self      :					Optional[int]					):
											# DonutSwin does not use inputs_embeds
											pass

					def        _lowerCAmelCase	(			self      :					List[str]					):
											lowercase				,				lowercase       :    int											=  self.model_tester.prepare_config_and_inputs_for_common()

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

					def        _lowerCAmelCase	(			self      :					Optional[int]					):
											lowercase				,				lowercase       :    str											=  self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	lowercase       :    Any											=  model_class(lowerCAmelCase					)
																	lowercase       :    Union[str, Any]											=  inspect.signature(model.forward					)
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	lowercase       :    Optional[int]											=  [*signature.parameters.keys()]

																	lowercase       :    Optional[int]											=  ['''pixel_values''']
																	self.assertListEqual(arg_names[:1] ,      lowerCAmelCase					)

					def        _lowerCAmelCase	(			self      :					Optional[int]					):
											lowercase				,				lowercase       :    List[str]											=  self.model_tester.prepare_config_and_inputs_for_common()
											lowercase       :    Dict											=  True

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

																	# check that output_attentions also work using config
																	del inputs_dict["output_attentions"]
																	lowercase       :    Optional[Any]											=  True
																	lowercase       :    Any											=  config.window_size**2
																	lowercase       :    Optional[Any]											=  model_class(lowerCAmelCase					)
																	model.to(lowerCAmelCase					)
																	model.eval()
																	with torch.no_grad():
																							lowercase       :    List[Any]											=  model(**self._prepare_for_class(lowerCAmelCase ,      lowerCAmelCase					)					)
																	lowercase       :    str											=  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       :    Optional[int]											=  len(lowerCAmelCase					)

																	# Check attention is always last and order is fine
																	lowercase       :    Union[str, Any]											=  True
																	lowercase       :    Union[str, Any]											=  True
																	lowercase       :    int											=  model_class(lowerCAmelCase					)
																	model.to(lowerCAmelCase					)
																	model.eval()
																	with torch.no_grad():
																							lowercase       :    Tuple											=  model(**self._prepare_for_class(lowerCAmelCase ,      lowerCAmelCase					)					)

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

																	lowercase       :    List[str]											=  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        _lowerCAmelCase	(			self      :					str ,      lowerCAmelCase      :					Dict ,      lowerCAmelCase      :					Any ,      lowerCAmelCase      :					Union[str, Any] ,      lowerCAmelCase      :					str					):
											lowercase       :    Dict											=  model_class(lowerCAmelCase					)
											model.to(lowerCAmelCase					)
											model.eval()

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

											lowercase       :    str											=  outputs.hidden_states

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

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

											lowercase       :    int											=  outputs.reshaped_hidden_states
											self.assertEqual(len(lowerCAmelCase					) ,      lowerCAmelCase					)

											lowercase				,				lowercase				,				lowercase				,				lowercase       :    Optional[Any]											=  reshaped_hidden_states[0].shape
											lowercase       :    Optional[int]											=  (
											    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        _lowerCAmelCase	(			self      :					Any					):
											lowercase				,				lowercase       :    List[str]											=  self.model_tester.prepare_config_and_inputs_for_common()

											lowercase       :    Dict											=  (
											    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       :    Any											=  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       :    Optional[Any]											=  True

																	self.check_hidden_states_output(lowerCAmelCase ,      lowerCAmelCase ,      lowerCAmelCase ,      lowerCAmelCase					)

					def        _lowerCAmelCase	(			self      :					Dict					):
											lowercase				,				lowercase       :    Optional[Any]											=  self.model_tester.prepare_config_and_inputs_for_common()
											lowercase       :    Dict											=  3

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

											lowercase       :    List[Any]											=  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
											lowercase       :    Optional[int]											=  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

											for model_class in self.all_model_classes:
																	lowercase       :    int											=  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       :    List[Any]											=  True
																	self.check_hidden_states_output(lowerCAmelCase ,      lowerCAmelCase ,      lowerCAmelCase ,      (padded_height, padded_width)					)

					@slow
					def        _lowerCAmelCase	(			self      :					Optional[int]					):
											for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowercase       :    str											=  DonutSwinModel.from_pretrained(lowerCAmelCase					)
																	self.assertIsNotNone(lowerCAmelCase					)




					def        _lowerCAmelCase	(			self      :					List[str]					):
											lowercase				,				lowercase       :    Any											=  self.model_tester.prepare_config_and_inputs_for_common()

											lowercase       :    Optional[int]											=  _config_zero_init(lowerCAmelCase					)
											for model_class in self.all_model_classes:
																	lowercase       :    List[Any]											=  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 typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


snake_case__  							=							logging.get_logger(__name__)







class 							UpperCAmelCase	(   __lowerCamelCase					):
					a__: str			  =				["""input_values""", """attention_mask"""]

					def __init__(			self      :					Union[str, Any] ,      lowerCAmelCase      :					Tuple=1 ,      lowerCAmelCase      :					Dict=1_6000 ,      lowerCAmelCase      :					Optional[Any]=128 ,      lowerCAmelCase      :					Dict=1024 ,      lowerCAmelCase      :					List[Any]=0.0 ,      lowerCAmelCase      :					Any=True ,      lowerCAmelCase      :					Tuple=-4.2_67_73_93 ,      lowerCAmelCase      :					Dict=4.5_68_99_74 ,      lowerCAmelCase      :					int=False ,      **lowerCAmelCase      :					Optional[Any] ,      ):
											super().__init__(feature_size=lowerCAmelCase ,      sampling_rate=lowerCAmelCase ,      padding_value=lowerCAmelCase ,      **lowerCAmelCase					)
											lowercase       :    Optional[int]											=  num_mel_bins
											lowercase       :    List[Any]											=  max_length
											lowercase       :    Any											=  do_normalize
											lowercase       :    Any											=  mean
											lowercase       :    Union[str, Any]											=  std
											lowercase       :    int											=  return_attention_mask

					def        _lowerCAmelCase	(			self      :					int ,      lowerCAmelCase      :					np.ndarray ,      lowerCAmelCase      :					int ,      ):
											lowercase       :    List[Any]											=  torch.from_numpy(lowerCAmelCase					).unsqueeze(0					)
											lowercase       :    List[str]											=  ta_kaldi.fbank(
											    lowerCAmelCase ,      htk_compat=lowerCAmelCase ,      sample_frequency=self.sampling_rate ,      use_energy=lowerCAmelCase ,      window_type='''hanning''' ,      num_mel_bins=self.num_mel_bins ,      dither=0.0 ,      frame_shift=10 ,      )

											lowercase       :    Tuple											=  fbank.shape[0]
											lowercase       :    Optional[Any]											=  max_length - n_frames

											# pad or truncate, depending on difference
											if difference > 0:
																	lowercase       :    int											=  torch.nn.ZeroPadad((0, 0, 0, difference)					)
																	lowercase       :    str											=  pad_module(lowerCAmelCase					)
											elif difference < 0:
																	lowercase       :    Optional[int]											=  fbank[0:max_length, :]

											lowercase       :    List[str]											=  fbank.numpy()

											return fbank

					def        _lowerCAmelCase	(			self      :					Tuple ,      lowerCAmelCase      :					np.ndarray					):
											return (input_values - (self.mean)) / (self.std * 2)




					def __call__(			self      :					Any ,      lowerCAmelCase      :					Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,      lowerCAmelCase      :					Optional[int] = None ,      lowerCAmelCase      :					Optional[Union[str, TensorType]] = None ,      **lowerCAmelCase      :					Tuple ,      ):

											if sampling_rate is not None:
																	if sampling_rate != self.sampling_rate:
																							raise ValueError(
																							    f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
																							    f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
																							    f''' {self.sampling_rate} and not {sampling_rate}.'''					)
											else:
																	logger.warning(
																	    '''It is strongly recommended to pass the `sampling_rate` argument to this function. '''
																	    '''Failing to do so can result in silent errors that might be hard to debug.'''					)

											lowercase       :    Optional[Any]											=  isinstance(lowerCAmelCase ,      np.ndarray					) and len(raw_speech.shape					) > 1
											if is_batched_numpy and len(raw_speech.shape					) > 2:
																	raise ValueError(f'''Only mono-channel audio is supported for input to {self}'''					)
											lowercase       :    Tuple											=  is_batched_numpy or (
											    isinstance(lowerCAmelCase ,      (list, tuple)					) and (isinstance(raw_speech[0] ,      (np.ndarray, tuple, list)					))
											)

											if is_batched:
																	lowercase       :    Optional[int]											=  [np.asarray(lowerCAmelCase ,      dtype=np.floataa					) for speech in raw_speech]
											elif not is_batched and not isinstance(lowerCAmelCase ,      np.ndarray					):
																	lowercase       :    Dict											=  np.asarray(lowerCAmelCase ,      dtype=np.floataa					)
											elif isinstance(lowerCAmelCase ,      np.ndarray					) and raw_speech.dtype is np.dtype(np.floataa					):
																	lowercase       :    int											=  raw_speech.astype(np.floataa					)

											# always return batch
											if not is_batched:
																	lowercase       :    Dict											=  [raw_speech]

											# extract fbank features and pad/truncate to max_length
											lowercase       :    Dict											=  [self._extract_fbank_features(lowerCAmelCase ,      max_length=self.max_length					) for waveform in raw_speech]

											# convert into BatchFeature
											lowercase       :    Any											=  BatchFeature({'''input_values''': features}					)

											# make sure list is in array format
											lowercase       :    str											=  padded_inputs.get('''input_values'''					)
											if isinstance(input_values[0] ,      lowerCAmelCase					):
																	lowercase       :    Any											=  [np.asarray(lowerCAmelCase ,      dtype=np.floataa					) for feature in input_values]

											# normalization
											if self.do_normalize:
																	lowercase       :    List[str]											=  [self.normalize(lowerCAmelCase					) for feature in input_values]

											if return_tensors is not None:
																	lowercase       :    str											=  padded_inputs.convert_to_tensors(lowerCAmelCase					)

											return padded_inputs


