



"""simple docstring"""




import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


lowerCAmelCase__		:					List[Any]							=logging.getLogger(__name__)

@dataclass(frozen=__UpperCamelCase	)
class        UpperCAmelCase_  :

						'''simple docstring'''




						UpperCamelCase__      :			str
						UpperCamelCase__      :			str
						UpperCamelCase__      :			Optional[str]      =  None
						UpperCamelCase__      :			Optional[str]      =  None
						UpperCamelCase__      :			Optional[str]      =  None







@dataclass(frozen=__UpperCamelCase	)
class        UpperCAmelCase_  :

						'''simple docstring'''




						UpperCamelCase__      :			List[int]
						UpperCamelCase__      :			Optional[List[int]]      =  None
						UpperCamelCase__      :			Optional[List[int]]      =  None
						UpperCamelCase__      :			Optional[Union[int, float]]      =  None
						UpperCamelCase__      :			Optional[int]      =  None


if is_torch_available():
			import torch
			from torch.utils.data import Dataset

			class        UpperCAmelCase_  (       __UpperCamelCase	):

									'''simple docstring'''




									UpperCamelCase__      :			List[InputFeatures]






									def __init__(   self				,							_A				,							_A				,							_A				,							_A = None				,							_A=False				,							_A = False				,							):







																'''simple docstring'''

																__SCREAMING_SNAKE_CASE									= hans_processors[task]()

																__SCREAMING_SNAKE_CASE									= os.path.join(
																    _A				,							'cached_{}_{}_{}_{}'.format(
																        'dev' if evaluate else 'train'				,							tokenizer.__class__.__name__				,							str(_A		)				,							_A				,							)				,							)
																__SCREAMING_SNAKE_CASE									= processor.get_labels()
																if tokenizer.__class__ in (
																    RobertaTokenizer,
																    RobertaTokenizerFast,
																    XLMRobertaTokenizer,
																    BartTokenizer,
																    BartTokenizerFast,
																):
																							# HACK(label indices are swapped in RoBERTa pretrained model)
																							__SCREAMING_SNAKE_CASE									= label_list[2], label_list[1]
																__SCREAMING_SNAKE_CASE									= label_list

																# Make sure only the first process in distributed training processes the dataset,
																# and the others will use the cache.
																__SCREAMING_SNAKE_CASE									= cached_features_file + """.lock"""
																with FileLock(_A		):
																							if os.path.exists(_A		) and not overwrite_cache:
																														logger.info(f"""Loading features from cached file {cached_features_file}"""		)
																														__SCREAMING_SNAKE_CASE									= torch.load(_A		)
																							else:
																														logger.info(f"""Creating features from dataset file at {data_dir}"""		)

																														__SCREAMING_SNAKE_CASE									= (
																														    processor.get_dev_examples(_A		) if evaluate else processor.get_train_examples(_A		)
																														)

																														logger.info('Training examples: %s'				,							len(_A		)		)
																														__SCREAMING_SNAKE_CASE									= hans_convert_examples_to_features(_A				,							_A				,							_A				,							_A		)
																														logger.info('Saving features into cached file %s'				,							_A		)
																														torch.save(self.features				,							_A		)






									def __len__(   self		):







																'''simple docstring'''

																return len(self.features		)






									def __getitem__(   self				,							_A		):







																'''simple docstring'''

																return self.features[i]






									def 	_A     (   self		):







																'''simple docstring'''

																return self.label_list


if is_tf_available():
			import tensorflow as tf

			class        UpperCAmelCase_  :

									'''simple docstring'''




									UpperCamelCase__      :			List[InputFeatures]






									def __init__(   self				,							_A				,							_A				,							_A				,							_A = 128				,							_A=False				,							_A = False				,							):







																'''simple docstring'''

																__SCREAMING_SNAKE_CASE									= hans_processors[task]()
																__SCREAMING_SNAKE_CASE									= processor.get_labels()
																if tokenizer.__class__ in (
																    RobertaTokenizer,
																    RobertaTokenizerFast,
																    XLMRobertaTokenizer,
																    BartTokenizer,
																    BartTokenizerFast,
																):
																							# HACK(label indices are swapped in RoBERTa pretrained model)
																							__SCREAMING_SNAKE_CASE									= label_list[2], label_list[1]
																__SCREAMING_SNAKE_CASE									= label_list

																__SCREAMING_SNAKE_CASE									= processor.get_dev_examples(_A		) if evaluate else processor.get_train_examples(_A		)
																__SCREAMING_SNAKE_CASE									= hans_convert_examples_to_features(_A				,							_A				,							_A				,							_A		)

																def gen():
																							for ex_index, ex in tqdm.tqdm(enumerate(self.features		)				,							desc='convert examples to features'		):
																														if ex_index % 10_000 == 0:
																																					logger.info('Writing example %d of %d' % (ex_index, len(_A		))		)

																														yield (
																														    {
																														        "example_id": 0,
																														        "input_ids": ex.input_ids,
																														        "attention_mask": ex.attention_mask,
																														        "token_type_ids": ex.token_type_ids,
																														    },
																														    ex.label,
																														)

																__SCREAMING_SNAKE_CASE									= tf.data.Dataset.from_generator(
																    _A				,							(
																        {
																            'example_id': tf.intaa,
																            'input_ids': tf.intaa,
																            'attention_mask': tf.intaa,
																            'token_type_ids': tf.intaa,
																        },
																        tf.intaa,
																    )				,							(
																        {
																            'example_id': tf.TensorShape([]		),
																            'input_ids': tf.TensorShape([None, None]		),
																            'attention_mask': tf.TensorShape([None, None]		),
																            'token_type_ids': tf.TensorShape([None, None]		),
																        },
																        tf.TensorShape([]		),
																    )				,							)






									def 	_A     (   self		):







																'''simple docstring'''

																return self.dataset






									def __len__(   self		):







																'''simple docstring'''

																return len(self.features		)






									def __getitem__(   self				,							_A		):







																'''simple docstring'''

																return self.features[i]






									def 	_A     (   self		):







																'''simple docstring'''

																return self.label_list

class        UpperCAmelCase_  (       __UpperCamelCase	):

						'''simple docstring'''




						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													return self._create_examples(self._read_tsv(os.path.join(_A				,							'heuristics_train_set.txt'		)		)				,							'train'		)






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													return self._create_examples(self._read_tsv(os.path.join(_A				,							'heuristics_evaluation_set.txt'		)		)				,							'dev'		)






						def 	_A     (   self		):







													'''simple docstring'''

													return ["contradiction", "entailment", "neutral"]






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= []
													for i, line in enumerate(_A		):
																				if i == 0:
																											continue
																				__SCREAMING_SNAKE_CASE									= """%s-%s""" % (set_type, line[0])
																				__SCREAMING_SNAKE_CASE									= line[5]
																				__SCREAMING_SNAKE_CASE									= line[6]
																				__SCREAMING_SNAKE_CASE									= line[7][2:] if line[7].startswith('ex'		) else line[7]
																				__SCREAMING_SNAKE_CASE									= line[0]
																				examples.append(InputExample(guid=_A				,							text_a=_A				,							text_b=_A				,							label=_A				,							pairID=_A		)		)
													return examples







def      __lowercase       (			a__							,       a__							,       a__							,       a__							,       )    ->			Union[str, Any]:
							__SCREAMING_SNAKE_CASE									= {label: i for i, label in enumerate(lowercase__       )}

							__SCREAMING_SNAKE_CASE									= []
							for ex_index, example in tqdm.tqdm(enumerate(lowercase__       )							,       desc='convert examples to features'       ):
														if ex_index % 1_00_00 == 0:
																					logger.info('Writing example %d' % (ex_index)       )

														__SCREAMING_SNAKE_CASE									= tokenizer(
														    example.text_a							,       example.text_b							,       add_special_tokens=lowercase__							,       max_length=lowercase__							,       padding='max_length'							,       truncation=lowercase__							,       return_overflowing_tokens=lowercase__							,       )

														__SCREAMING_SNAKE_CASE									= label_map[example.label] if example.label in label_map else 0

														__SCREAMING_SNAKE_CASE									= int(example.pairID       )

														features.append(InputFeatures(**lowercase__							,       label=lowercase__							,       pairID=lowercase__       )       )

							for i, example in enumerate(examples[:5]       ):
														logger.info('*** Example ***'       )
														logger.info(f"""guid: {example}"""       )
														logger.info(f"""features: {features[i]}"""       )

							return features


lowerCAmelCase__		:					Optional[int]							={
    '''hans''': 3,
}

lowerCAmelCase__		:					Any							={
    '''hans''': HansProcessor,
}











import multiprocessing
from typing import TYPE_CHECKING, Optional, Union

from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream


if TYPE_CHECKING:
			import sqlitea

			import sqlalchemy

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




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







													'''simple docstring'''

													super().__init__(features=_A				,							cache_dir=_A				,							keep_in_memory=_A				,							**_A		)
													__SCREAMING_SNAKE_CASE									= Sql(
													    cache_dir=_A				,							features=_A				,							sql=_A				,							con=_A				,							**_A				,							)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None

													self.builder.download_and_prepare(
													    download_config=_A				,							download_mode=_A				,							verification_mode=_A				,							base_path=_A				,							)

													# Build dataset for splits
													__SCREAMING_SNAKE_CASE									= self.builder.as_dataset(
													    split='train'				,							verification_mode=_A				,							in_memory=self.keep_in_memory		)
													return dataset







class        UpperCAmelCase_  :

						'''simple docstring'''




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







													'''simple docstring'''

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

													__SCREAMING_SNAKE_CASE									= dataset
													__SCREAMING_SNAKE_CASE									= name
													__SCREAMING_SNAKE_CASE									= con
													__SCREAMING_SNAKE_CASE									= batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
													__SCREAMING_SNAKE_CASE									= num_proc
													__SCREAMING_SNAKE_CASE									= to_sql_kwargs






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('sql'				,							_A		)
													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('con'				,							_A		)
													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('index'				,							_A		)

													__SCREAMING_SNAKE_CASE									= self._write(index=_A				,							**self.to_sql_kwargs		)
													return written






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= args
													__SCREAMING_SNAKE_CASE									= {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs
													__SCREAMING_SNAKE_CASE									= query_table(
													    table=self.dataset.data				,							key=slice(_A				,							offset + self.batch_size		)				,							indices=self.dataset._indices				,							)
													__SCREAMING_SNAKE_CASE									= batch.to_pandas()
													__SCREAMING_SNAKE_CASE									= df.to_sql(self.name				,							self.con				,							index=_A				,							**_A		)
													return num_rows or len(_A		)






						def 	_A     (   self				,							_A				,							**_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= 0

													if self.num_proc is None or self.num_proc == 1:
																				for offset in logging.tqdm(
																				    range(0				,							len(self.dataset		)				,							self.batch_size		)				,							unit='ba'				,							disable=not logging.is_progress_bar_enabled()				,							desc='Creating SQL from Arrow format'				,							):
																											written += self._batch_sql((offset, index, to_sql_kwargs)		)
													else:
																				__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= len(self.dataset		), self.batch_size
																				with multiprocessing.Pool(self.num_proc		) as pool:
																											for num_rows in logging.tqdm(
																											    pool.imap(
																											        self._batch_sql				,							[(offset, index, to_sql_kwargs) for offset in range(0				,							_A				,							_A		)]				,							)				,							total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size				,							unit='ba'				,							disable=not logging.is_progress_bar_enabled()				,							desc='Creating SQL from Arrow format'				,							):
																																		written += num_rows

													return written






