






'''simple docstring'''





import collections
import inspect
import unittest

from transformers import SwinConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel
		from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class 							a_				:


							'''simple docstring'''






							def __init__(	self    ,    lowercase_    ,    lowercase_=1_3    ,    lowercase_=3_2    ,    lowercase_=2    ,    lowercase_=3    ,    lowercase_=1_6    ,    lowercase_=[1, 2, 1]    ,    lowercase_=[2, 2, 4]    ,    lowercase_=2    ,    lowercase_=2.0    ,    lowercase_=True    ,    lowercase_=0.0    ,    lowercase_=0.0    ,    lowercase_=0.1    ,    lowercase_="gelu"    ,    lowercase_=False    ,    lowercase_=True    ,    lowercase_=0.02    ,    lowercase_=1e-5    ,    lowercase_=True    ,    lowercase_=None    ,    lowercase_=True    ,    lowercase_=1_0    ,    lowercase_=8    ,    lowercase_=["stage1", "stage2"]    ,    lowercase_=[1, 2]    ,    )      ->      Dict:
														'''simple docstring'''

														lowerCAmelCase_       		=  parent
														lowerCAmelCase_       		=  batch_size
														lowerCAmelCase_       		=  image_size
														lowerCAmelCase_       		=  patch_size
														lowerCAmelCase_       		=  num_channels
														lowerCAmelCase_       		=  embed_dim
														lowerCAmelCase_       		=  depths
														lowerCAmelCase_       		=  num_heads
														lowerCAmelCase_       		=  window_size
														lowerCAmelCase_       		=  mlp_ratio
														lowerCAmelCase_       		=  qkv_bias
														lowerCAmelCase_       		=  hidden_dropout_prob
														lowerCAmelCase_       		=  attention_probs_dropout_prob
														lowerCAmelCase_       		=  drop_path_rate
														lowerCAmelCase_       		=  hidden_act
														lowerCAmelCase_       		=  use_absolute_embeddings
														lowerCAmelCase_       		=  patch_norm
														lowerCAmelCase_       		=  layer_norm_eps
														lowerCAmelCase_       		=  initializer_range
														lowerCAmelCase_       		=  is_training
														lowerCAmelCase_       		=  scope
														lowerCAmelCase_       		=  use_labels
														lowerCAmelCase_       		=  type_sequence_label_size
														lowerCAmelCase_       		=  encoder_stride
														lowerCAmelCase_       		=  out_features
														lowerCAmelCase_       		=  out_indices

							def   _lowercase (	self     )      ->      str:
														'''simple docstring'''

														lowerCAmelCase_       		=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

														lowerCAmelCase_       		=  self.get_config()

														return config, pixel_values, labels

							def   _lowercase (	self     )      ->      Optional[Any]:
														'''simple docstring'''

														return SwinConfig(
														    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    ,    out_features=self.out_features    ,    out_indices=self.out_indices    ,    )

							def   _lowercase (	self    ,    lowercase_    ,    lowercase_    ,    lowercase_     )      ->      Union[str, Any]:
														'''simple docstring'''

														lowerCAmelCase_       		=  SwinModel(config=lowercase_     )
														model.to(lowercase_     )
														model.eval()
														lowerCAmelCase_       		=  model(lowercase_     )

														lowerCAmelCase_       		=  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths     ) - 1))
														lowerCAmelCase_       		=  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   _lowercase (	self    ,    lowercase_    ,    lowercase_    ,    lowercase_     )      ->      List[str]:
														'''simple docstring'''

														lowerCAmelCase_       		=  SwinBackbone(config=lowercase_     )
														model.to(lowercase_     )
														model.eval()
														lowerCAmelCase_       		=  model(lowercase_     )

														# verify hidden states
														self.parent.assertEqual(len(result.feature_maps     )    ,    len(config.out_features     )     )
														self.parent.assertListEqual(list(result.feature_maps[0].shape     )    ,    [self.batch_size, model.channels[0], 1_6, 1_6]     )

														# verify channels
														self.parent.assertEqual(len(model.channels     )    ,    len(config.out_features     )     )

														# verify backbone works with out_features=None
														lowerCAmelCase_       		=  None
														lowerCAmelCase_       		=  SwinBackbone(config=lowercase_     )
														model.to(lowercase_     )
														model.eval()
														lowerCAmelCase_       		=  model(lowercase_     )

														# verify feature maps
														self.parent.assertEqual(len(result.feature_maps     )    ,    1     )
														self.parent.assertListEqual(list(result.feature_maps[0].shape     )    ,    [self.batch_size, model.channels[-1], 4, 4]     )

														# verify channels
														self.parent.assertEqual(len(model.channels     )    ,    1     )

							def   _lowercase (	self    ,    lowercase_    ,    lowercase_    ,    lowercase_     )      ->      Optional[Any]:
														'''simple docstring'''

														lowerCAmelCase_       		=  SwinForMaskedImageModeling(config=lowercase_     )
														model.to(lowercase_     )
														model.eval()
														lowerCAmelCase_       		=  model(lowercase_     )
														self.parent.assertEqual(
														    result.logits.shape    ,    (self.batch_size, self.num_channels, self.image_size, self.image_size)     )

														# test greyscale images
														lowerCAmelCase_       		=  1
														lowerCAmelCase_       		=  SwinForMaskedImageModeling(lowercase_     )
														model.to(lowercase_     )
														model.eval()

														lowerCAmelCase_       		=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
														lowerCAmelCase_       		=  model(lowercase_     )
														self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, 1, self.image_size, self.image_size)     )

							def   _lowercase (	self    ,    lowercase_    ,    lowercase_    ,    lowercase_     )      ->      Any:
														'''simple docstring'''

														lowerCAmelCase_       		=  self.type_sequence_label_size
														lowerCAmelCase_       		=  SwinForImageClassification(lowercase_     )
														model.to(lowercase_     )
														model.eval()
														lowerCAmelCase_       		=  model(lowercase_    ,    labels=lowercase_     )
														self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.type_sequence_label_size)     )

														# test greyscale images
														lowerCAmelCase_       		=  1
														lowerCAmelCase_       		=  SwinForImageClassification(lowercase_     )
														model.to(lowercase_     )
														model.eval()

														lowerCAmelCase_       		=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
														lowerCAmelCase_       		=  model(lowercase_     )
														self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.type_sequence_label_size)     )






							def   _lowercase (	self     )      ->      Tuple:
														'''simple docstring'''

														lowerCAmelCase_       		=  self.prepare_config_and_inputs()
														(
														    (
														    lowerCAmelCase_     
														)		,     (
														    lowerCAmelCase_     
														)		,     (
														    lowerCAmelCase_     
														)		,          
														)       		=  config_and_inputs
														lowerCAmelCase_       		=  {'pixel_values': pixel_values}
														return config, inputs_dict




@require_torch
class 							a_				(		a_			,			a_			,			unittest.TestCase	):


							'''simple docstring'''






							__a:			List[str]									=					(
							    (
							        SwinModel,
							        SwinBackbone,
							        SwinForImageClassification,
							        SwinForMaskedImageModeling,
							    )
							    if is_torch_available()
							    else ()
							)
							__a:			List[str]									=					(
							    {'''feature-extraction''': SwinModel, '''image-classification''': SwinForImageClassification}
							    if is_torch_available()
							    else {}
							)
							__a:			Union[str, Any]									=					True

							__a:			Tuple									=					False
							__a:			Any									=					False
							__a:			Any									=					False

							def   _lowercase (	self     )      ->      List[str]:
														'''simple docstring'''

														lowerCAmelCase_       		=  SwinModelTester(self     )
														lowerCAmelCase_       		=  ConfigTester(self    ,    config_class=lowercase_    ,    embed_dim=3_7     )

							def   _lowercase (	self     )      ->      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   _lowercase (	self     )      ->      Optional[int]:
														'''simple docstring'''

														return

							def   _lowercase (	self     )      ->      Optional[int]:
														'''simple docstring'''

														lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*lowercase_     )

							@unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'     )
							def   _lowercase (	self     )      ->      Tuple:
														'''simple docstring'''

														pass

							def   _lowercase (	self     )      ->      List[str]:
														'''simple docstring'''

														super().test_training_gradient_checkpointing()

							def   _lowercase (	self     )      ->      List[Any]:
														'''simple docstring'''

														lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_backbone(*lowercase_     )

							def   _lowercase (	self     )      ->      Dict:
														'''simple docstring'''

														lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_     )

							def   _lowercase (	self     )      ->      List[str]:
														'''simple docstring'''

														lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*lowercase_     )

							@unittest.skip(reason='Swin does not use inputs_embeds'     )
							def   _lowercase (	self     )      ->      str:
														'''simple docstring'''

														pass

							@unittest.skip(reason='Swin Transformer does not use feedforward chunking'     )
							def   _lowercase (	self     )      ->      List[str]:
														'''simple docstring'''

														pass

							def   _lowercase (	self     )      ->      Tuple:
														'''simple docstring'''

														lowerCAmelCase_		,     lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs_for_common()

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

							def   _lowercase (	self     )      ->      Optional[int]:
														'''simple docstring'''

														lowerCAmelCase_		,     lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs_for_common()

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

																					lowerCAmelCase_       		=  ['pixel_values']
																					self.assertListEqual(arg_names[:1]    ,    lowercase_     )

							def   _lowercase (	self     )      ->      Union[str, Any]:
														'''simple docstring'''

														lowerCAmelCase_		,     lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs_for_common()
														lowerCAmelCase_       		=  True

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

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

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

																					# also another +1 for reshaped_hidden_states
																					lowerCAmelCase_       		=  1 if model_class.__name__ == 'SwinBackbone' else 2
																					self.assertEqual(out_len + added_hidden_states    ,    len(lowercase_     )     )

																					lowerCAmelCase_       		=  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   _lowercase (	self    ,    lowercase_    ,    lowercase_    ,    lowercase_    ,    lowercase_     )      ->      Union[str, Any]:
														'''simple docstring'''

														lowerCAmelCase_       		=  model_class(lowercase_     )
														model.to(lowercase_     )
														model.eval()

														with torch.no_grad():
																					lowerCAmelCase_       		=  model(**self._prepare_for_class(lowercase_    ,    lowercase_     )     )

														lowerCAmelCase_       		=  outputs.hidden_states

														lowerCAmelCase_       		=  getattr(
														    self.model_tester    ,    'expected_num_hidden_layers'    ,    len(self.model_tester.depths     ) + 1     )
														self.assertEqual(len(lowercase_     )    ,    lowercase_     )

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

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

														if not model_class.__name__ == "SwinBackbone":
																					lowerCAmelCase_       		=  outputs.reshaped_hidden_states
																					self.assertEqual(len(lowercase_     )    ,    lowercase_     )

																					lowerCAmelCase_		,     lowerCAmelCase_		,     lowerCAmelCase_		,     lowerCAmelCase_       		=  reshaped_hidden_states[0].shape
																					lowerCAmelCase_       		=  (
																					    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   _lowercase (	self     )      ->      int:
														'''simple docstring'''

														lowerCAmelCase_		,     lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs_for_common()

														lowerCAmelCase_       		=  (
														    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_       		=  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_       		=  True

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

							def   _lowercase (	self     )      ->      List[str]:
														'''simple docstring'''

														lowerCAmelCase_		,     lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs_for_common()
														lowerCAmelCase_       		=  3

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

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

														for model_class in self.all_model_classes:
																					lowerCAmelCase_       		=  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_       		=  True
																					self.check_hidden_states_output(lowercase_    ,    lowercase_    ,    lowercase_    ,    (padded_height, padded_width)     )

							@slow
							def   _lowercase (	self     )      ->      Any:
														'''simple docstring'''

														for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCAmelCase_       		=  SwinModel.from_pretrained(lowercase_     )
																					self.assertIsNotNone(lowercase_     )






							def   _lowercase (	self     )      ->      Dict:
														'''simple docstring'''

														lowerCAmelCase_		,     lowerCAmelCase_       		=  self.model_tester.prepare_config_and_inputs_for_common()

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




@require_vision
@require_torch
class 							a_				(		unittest.TestCase	):


							'''simple docstring'''






							@cached_property
							def   _lowercase (	self     )      ->      Tuple:
														'''simple docstring'''

														return (
														    AutoImageProcessor.from_pretrained('microsoft/swin-tiny-patch4-window7-224'     )
														    if is_vision_available()
														    else None
														)






							@slow
							def   _lowercase (	self     )      ->      Optional[Any]:
														'''simple docstring'''

														lowerCAmelCase_       		=  SwinForImageClassification.from_pretrained('microsoft/swin-tiny-patch4-window7-224'     ).to(lowercase_     )
														lowerCAmelCase_       		=  self.default_image_processor

														lowerCAmelCase_       		=  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
														lowerCAmelCase_       		=  image_processor(images=lowercase_    ,    return_tensors='pt'     ).to(lowercase_     )

														# forward pass
														with torch.no_grad():
																					lowerCAmelCase_       		=  model(**lowercase_     )

														# verify the logits
														lowerCAmelCase_       		=  torch.Size((1, 1_0_0_0)     )
														self.assertEqual(outputs.logits.shape    ,    lowercase_     )
														lowerCAmelCase_       		=  torch.tensor([-0.09_48, -0.64_54, -0.09_21]     ).to(lowercase_     )
														self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,    lowercase_    ,    atol=1e-4     )     )




@require_torch
class 							a_				(		unittest.TestCase			,			a_	):


							'''simple docstring'''






							__a:			Tuple									=					(SwinBackbone,) if is_torch_available() else ()
							__a:			Any									=					SwinConfig

							def   _lowercase (	self     )      ->      Optional[int]:
														'''simple docstring'''

														lowerCAmelCase_       		=  SwinModelTester(self     )











import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile, rmtree
from typing import Generator

import datasets.config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.filelock import logger as fl_logger
from datasets.utils.info_utils import VerificationMode
from datasets.utils.logging import ERROR, get_logger


lowerCamelCase_		  =						get_logger(__name__)
def   lowerCamelCase      (		a_			)			->    Tuple:
							return TestCommand(
							    args.dataset				,		args.name				,		args.cache_dir				,		args.data_dir				,		args.all_configs				,		args.save_info or args.save_infos				,		args.ignore_verifications				,		args.force_redownload				,		args.clear_cache				,		)




class 							a_				(		a_	):


							'''simple docstring'''






							__a:			Any									=					False  # to tell pytest it's not a test class

							@staticmethod
							def   _lowercase (	lowercase_     )      ->      Dict:
														'''simple docstring'''

														lowerCAmelCase_       		=  parser.add_parser('test'    ,    help='Test dataset implementation.'     )
														test_parser.add_argument('--name'    ,    type=lowercase_    ,    default=lowercase_    ,    help='Dataset processing name'     )
														test_parser.add_argument(
														    '--cache_dir'    ,    type=lowercase_    ,    default=lowercase_    ,    help='Cache directory where the datasets are stored.'    ,    )
														test_parser.add_argument(
														    '--data_dir'    ,    type=lowercase_    ,    default=lowercase_    ,    help='Can be used to specify a manual directory to get the files from.'    ,    )
														test_parser.add_argument('--all_configs'    ,    action='store_true'    ,    help='Test all dataset configurations'     )
														test_parser.add_argument(
														    '--save_info'    ,    action='store_true'    ,    help='Save the dataset infos in the dataset card (README.md)'     )
														test_parser.add_argument(
														    '--ignore_verifications'    ,    action='store_true'    ,    help='Run the test without checksums and splits checks.'    ,    )
														test_parser.add_argument('--force_redownload'    ,    action='store_true'    ,    help='Force dataset redownload'     )
														test_parser.add_argument(
														    '--clear_cache'    ,    action='store_true'    ,    help='Remove downloaded files and cached datasets after each config test'    ,    )
														# aliases
														test_parser.add_argument('--save_infos'    ,    action='store_true'    ,    help='alias to save_info'     )
														test_parser.add_argument('dataset'    ,    type=lowercase_    ,    help='Name of the dataset to download'     )
														test_parser.set_defaults(func=_test_command_factory     )

							def __init__(	self    ,    lowercase_    ,    lowercase_    ,    lowercase_    ,    lowercase_    ,    lowercase_    ,    lowercase_    ,    lowercase_    ,    lowercase_    ,    lowercase_    ,    )      ->      Union[str, Any]:
														'''simple docstring'''

														lowerCAmelCase_       		=  dataset
														lowerCAmelCase_       		=  name
														lowerCAmelCase_       		=  cache_dir
														lowerCAmelCase_       		=  data_dir
														lowerCAmelCase_       		=  all_configs
														lowerCAmelCase_       		=  save_infos
														lowerCAmelCase_       		=  ignore_verifications
														lowerCAmelCase_       		=  force_redownload
														lowerCAmelCase_       		=  clear_cache
														if clear_cache and not cache_dir:
																					print(
																					    'When --clear_cache is used, specifying a cache directory is mandatory.\n'
																					    'The \'download\' folder of the cache directory and the dataset builder cache will be deleted after each configuration test.\n'
																					    'Please provide a --cache_dir that will be used to test the dataset script.'     )
																					exit(1     )
														if save_infos:
																					lowerCAmelCase_       		=  True






							def   _lowercase (	self     )      ->      Dict:
														'''simple docstring'''

														fl_logger().setLevel(lowercase_     )
														if self._name is not None and self._all_configs:
																					print('Both parameters `config` and `all_configs` can\'t be used at once.'     )
																					exit(1     )
														lowerCAmelCase_		,     lowerCAmelCase_       		=  self._dataset, self._name
														lowerCAmelCase_       		=  dataset_module_factory(lowercase_     )
														lowerCAmelCase_       		=  import_main_class(module.module_path     )
														lowerCAmelCase_       		=  len(builder_cls.BUILDER_CONFIGS     ) if self._all_configs and builder_cls.BUILDER_CONFIGS else 1

														def get_builders() -> Generator[DatasetBuilder, None, None]:
																					if self._all_configs and builder_cls.BUILDER_CONFIGS:
																												for i, config in enumerate(builder_cls.BUILDER_CONFIGS     ):
																																			if "config_name" in module.builder_kwargs:
																																										yield builder_cls(
																																										    cache_dir=self._cache_dir    ,    data_dir=self._data_dir    ,    **module.builder_kwargs    ,    )
																																			else:
																																										yield builder_cls(
																																										    config_name=config.name    ,    cache_dir=self._cache_dir    ,    data_dir=self._data_dir    ,    **module.builder_kwargs    ,    )
																					else:
																												if "config_name" in module.builder_kwargs:
																																			yield builder_cls(cache_dir=self._cache_dir    ,    data_dir=self._data_dir    ,    **module.builder_kwargs     )
																												else:
																																			yield builder_cls(
																																			    config_name=lowercase_    ,    cache_dir=self._cache_dir    ,    data_dir=self._data_dir    ,    **module.builder_kwargs    ,    )

														for j, builder in enumerate(get_builders()     ):
																					print(f'''Testing builder \'{builder.config.name}\' ({j + 1}/{n_builders})'''     )
																					lowerCAmelCase_       		=  os.path.exists(
																					    os.path.join(builder.get_imported_module_dir()    ,    datasets.config.DATASETDICT_INFOS_FILENAME     )     )  # record checksums only if we need to update a (deprecated) dataset_infos.json
																					builder.download_and_prepare(
																					    download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
																					    if not self._force_redownload
																					    else DownloadMode.FORCE_REDOWNLOAD    ,    verification_mode=VerificationMode.NO_CHECKS
																					    if self._ignore_verifications
																					    else VerificationMode.ALL_CHECKS    ,    try_from_hf_gcs=lowercase_    ,    )
																					builder.as_dataset()
																					if self._save_infos:
																												builder._save_infos()

																					# If save_infos=True, the dataset card (README.md) is created next to the loaded module file.
																					# The dataset_infos are saved in the YAML part of the README.md

																					# Let's move it to the original directory of the dataset script, to allow the user to
																					# upload them on S3 at the same time afterwards.
																					if self._save_infos:
																												lowerCAmelCase_       		=  os.path.join(builder_cls.get_imported_module_dir()    ,    'README.md'     )
																												lowerCAmelCase_       		=  Path(lowercase_     ).name + '.py'
																												lowerCAmelCase_       		=  os.path.join(lowercase_    ,    lowercase_     )
																												if os.path.isfile(lowercase_     ):
																																			lowerCAmelCase_       		=  os.path.dirname(lowercase_     )
																												elif os.path.isfile(lowercase_     ):
																																			lowerCAmelCase_       		=  path
																												elif os.path.isdir(lowercase_     ):  # for local directories containing only data files
																																			lowerCAmelCase_       		=  path
																												else:  # in case of a remote dataset
																																			lowerCAmelCase_       		=  None
																																			print(f'''Dataset card saved at {dataset_readme_path}'''     )

																												# Move dataset_info back to the user
																												if dataset_dir is not None:
																																			lowerCAmelCase_       		=  os.path.join(lowercase_    ,    'README.md'     )
																																			copyfile(lowercase_    ,    lowercase_     )
																																			print(f'''Dataset card saved at {user_dataset_readme_path}'''     )

            # If clear_cache=True, the download folder and the dataset builder cache directory are deleted
																					if self._clear_cache:
																												if os.path.isdir(builder._cache_dir     ):
																																			logger.warning(f'''Clearing cache at {builder._cache_dir}'''     )
																																			rmtree(builder._cache_dir     )
																												lowerCAmelCase_       		=  os.path.join(self._cache_dir    ,    datasets.config.DOWNLOADED_DATASETS_DIR     )
																												if os.path.isdir(lowercase_     ):
																																			logger.warning(f'''Clearing cache at {download_dir}'''     )
																																			rmtree(lowercase_     )

														print('Test successful.'     )



