






"""simple docstring"""


from __future__ import annotations

import copy
import os
import tempfile
from importlib import import_module
from math import isnan

from transformers import is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import _tf_gpu_memory_limit, require_tf, slow

from ..test_modeling_tf_common import ids_tensor


if is_tf_available():
		import numpy as np
		import tensorflow as tf

		from transformers import (
		    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
		    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
		    TF_MODEL_FOR_MASKED_LM_MAPPING,
		    TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
		    TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
		    TF_MODEL_FOR_PRETRAINING_MAPPING,
		    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
		    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
		    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
		    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
		    TFSharedEmbeddings,
		)

		if _tf_gpu_memory_limit is not None:
				__SCREAMING_SNAKE_CASE      =      tf.config.list_physical_devices('GPU')
				for gpu in gpus:
						# Restrict TensorFlow to only allocate x GB of memory on the GPUs
						try:
								tf.config.set_logical_device_configuration(
								    gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)]
								)
								__SCREAMING_SNAKE_CASE      =      tf.config.list_logical_devices('GPU')
								print('Logical GPUs', logical_gpus)
						except RuntimeError as e:
								# Virtual devices must be set before GPUs have been initialized
								print(e)




@require_tf
class 	__UpperCamelCase    :
					lowercase_						:							Optional[int]			=     None
					lowercase_						:							str			=     ()
					lowercase_						:							Tuple			=     ()
					lowercase_						:							Union[str, Any]			=     True
					lowercase_						:							Tuple			=     True
					lowercase_						:							int			=     True
					lowercase_						:							Optional[Any]			=     False
					def 					UpperCAmelCase__   (       self       :  Dict    ,   UpperCAmelCase       :  Any    ,   UpperCAmelCase       :  List[Any]    ,   UpperCAmelCase       :  str=False      )  ->					dict:
											lowerCAmelCase      :str				  = copy.deepcopy(UpperCAmelCase      )

											if model_class in get_values(UpperCAmelCase      ):
																	lowerCAmelCase      :List[Any]				  = {
																	    k: tf.tile(tf.expand_dims(UpperCAmelCase    ,   1      )    ,   (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)      )
																	    if isinstance(UpperCAmelCase    ,   tf.Tensor      ) and v.ndim > 0
																	    else v
																	    for k, v in inputs_dict.items()
																	}

											if return_labels:
																	if model_class in get_values(UpperCAmelCase      ):
																							lowerCAmelCase      :Any				  = tf.ones(self.model_tester.batch_size    ,   dtype=tf.intaa      )
																	elif model_class in get_values(UpperCAmelCase      ):
																							lowerCAmelCase      :Any				  = tf.zeros(self.model_tester.batch_size    ,   dtype=tf.intaa      )
																							lowerCAmelCase      :List[Any]				  = tf.zeros(self.model_tester.batch_size    ,   dtype=tf.intaa      )
																	elif model_class in [
																	    *get_values(UpperCAmelCase      ),
																	    *get_values(UpperCAmelCase      ),
																	]:
																							lowerCAmelCase      :List[Any]				  = tf.zeros(self.model_tester.batch_size    ,   dtype=tf.intaa      )
																	elif model_class in get_values(UpperCAmelCase      ):
																							lowerCAmelCase      :Tuple				  = tf.zeros(self.model_tester.batch_size    ,   dtype=tf.intaa      )
																	elif model_class in [
																	    *get_values(UpperCAmelCase      ),
																	    *get_values(UpperCAmelCase      ),
																	    *get_values(UpperCAmelCase      ),
																	    *get_values(UpperCAmelCase      ),
																	    *get_values(UpperCAmelCase      ),
																	]:
																							lowerCAmelCase      :List[str]				  = tf.zeros(
																							    (self.model_tester.batch_size, self.model_tester.seq_length)    ,   dtype=tf.intaa      )
											return inputs_dict
					@slow
					def 					UpperCAmelCase__   (       self       :  Tuple      )  ->					Optional[Any]:
											lowerCAmelCase  ,   lowerCAmelCase      :Dict				  = self.model_tester.prepare_config_and_inputs_for_common()
											for model_class in self.all_model_classes[:2]:
																	lowerCAmelCase      :Any				  = self._prepare_for_class(UpperCAmelCase    ,   UpperCAmelCase      )
																	lowerCAmelCase      :Optional[int]				  = model_class(UpperCAmelCase      )

																	@tf.function
																	def run_in_graph_mode():
																							return model(UpperCAmelCase      )

																	lowerCAmelCase      :List[str]				  = run_in_graph_mode()
																	self.assertIsNotNone(UpperCAmelCase      )
					@slow
					def 					UpperCAmelCase__   (       self       :  Tuple      )  ->					Union[str, Any]:
											lowerCAmelCase  ,   lowerCAmelCase      :List[Any]				  = self.model_tester.prepare_config_and_inputs_for_common()
											for model_class in self.all_model_classes[:2]:
																	lowerCAmelCase      :int				  = self._prepare_for_class(UpperCAmelCase    ,   UpperCAmelCase      )
																	lowerCAmelCase      :Any				  = model_class(UpperCAmelCase      )

																	@tf.function(experimental_compile=UpperCAmelCase      )
																	def run_in_graph_mode():
																							return model(UpperCAmelCase      )

																	lowerCAmelCase      :Dict				  = run_in_graph_mode()
																	self.assertIsNotNone(UpperCAmelCase      )
					@slow
					def 					UpperCAmelCase__   (       self       :  int      )  ->					Dict:
											# This is a copy of the test_keras_fit method, but we use XLA compilation instead of eager
											lowerCAmelCase  ,   lowerCAmelCase      :List[str]				  = self.model_tester.prepare_config_and_inputs_for_common()
											for model_class in self.all_model_classes[:2]:
																	lowerCAmelCase      :Optional[Any]				  = model_class(UpperCAmelCase      )
																	if getattr(UpperCAmelCase    ,   'hf_compute_loss'    ,   UpperCAmelCase      ):
																							# Test that model correctly compute the loss with kwargs
																							lowerCAmelCase      :Tuple				  = self._prepare_for_class(inputs_dict.copy()    ,   UpperCAmelCase    ,   return_labels=UpperCAmelCase      )
																							# Is there a better way to remove these decoder inputs?
																							lowerCAmelCase      :Dict				  = {
																							    key: val
																							    for key, val in prepared_for_class.items()
																							    if key not in ('head_mask', 'decoder_head_mask', 'cross_attn_head_mask', 'decoder_input_ids')
																							}

																							lowerCAmelCase      :List[str]				  = {
																							    'labels',
																							    'label',
																							    'label_ids',
																							    'start_positions',
																							    'start_position',
																							    'end_positions',
																							    'end_position',
																							    'next_sentence_label',
																							}
																							lowerCAmelCase      :Dict				  = possible_label_cols.intersection(set(UpperCAmelCase      )      )
																							self.assertGreater(len(UpperCAmelCase      )    ,   0    ,   msg='No matching label names found!'      )
																							lowerCAmelCase      :Optional[int]				  = {key: val for key, val in prepared_for_class.items() if key in label_names}
																							lowerCAmelCase      :List[Any]				  = {key: val for key, val in prepared_for_class.items() if key not in label_names}
																							self.assertGreater(len(UpperCAmelCase      )    ,   0      )

																							# Make sure it works with XLA!
																							model.compile(optimizer=tf.keras.optimizers.SGD(0.0      )    ,   jit_compile=UpperCAmelCase      )
																							# Make sure the model fits without crashing regardless of where we pass the labels
																							lowerCAmelCase      :Optional[int]				  = model.fit(
																							    UpperCAmelCase    ,   validation_data=UpperCAmelCase    ,   steps_per_epoch=1    ,   validation_steps=1    ,   shuffle=UpperCAmelCase    ,   verbose=0    ,   )
																							lowerCAmelCase      :Any				  = history.history['loss'][0]
																							self.assertTrue(not isnan(UpperCAmelCase      )      )
																							lowerCAmelCase      :Any				  = history.history['val_loss'][0]
																							self.assertTrue(not isnan(UpperCAmelCase      )      )

																							# Now test it with separate labels, to make sure that path works in XLA too.
																							lowerCAmelCase      :Any				  = model_class(UpperCAmelCase      )
																							model.compile(optimizer=tf.keras.optimizers.SGD(0.0      )    ,   jit_compile=UpperCAmelCase      )
																							lowerCAmelCase      :Optional[Any]				  = model.fit(
																							    UpperCAmelCase    ,   UpperCAmelCase    ,   validation_data=(inputs_minus_labels, labels)    ,   steps_per_epoch=1    ,   validation_steps=1    ,   shuffle=UpperCAmelCase    ,   verbose=0    ,   )

																							lowerCAmelCase      :List[str]				  = history.history['loss'][0]
																							self.assertTrue(not isnan(UpperCAmelCase      )      )
																							lowerCAmelCase      :List[str]				  = history.history['val_loss'][0]
																							self.assertTrue(not isnan(UpperCAmelCase      )      )
					@slow
					def 					UpperCAmelCase__   (       self       :  Dict      )  ->					Optional[Any]:
											lowerCAmelCase  ,   lowerCAmelCase      :Union[str, Any]				  = self.model_tester.prepare_config_and_inputs_for_common()
											lowerCAmelCase      :Union[str, Any]				  = True
											lowerCAmelCase      :List[Any]				  = True

											if hasattr(UpperCAmelCase    ,   'use_cache'      ):
																	lowerCAmelCase      :Union[str, Any]				  = True

											lowerCAmelCase      :Optional[Any]				  = getattr(self.model_tester    ,   'encoder_seq_length'    ,   self.model_tester.seq_length      )
											lowerCAmelCase      :List[str]				  = getattr(self.model_tester    ,   'key_length'    ,   UpperCAmelCase      )

											for model_class in self.all_model_classes[:2]:
																	lowerCAmelCase      :List[str]				  = self._prepare_for_class(UpperCAmelCase    ,   UpperCAmelCase      )
																	lowerCAmelCase      :Dict				  = model_class(UpperCAmelCase      )
																	model.build()
																	lowerCAmelCase      :Optional[Any]				  = len(model(UpperCAmelCase      )      )

																	for key in list(class_inputs_dict.keys()      ):
																							# Remove keys not in the serving signature, as the SavedModel will not be compiled to deal with them
																							if key not in model.input_signature:
																													del class_inputs_dict[key]
																							# Check it's a tensor, in case the inputs dict has some bools in it too
																							elif isinstance(class_inputs_dict[key]    ,   tf.Tensor      ) and class_inputs_dict[key].dtype.is_integer:
																													lowerCAmelCase      :List[str]				  = tf.cast(class_inputs_dict[key]    ,   tf.intaa      )

																	if set(class_inputs_dict.keys()      ) != set(model.input_signature.keys()      ):
																							continue  # Some models have inputs that the preparation functions don't create, we skip those

																	with tempfile.TemporaryDirectory() as tmpdirname:
																							model.save_pretrained(UpperCAmelCase    ,   saved_model=UpperCAmelCase      )
																							lowerCAmelCase      :int				  = os.path.join(UpperCAmelCase    ,   'saved_model'    ,   '1'      )
																							lowerCAmelCase      :Optional[int]				  = tf.keras.models.load_model(UpperCAmelCase      )
																							lowerCAmelCase      :List[Any]				  = model(UpperCAmelCase      )

																							if self.is_encoder_decoder:
																													lowerCAmelCase      :Tuple				  = outputs['encoder_hidden_states']
																													lowerCAmelCase      :Union[str, Any]				  = outputs['encoder_attentions']
																							else:
																													lowerCAmelCase      :Dict				  = outputs['hidden_states']
																													lowerCAmelCase      :Any				  = outputs['attentions']

																							self.assertEqual(len(UpperCAmelCase      )    ,   UpperCAmelCase      )

																							lowerCAmelCase      :List[Any]				  = getattr(
																							    self.model_tester    ,   'expected_num_hidden_layers'    ,   self.model_tester.num_hidden_layers + 1      )

																							self.assertEqual(len(UpperCAmelCase      )    ,   UpperCAmelCase      )
																							self.assertListEqual(
																							    list(output_hidden_states[0].shape[-2:]      )    ,   [self.model_tester.seq_length, self.model_tester.hidden_size]    ,   )

																							self.assertEqual(len(UpperCAmelCase      )    ,   self.model_tester.num_hidden_layers      )
																							self.assertListEqual(
																							    list(output_attentions[0].shape[-3:]      )    ,   [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]    ,   )
					@slow
					def 					UpperCAmelCase__   (       self       :  Any      )  ->					Dict:
											tf.keras.mixed_precision.set_global_policy('mixed_float16'      )

											# try/finally block to ensure subsequent tests run in float32
											try:
																	lowerCAmelCase  ,   lowerCAmelCase      :Any				  = self.model_tester.prepare_config_and_inputs_for_common()
																	for model_class in self.all_model_classes[:2]:
																							lowerCAmelCase      :List[Any]				  = self._prepare_for_class(UpperCAmelCase    ,   UpperCAmelCase      )
																							lowerCAmelCase      :Union[str, Any]				  = model_class(UpperCAmelCase      )
																							lowerCAmelCase      :Optional[int]				  = model(UpperCAmelCase      )

																							self.assertIsNotNone(UpperCAmelCase      )
											finally:
																	tf.keras.mixed_precision.set_global_policy('float32'      )
					@slow
					def 					UpperCAmelCase__   (       self       :  str      )  ->					Union[str, Any]:
											lowerCAmelCase  ,   lowerCAmelCase      :List[str]				  = self.model_tester.prepare_config_and_inputs_for_common()
											# head_mask and decoder_head_mask has different shapes than other input args
											if "head_mask" in inputs_dict:
																	del inputs_dict["head_mask"]
											if "decoder_head_mask" in inputs_dict:
																	del inputs_dict["decoder_head_mask"]
											if "cross_attn_head_mask" in inputs_dict:
																	del inputs_dict["cross_attn_head_mask"]
											lowerCAmelCase      :Dict				  = {
											    module_member
											    for model_class in self.all_model_classes
											    for module in (import_module(model_class.__module__      ),)
											    for module_member_name in dir(UpperCAmelCase      )
											    if module_member_name.endswith('MainLayer'      )
											    for module_member in (getattr(UpperCAmelCase    ,   UpperCAmelCase      ),)
											    if isinstance(UpperCAmelCase    ,   UpperCAmelCase      )
											    and tf.keras.layers.Layer in module_member.__bases__
											    and getattr(UpperCAmelCase    ,   '_keras_serializable'    ,   UpperCAmelCase      )
											}

											for main_layer_class in tf_main_layer_classes:
																	# T5MainLayer needs an embed_tokens parameter when called without the inputs_embeds parameter
																	if "T5" in main_layer_class.__name__:
																							# Take the same values than in TFT5ModelTester for this shared layer
																							lowerCAmelCase      :Union[str, Any]				  = TFSharedEmbeddings(self.model_tester.vocab_size    ,   self.model_tester.hidden_size    ,   name='shared'      )
																							lowerCAmelCase      :List[str]				  = False
																							lowerCAmelCase      :Tuple				  = main_layer_class(UpperCAmelCase    ,   embed_tokens=UpperCAmelCase      )
																	else:
																							lowerCAmelCase      :int				  = main_layer_class(UpperCAmelCase      )

																	lowerCAmelCase      :Optional[int]				  = {
																	    name: tf.keras.Input(tensor.shape[1:]    ,   dtype=tensor.dtype      ) for name, tensor in inputs_dict.items()
																	}

																	if hasattr(self.model_tester    ,   'num_labels'      ):
																							lowerCAmelCase      :Optional[int]				  = self.model_tester.num_labels
																	else:
																							lowerCAmelCase      :Any				  = 2

																	lowerCAmelCase      :str				  = tf.data.Dataset.from_tensor_slices(
																	    (inputs_dict, np.ones((self.model_tester.batch_size, self.model_tester.seq_length, num_labels, 1)      ))      ).batch(1      )

																	lowerCAmelCase      :str				  = main_layer(UpperCAmelCase      )[0]
																	lowerCAmelCase      :Optional[int]				  = tf.keras.layers.Dense(UpperCAmelCase    ,   activation='softmax'    ,   name='outputs'      )(UpperCAmelCase      )
																	lowerCAmelCase      :Tuple				  = tf.keras.models.Model(inputs=UpperCAmelCase    ,   outputs=[outputs]      )

																	model.compile(loss='binary_crossentropy'    ,   optimizer='adam'    ,   metrics=['binary_accuracy']      )
																	model.fit(UpperCAmelCase    ,   epochs=1      )

																	with tempfile.TemporaryDirectory() as tmpdirname:
																							lowerCAmelCase      :Optional[Any]				  = os.path.join(UpperCAmelCase    ,   'keras_model.h5'      )
																							model.save(UpperCAmelCase      )
																							if "T5" in main_layer_class.__name__:
																													lowerCAmelCase      :Dict				  = tf.keras.models.load_model(
																													    UpperCAmelCase    ,   custom_objects={
																													        main_layer_class.__name__: main_layer_class,
																													        'TFSharedEmbeddings': TFSharedEmbeddings,
																													    }    ,   )
																							else:
																													lowerCAmelCase      :str				  = tf.keras.models.load_model(
																													    UpperCAmelCase    ,   custom_objects={main_layer_class.__name__: main_layer_class}      )
																							assert isinstance(UpperCAmelCase    ,   tf.keras.Model      )
																							model(UpperCAmelCase      )
					@slow
					def 					UpperCAmelCase__   (       self       :  str      )  ->					List[Any]:
											lowerCAmelCase  ,   lowerCAmelCase      :Dict				  = self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes[:2]:
																	lowerCAmelCase      :Tuple				  = model_class(UpperCAmelCase      )

																	lowerCAmelCase      :int				  = copy.deepcopy(UpperCAmelCase      )

																	if not self.is_encoder_decoder:
																							lowerCAmelCase      :List[Any]				  = inputs['input_ids']
																							del inputs["input_ids"]
																	else:
																							lowerCAmelCase      :Dict				  = inputs['input_ids']
																							lowerCAmelCase      :Any				  = inputs.get('decoder_input_ids'    ,   UpperCAmelCase      )
																							del inputs["input_ids"]
																							inputs.pop('decoder_input_ids'    ,   UpperCAmelCase      )

																	if not self.is_encoder_decoder:
																							lowerCAmelCase      :Any				  = model.get_input_embeddings()(UpperCAmelCase      )
																	else:
																							lowerCAmelCase      :Optional[int]				  = model.get_input_embeddings()(UpperCAmelCase      )
																							lowerCAmelCase      :Any				  = model.get_input_embeddings()(UpperCAmelCase      )

																	lowerCAmelCase      :str				  = self._prepare_for_class(UpperCAmelCase    ,   UpperCAmelCase      )

																	@tf.function
																	def run_in_graph_mode():
																							return model(UpperCAmelCase      )

																	lowerCAmelCase      :Dict				  = run_in_graph_mode()
																	self.assertIsNotNone(UpperCAmelCase      )
					def 					UpperCAmelCase__   (       self       :  Dict    ,   UpperCAmelCase       :  Any    ,   UpperCAmelCase       :  Tuple      )  ->					Union[str, Any]:
											# special tokens cannot be bad tokens
											lowerCAmelCase      :Optional[Any]				  = []
											if model.config.bos_token_id is not None:
																	special_tokens.append(model.config.bos_token_id      )
											if model.config.pad_token_id is not None:
																	special_tokens.append(model.config.pad_token_id      )
											if model.config.eos_token_id is not None:
																	special_tokens.append(model.config.eos_token_id      )

											# create random bad tokens that are not special tokens
											lowerCAmelCase      :Any				  = []
											while len(UpperCAmelCase      ) < num_bad_tokens:
																	lowerCAmelCase      :Tuple				  = tf.squeeze(ids_tensor((1, 1)    ,   self.model_tester.vocab_size      )    ,   0      ).numpy()[0]
																	if token not in special_tokens:
																							bad_tokens.append(UpperCAmelCase      )
											return bad_tokens
					def 					UpperCAmelCase__   (       self       :  List[Any]    ,   UpperCAmelCase       :  Dict      )  ->					Tuple:
											for token_id in output_ids[0].numpy().tolist():
																	self.assertGreaterEqual(UpperCAmelCase    ,   0      )
																	self.assertLess(UpperCAmelCase    ,   self.model_tester.vocab_size      )
					def 					UpperCAmelCase__   (       self       :  Any    ,   UpperCAmelCase       :  Union[str, Any]    ,   UpperCAmelCase       :  str      )  ->					Any:
											# for all bad word tokens
											for bad_word_ids in bad_words_ids:
																	# for all slices in batch
																	for generated_ids_slice in generated_ids:
																							# for all word idx
																							for i in range(len(UpperCAmelCase      )    ,   len(UpperCAmelCase      )      ):
																													# if tokens match
																													if generated_ids_slice[i - len(UpperCAmelCase      ) : i] == bad_word_ids:
																																			return True
											return False







"""simple docstring"""


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


__SCREAMING_SNAKE_CASE      =      get_logger(__name__)


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						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 	__UpperCamelCase    (    UpperCamelCase	):
					lowercase_						:							str			=     False  # to tell pytest it's not a test class
					@staticmethod
					def 					UpperCAmelCase__   (       UpperCAmelCase       :  ArgumentParser      )  ->					Optional[int]:
											lowerCAmelCase      :Union[str, Any]				  = parser.add_parser('test'    ,   help='Test dataset implementation.'      )
											test_parser.add_argument('--name'    ,   type=UpperCAmelCase    ,   default=UpperCAmelCase    ,   help='Dataset processing name'      )
											test_parser.add_argument(
											    '--cache_dir'    ,   type=UpperCAmelCase    ,   default=UpperCAmelCase    ,   help='Cache directory where the datasets are stored.'    ,   )
											test_parser.add_argument(
											    '--data_dir'    ,   type=UpperCAmelCase    ,   default=UpperCAmelCase    ,   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=UpperCAmelCase    ,   help='Name of the dataset to download'      )
											test_parser.set_defaults(func=_test_command_factory      )
					def __init__(       self       :  List[Any]    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  bool    ,   UpperCAmelCase       :  bool    ,   UpperCAmelCase       :  bool    ,   UpperCAmelCase       :  bool    ,   UpperCAmelCase       :  bool    ,   )  ->					Any:
											lowerCAmelCase      :int				  = dataset
											lowerCAmelCase      :Tuple				  = name
											lowerCAmelCase      :Tuple				  = cache_dir
											lowerCAmelCase      :List[Any]				  = data_dir
											lowerCAmelCase      :int				  = all_configs
											lowerCAmelCase      :Dict				  = save_infos
											lowerCAmelCase      :Union[str, Any]				  = ignore_verifications
											lowerCAmelCase      :int				  = force_redownload
											lowerCAmelCase      :Union[str, Any]				  = 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      :List[str]				  = True
					def 					UpperCAmelCase__   (       self       :  Optional[Any]      )  ->					int:
											fl_logger().setLevel(UpperCAmelCase      )
											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      :Dict				  = self._dataset, self._name
											lowerCAmelCase      :int				  = dataset_module_factory(UpperCAmelCase      )
											lowerCAmelCase      :int				  = import_main_class(module.module_path      )
											lowerCAmelCase      :Dict				  = 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=UpperCAmelCase    ,   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      :int				  = 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=UpperCAmelCase    ,   )
																	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      :Optional[Any]				  = os.path.join(builder_cls.get_imported_module_dir()    ,   'README.md'      )
																							lowerCAmelCase      :List[str]				  = Path(UpperCAmelCase      ).name + '.py'
																							lowerCAmelCase      :Dict				  = os.path.join(UpperCAmelCase    ,   UpperCAmelCase      )
																							if os.path.isfile(UpperCAmelCase      ):
																													lowerCAmelCase      :Any				  = os.path.dirname(UpperCAmelCase      )
																							elif os.path.isfile(UpperCAmelCase      ):
																													lowerCAmelCase      :Any				  = path
																							elif os.path.isdir(UpperCAmelCase      ):  # for local directories containing only data files
																													lowerCAmelCase      :Dict				  = path
																							else:  # in case of a remote dataset
																													lowerCAmelCase      :int				  = None
																													print(f"""Dataset card saved at {dataset_readme_path}"""      )

																							# Move dataset_info back to the user
																							if dataset_dir is not None:
																													lowerCAmelCase      :Any				  = os.path.join(UpperCAmelCase    ,   'README.md'      )
																													copyfile(UpperCAmelCase    ,   UpperCAmelCase      )
																													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      :str				  = os.path.join(self._cache_dir    ,   datasets.config.DOWNLOADED_DATASETS_DIR      )
																							if os.path.isdir(UpperCAmelCase      ):
																													logger.warning(f"""Clearing cache at {download_dir}"""      )
																													rmtree(UpperCAmelCase      )

											print('Test successful.'      )