






"""simple docstring"""


import csv
import dataclasses
import json
from dataclasses import dataclass
from typing import List, Optional, Union

from ...utils import is_tf_available, is_torch_available, logging


__SCREAMING_SNAKE_CASE      =      logging.get_logger(__name__)




@dataclass
class 	__UpperCamelCase    :
					lowercase_						:							str
					lowercase_						:							str
					lowercase_						:							Optional[str]			=     None
					lowercase_						:							Optional[str]			=     None
					def 					UpperCAmelCase__   (       self       :  List[Any]      )  ->					str:
											return json.dumps(dataclasses.asdict(self      )    ,   indent=2      ) + "\n"




@dataclass(frozen=UpperCamelCase	)
class 	__UpperCamelCase    :
					lowercase_						:							List[int]
					lowercase_						:							Optional[List[int]]			=     None
					lowercase_						:							Optional[List[int]]			=     None
					lowercase_						:							Optional[Union[int, float]]			=     None
					def 					UpperCAmelCase__   (       self       :  Optional[Any]      )  ->					Optional[Any]:
											return json.dumps(dataclasses.asdict(self      )      ) + "\n"




class 	__UpperCamelCase    :
					def 					UpperCAmelCase__   (       self       :  List[str]    ,   UpperCAmelCase       :  Any      )  ->					Dict:
											raise NotImplementedError()
					def 					UpperCAmelCase__   (       self       :  Dict    ,   UpperCAmelCase       :  Optional[Any]      )  ->					Tuple:
											raise NotImplementedError()
					def 					UpperCAmelCase__   (       self       :  Optional[Any]    ,   UpperCAmelCase       :  List[str]      )  ->					Dict:
											raise NotImplementedError()
					def 					UpperCAmelCase__   (       self       :  Any    ,   UpperCAmelCase       :  List[str]      )  ->					Optional[Any]:
											raise NotImplementedError()
					def 					UpperCAmelCase__   (       self       :  Optional[Any]      )  ->					Dict:
											raise NotImplementedError()
					def 					UpperCAmelCase__   (       self       :  Any    ,   UpperCAmelCase       :  Optional[int]      )  ->					str:
											if len(self.get_labels()      ) > 1:
																	lowerCAmelCase      :int				  = self.get_labels()[int(example.label      )]
											return example
					@classmethod
					def 					UpperCAmelCase__   (       cls       :  Any    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  List[Any]=None      )  ->					Optional[Any]:
											with open(UpperCAmelCase    ,   'r'    ,   encoding='utf-8-sig'      ) as f:
																	return list(csv.reader(UpperCAmelCase    ,   delimiter='\t'    ,   quotechar=UpperCAmelCase      )      )




class 	__UpperCamelCase    (    UpperCamelCase	):
					def __init__(       self       :  List[Any]    ,   UpperCAmelCase       :  Tuple=None    ,   UpperCAmelCase       :  Dict=None    ,   UpperCAmelCase       :  Union[str, Any]="classification"    ,   UpperCAmelCase       :  Union[str, Any]=False      )  ->					Any:
											lowerCAmelCase      :Optional[int]				  = [] if labels is None else labels
											lowerCAmelCase      :Tuple				  = [] if examples is None else examples
											lowerCAmelCase      :Optional[Any]				  = mode
											lowerCAmelCase      :Dict				  = verbose
					def __len__(       self       :  str      )  ->					int:
											return len(self.examples      )
					def __getitem__(       self       :  str    ,   UpperCAmelCase       :  str      )  ->					List[Any]:
											if isinstance(UpperCAmelCase    ,   UpperCAmelCase      ):
																	return SingleSentenceClassificationProcessor(labels=self.labels    ,   examples=self.examples[idx]      )
											return self.examples[idx]
					@classmethod
					def 					UpperCAmelCase__   (       cls       :  Any    ,   UpperCAmelCase       :  Optional[int]    ,   UpperCAmelCase       :  int=""    ,   UpperCAmelCase       :  str=0    ,   UpperCAmelCase       :  Optional[int]=1    ,   UpperCAmelCase       :  str=None    ,   UpperCAmelCase       :  List[Any]=False    ,   **UpperCAmelCase       :  List[Any]      )  ->					Optional[Any]:
											lowerCAmelCase      :List[str]				  = cls(**UpperCAmelCase      )
											processor.add_examples_from_csv(
											    UpperCAmelCase    ,   split_name=UpperCAmelCase    ,   column_label=UpperCAmelCase    ,   column_text=UpperCAmelCase    ,   column_id=UpperCAmelCase    ,   skip_first_row=UpperCAmelCase    ,   overwrite_labels=UpperCAmelCase    ,   overwrite_examples=UpperCAmelCase    ,   )
											return processor
					@classmethod
					def 					UpperCAmelCase__   (       cls       :  Union[str, Any]    ,   UpperCAmelCase       :  Tuple    ,   UpperCAmelCase       :  Union[str, Any]=None    ,   **UpperCAmelCase       :  Optional[int]      )  ->					str:
											lowerCAmelCase      :int				  = cls(**UpperCAmelCase      )
											processor.add_examples(UpperCAmelCase    ,   labels=UpperCAmelCase      )
											return processor
					def 					UpperCAmelCase__   (       self       :  List[Any]    ,   UpperCAmelCase       :  Optional[Any]    ,   UpperCAmelCase       :  Any=""    ,   UpperCAmelCase       :  Dict=0    ,   UpperCAmelCase       :  Any=1    ,   UpperCAmelCase       :  List[Any]=None    ,   UpperCAmelCase       :  Union[str, Any]=False    ,   UpperCAmelCase       :  List[Any]=False    ,   UpperCAmelCase       :  int=False    ,   )  ->					Tuple:
											lowerCAmelCase      :List[str]				  = self._read_tsv(UpperCAmelCase      )
											if skip_first_row:
																	lowerCAmelCase      :Tuple				  = lines[1:]
											lowerCAmelCase      :List[str]				  = []
											lowerCAmelCase      :Dict				  = []
											lowerCAmelCase      :Optional[int]				  = []
											for i, line in enumerate(UpperCAmelCase      ):
																	texts.append(line[column_text]      )
																	labels.append(line[column_label]      )
																	if column_id is not None:
																							ids.append(line[column_id]      )
																	else:
																							lowerCAmelCase      :Optional[Any]				  = f"""{split_name}-{i}""" if split_name else str(UpperCAmelCase      )
																							ids.append(UpperCAmelCase      )

											return self.add_examples(
											    UpperCAmelCase    ,   UpperCAmelCase    ,   UpperCAmelCase    ,   overwrite_labels=UpperCAmelCase    ,   overwrite_examples=UpperCAmelCase      )
					def 					UpperCAmelCase__   (       self       :  Any    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  Dict=None    ,   UpperCAmelCase       :  Dict=None    ,   UpperCAmelCase       :  Dict=False    ,   UpperCAmelCase       :  int=False      )  ->					Tuple:
											if labels is not None and len(UpperCAmelCase      ) != len(UpperCAmelCase      ):
																	raise ValueError(
																	    f"""Text and labels have mismatched lengths {len(UpperCAmelCase      )} and {len(UpperCAmelCase      )}"""      )
											if ids is not None and len(UpperCAmelCase      ) != len(UpperCAmelCase      ):
																	raise ValueError(f"""Text and ids have mismatched lengths {len(UpperCAmelCase      )} and {len(UpperCAmelCase      )}"""      )
											if ids is None:
																	lowerCAmelCase      :List[str]				  = [None] * len(UpperCAmelCase      )
											if labels is None:
																	lowerCAmelCase      :Optional[int]				  = [None] * len(UpperCAmelCase      )
											lowerCAmelCase      :int				  = []
											lowerCAmelCase      :List[Any]				  = set()
											for text_or_text_and_label, label, guid in zip(UpperCAmelCase    ,   UpperCAmelCase    ,   UpperCAmelCase      ):
																	if isinstance(UpperCAmelCase    ,   (tuple, list)      ) and label is None:
																							lowerCAmelCase  ,   lowerCAmelCase      :Optional[Any]				  = text_or_text_and_label
																	else:
																							lowerCAmelCase      :List[str]				  = text_or_text_and_label
																	added_labels.add(UpperCAmelCase      )
																	examples.append(InputExample(guid=UpperCAmelCase    ,   text_a=UpperCAmelCase    ,   text_b=UpperCAmelCase    ,   label=UpperCAmelCase      )      )

											# Update examples
											if overwrite_examples:
																	lowerCAmelCase      :List[Any]				  = examples
											else:
																	self.examples.extend(UpperCAmelCase      )

											# Update labels
											if overwrite_labels:
																	lowerCAmelCase      :Optional[int]				  = list(UpperCAmelCase      )
											else:
																	lowerCAmelCase      :int				  = list(set(self.labels      ).union(UpperCAmelCase      )      )

											return self.examples
					def 					UpperCAmelCase__   (       self       :  str    ,   UpperCAmelCase       :  Any    ,   UpperCAmelCase       :  Optional[int]=None    ,   UpperCAmelCase       :  Tuple=False    ,   UpperCAmelCase       :  Optional[int]=0    ,   UpperCAmelCase       :  Tuple=True    ,   UpperCAmelCase       :  Dict=None    ,   )  ->					Optional[Any]:
											if max_length is None:
																	lowerCAmelCase      :Optional[int]				  = tokenizer.max_len

											lowerCAmelCase      :int				  = {label: i for i, label in enumerate(self.labels      )}

											lowerCAmelCase      :int				  = []
											for ex_index, example in enumerate(self.examples      ):
																	if ex_index % 1_0000 == 0:
																							logger.info(f"""Tokenizing example {ex_index}"""      )

																	lowerCAmelCase      :Tuple				  = tokenizer.encode(
																	    example.text_a    ,   add_special_tokens=UpperCAmelCase    ,   max_length=min(UpperCAmelCase    ,   tokenizer.max_len      )    ,   )
																	all_input_ids.append(UpperCAmelCase      )

											lowerCAmelCase      :Optional[Any]				  = max(len(UpperCAmelCase      ) for input_ids in all_input_ids      )

											lowerCAmelCase      :int				  = []
											for ex_index, (input_ids, example) in enumerate(zip(UpperCAmelCase    ,   self.examples      )      ):
																	if ex_index % 1_0000 == 0:
																							logger.info(f"""Writing example {ex_index}/{len(self.examples      )}"""      )
																	# The mask has 1 for real tokens and 0 for padding tokens. Only real
																	# tokens are attended to.
																	lowerCAmelCase      :Union[str, Any]				  = [1 if mask_padding_with_zero else 0] * len(UpperCAmelCase      )

																	# Zero-pad up to the sequence length.
																	lowerCAmelCase      :str				  = batch_length - len(UpperCAmelCase      )
																	if pad_on_left:
																							lowerCAmelCase      :str				  = ([pad_token] * padding_length) + input_ids
																							lowerCAmelCase      :Optional[Any]				  = ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
																	else:
																							lowerCAmelCase      :str				  = input_ids + ([pad_token] * padding_length)
																							lowerCAmelCase      :str				  = attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)

																	if len(UpperCAmelCase      ) != batch_length:
																							raise ValueError(f"""Error with input length {len(UpperCAmelCase      )} vs {batch_length}"""      )
																	if len(UpperCAmelCase      ) != batch_length:
																							raise ValueError(f"""Error with input length {len(UpperCAmelCase      )} vs {batch_length}"""      )

																	if self.mode == "classification":
																							lowerCAmelCase      :List[str]				  = label_map[example.label]
																	elif self.mode == "regression":
																							lowerCAmelCase      :Union[str, Any]				  = float(example.label      )
																	else:
																							raise ValueError(self.mode      )

																	if ex_index < 5 and self.verbose:
																							logger.info('*** Example ***'      )
																							logger.info(f"""guid: {example.guid}"""      )
																							logger.info(f"""input_ids: {" ".join([str(UpperCAmelCase      ) for x in input_ids]      )}"""      )
																							logger.info(f"""attention_mask: {" ".join([str(UpperCAmelCase      ) for x in attention_mask]      )}"""      )
																							logger.info(f"""label: {example.label} (id = {label})"""      )

																	features.append(InputFeatures(input_ids=UpperCAmelCase    ,   attention_mask=UpperCAmelCase    ,   label=UpperCAmelCase      )      )

											if return_tensors is None:
																	return features
											elif return_tensors == "tf":
																	if not is_tf_available():
																							raise RuntimeError('return_tensors set to \'tf\' but TensorFlow 2.0 can\'t be imported'      )
																	import tensorflow as tf

																	def gen():
																							for ex in features:
																													yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)

																	lowerCAmelCase      :Optional[int]				  = tf.data.Dataset.from_generator(
																	    UpperCAmelCase    ,   ({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa)    ,   ({'input_ids': tf.TensorShape([None]      ), 'attention_mask': tf.TensorShape([None]      )}, tf.TensorShape([]      ))    ,   )
																	return dataset
											elif return_tensors == "pt":
																	if not is_torch_available():
																							raise RuntimeError('return_tensors set to \'pt\' but PyTorch can\'t be imported'      )
																	import torch
																	from torch.utils.data import TensorDataset

																	lowerCAmelCase      :str				  = torch.tensor([f.input_ids for f in features]    ,   dtype=torch.long      )
																	lowerCAmelCase      :Any				  = torch.tensor([f.attention_mask for f in features]    ,   dtype=torch.long      )
																	if self.mode == "classification":
																							lowerCAmelCase      :Dict				  = torch.tensor([f.label for f in features]    ,   dtype=torch.long      )
																	elif self.mode == "regression":
																							lowerCAmelCase      :List[Any]				  = torch.tensor([f.label for f in features]    ,   dtype=torch.float      )

																	lowerCAmelCase      :str				  = TensorDataset(UpperCAmelCase    ,   UpperCAmelCase    ,   UpperCAmelCase      )
																	return dataset
											else:
																	raise ValueError('return_tensors should be one of \'tf\' or \'pt\''      )







"""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.'      )