
'''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   UpperCamelCase__   :


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case=1_3   ,      snake_case=3_2   ,      snake_case=2   ,      snake_case=3   ,      snake_case=1_6   ,      snake_case=[1, 2, 1]   ,      snake_case=[2, 2, 4]   ,      snake_case=2   ,      snake_case=2.0   ,      snake_case=True   ,      snake_case=0.0   ,      snake_case=0.0   ,      snake_case=0.1   ,      snake_case="gelu"   ,      snake_case=False   ,      snake_case=True   ,      snake_case=0.02   ,      snake_case=1e-5   ,      snake_case=True   ,      snake_case=None   ,      snake_case=True   ,      snake_case=1_0   ,      snake_case=8   ,      ):


							'''simple docstring'''

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







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[int]        =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

							UpperCAmelCase		:							Any        =       self.get_config()

							return config, pixel_values, labels







		def 				A_	(			self      ):


							'''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 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

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

							UpperCAmelCase		:							Optional[int]        =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths      ) - 1))
							UpperCAmelCase		:							Optional[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      ):


							'''simple docstring'''

							UpperCAmelCase		:							Dict        =       self.prepare_config_and_inputs()
							(
							    (
							    UpperCAmelCase				
							) ,			(
							    UpperCAmelCase				
							) ,			(
							    UpperCAmelCase				
							) ,							
							)		:							Any        =       config_and_inputs
							UpperCAmelCase		:							Any        =       {"pixel_values": pixel_values}
							return config, inputs_dict







@require_torch
class   UpperCamelCase__   (       UpperCAmelCase__							,							UpperCAmelCase__							,							unittest.TestCase       ):


		"""simple docstring"""

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

		SCREAMING_SNAKE_CASE__  :     Optional[Any]       =							False
		SCREAMING_SNAKE_CASE__  :     List[Any]       =							False
		SCREAMING_SNAKE_CASE__  :     Optional[int]       =							False







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Tuple        =       DonutSwinModelTester(self      )
							UpperCAmelCase		:							List[Any]        =       ConfigTester(self   ,      config_class=__lowercase   ,      embed_dim=3_7      )







		def 				A_	(			self      ):


							'''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 				A_	(			self      ):


							'''simple docstring'''

							return







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[Any]        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowercase      )







		def 				A_	(			self      ):


							'''simple docstring'''

							pass







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase ,			UpperCAmelCase		:							List[str]        =       self.model_tester.prepare_config_and_inputs_for_common()

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







		def 				A_	(			self      ):


							'''simple docstring'''

							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(__lowercase      )
												UpperCAmelCase		:							Dict        =       inspect.signature(model.forward      )
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												UpperCAmelCase		:							Union[str, Any]        =       [*signature.parameters.keys()]

												UpperCAmelCase		:							int        =       ["pixel_values"]
												self.assertListEqual(arg_names[:1]   ,      __lowercase      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase ,			UpperCAmelCase		:							Union[str, Any]        =       self.model_tester.prepare_config_and_inputs_for_common()
							UpperCAmelCase		:							List[str]        =       True

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

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

												# Check attention is always last and order is fine
												UpperCAmelCase		:							Tuple        =       True
												UpperCAmelCase		:							Dict        =       True
												UpperCAmelCase		:							List[Any]        =       model_class(__lowercase      )
												model.to(__lowercase      )
												model.eval()
												with torch.no_grad():
																	UpperCAmelCase		:							str        =       model(**self._prepare_for_class(__lowercase   ,      __lowercase      )      )

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

												UpperCAmelCase		:							Tuple        =       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 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       model_class(__lowercase      )
							model.to(__lowercase      )
							model.eval()

							with torch.no_grad():
												UpperCAmelCase		:							Tuple        =       model(**self._prepare_for_class(__lowercase   ,      __lowercase      )      )

							UpperCAmelCase		:							int        =       outputs.hidden_states

							UpperCAmelCase		:							List[str]        =       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
							UpperCAmelCase		:							int        =       (
							    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		:							int        =       outputs.reshaped_hidden_states
							self.assertEqual(len(__lowercase      )   ,      __lowercase      )

							UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase		:							Optional[int]        =       reshaped_hidden_states[0].shape
							UpperCAmelCase		:							Optional[Any]        =       (
							    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 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase ,			UpperCAmelCase		:							Tuple        =       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		:							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"]
												UpperCAmelCase		:							List[Any]        =       True

												self.check_hidden_states_output(__lowercase   ,      __lowercase   ,      __lowercase   ,      __lowercase      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase ,			UpperCAmelCase		:							str        =       self.model_tester.prepare_config_and_inputs_for_common()
							UpperCAmelCase		:							Any        =       3

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

							UpperCAmelCase		:							Optional[Any]        =       image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
							UpperCAmelCase		:							int        =       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(__lowercase   ,      __lowercase   ,      __lowercase   ,      (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(__lowercase   ,      __lowercase   ,      __lowercase   ,      (padded_height, padded_width)      )







		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

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







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase ,			UpperCAmelCase		:							str        =       self.model_tester.prepare_config_and_inputs_for_common()

							UpperCAmelCase		:							List[str]        =       _config_zero_init(__lowercase      )
							for model_class in self.all_model_classes:
												UpperCAmelCase		:							Dict        =       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"   ,      )



'''simple docstring'''

import multiprocessing
import os
from typing import BinaryIO, Optional, Union

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.csv.csv import Csv
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader







class   UpperCamelCase__   (       lowercase__       ):


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case = None   ,      snake_case = None   ,      snake_case = None   ,      snake_case = False   ,      snake_case = False   ,      snake_case = None   ,      **snake_case   ,      ):


							'''simple docstring'''

							super().__init__(
							    snake_case   ,      split=snake_case   ,      features=snake_case   ,      cache_dir=snake_case   ,      keep_in_memory=snake_case   ,      streaming=snake_case   ,      num_proc=snake_case   ,      **snake_case   ,      )
							UpperCAmelCase		:							str        =       path_or_paths if isinstance(snake_case   ,      snake_case      ) else {self.split: path_or_paths}
							UpperCAmelCase		:							int        =       Csv(
							    cache_dir=snake_case   ,      data_files=snake_case   ,      features=snake_case   ,      **snake_case   ,      )







		def 				A_	(			self      ):


							'''simple docstring'''

							if self.streaming:
												UpperCAmelCase		:							Optional[Any]        =       self.builder.as_streaming_dataset(split=self.split      )
							# Build regular (map-style) dataset
							else:
												UpperCAmelCase		:							Union[str, Any]        =       None
												UpperCAmelCase		:							str        =       None
												UpperCAmelCase		:							Union[str, Any]        =       None
												UpperCAmelCase		:							int        =       None

												self.builder.download_and_prepare(
												    download_config=snake_case   ,      download_mode=snake_case   ,      verification_mode=snake_case   ,      base_path=snake_case   ,      num_proc=self.num_proc   ,      )
												UpperCAmelCase		:							Tuple        =       self.builder.as_dataset(
												    split=self.split   ,      verification_mode=snake_case   ,      in_memory=self.keep_in_memory      )
							return dataset







class   UpperCamelCase__   :


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case   ,      snake_case = None   ,      snake_case = None   ,      **snake_case   ,      ):


							'''simple docstring'''

							if num_proc is not None and num_proc <= 0:
												raise ValueError(f"num_proc {num_proc} must be an integer > 0."      )

							UpperCAmelCase		:							Tuple        =       dataset
							UpperCAmelCase		:							Dict        =       path_or_buf
							UpperCAmelCase		:							List[Any]        =       batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
							UpperCAmelCase		:							str        =       num_proc
							UpperCAmelCase		:							List[Any]        =       "utf-8"
							UpperCAmelCase		:							Tuple        =       to_csv_kwargs







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       self.to_csv_kwargs.pop("path_or_buf"   ,      snake_case      )
							UpperCAmelCase		:							Any        =       self.to_csv_kwargs.pop("header"   ,      snake_case      )
							UpperCAmelCase		:							Dict        =       self.to_csv_kwargs.pop("index"   ,      snake_case      )

							if isinstance(self.path_or_buf   ,      (str, bytes, os.PathLike)      ):
												with open(self.path_or_buf   ,      "wb+"      ) as buffer:
																	UpperCAmelCase		:							Tuple        =       self._write(file_obj=snake_case   ,      header=snake_case   ,      index=snake_case   ,      **self.to_csv_kwargs      )
							else:
												UpperCAmelCase		:							Any        =       self._write(file_obj=self.path_or_buf   ,      header=snake_case   ,      index=snake_case   ,      **self.to_csv_kwargs      )
							return written







		def 				A_	(			self   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase		:							Optional[int]        =       args

							UpperCAmelCase		:							List[str]        =       query_table(
							    table=self.dataset.data   ,      key=slice(snake_case   ,      offset + self.batch_size      )   ,      indices=self.dataset._indices   ,      )
							UpperCAmelCase		:							int        =       batch.to_pandas().to_csv(
							    path_or_buf=snake_case   ,      header=header if (offset == 0) else False   ,      index=snake_case   ,      **snake_case      )
							return csv_str.encode(self.encoding      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      **snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       0

							if self.num_proc is None or self.num_proc == 1:
												for offset in logging.tqdm(
												    range(0   ,      len(self.dataset      )   ,      self.batch_size      )   ,      unit="ba"   ,      disable=not logging.is_progress_bar_enabled()   ,      desc="Creating CSV from Arrow format"   ,      ):
																	UpperCAmelCase		:							Any        =       self._batch_csv((offset, header, index, to_csv_kwargs)      )
																	written += file_obj.write(snake_case      )

							else:
												UpperCAmelCase ,			UpperCAmelCase		:							Union[str, Any]        =       len(self.dataset      ), self.batch_size
												with multiprocessing.Pool(self.num_proc      ) as pool:
																	for csv_str in logging.tqdm(
																	    pool.imap(
																	        self._batch_csv   ,      [(offset, header, index, to_csv_kwargs) for offset in range(0   ,      snake_case   ,      snake_case      )]   ,      )   ,      total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size   ,      unit="ba"   ,      disable=not logging.is_progress_bar_enabled()   ,      desc="Creating CSV from Arrow format"   ,      ):
																						written += file_obj.write(snake_case      )

							return written
