


import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


UpperCamelCase														=      logging.get_logger(__name__)

UpperCamelCase														=      list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCamelCase														=      tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class     _lowerCamelCase					:




       """simple docstring"""
       snake_case    =       field(
           default=lowerCamelCase_   ,				metadata={"help": "Model type selected in the list: " + ", ".join(lowerCamelCase_     )}     )
       snake_case    =       field(
           default=lowerCamelCase_   ,				metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."}     )
       snake_case    =       field(
           default=128   ,				metadata={
               "help": (
                   "The maximum total input sequence length after tokenization. Sequences longer "
                   "than this will be truncated, sequences shorter will be padded."
               )
           }   ,				)
       snake_case    =       field(
           default=128   ,				metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}   ,				)
       snake_case    =       field(
           default=64   ,				metadata={
               "help": (
                   "The maximum number of tokens for the question. Questions longer than this will "
                   "be truncated to this length."
               )
           }   ,				)
       snake_case    =       field(
           default=30   ,				metadata={
               "help": (
                   "The maximum length of an answer that can be generated. This is needed because the start "
                   "and end predictions are not conditioned on one another."
               )
           }   ,				)
       snake_case    =       field(
           default=lowerCamelCase_   ,				metadata={"help": "Overwrite the cached training and evaluation sets"}     )
       snake_case    =       field(
           default=lowerCamelCase_   ,				metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."}     )
       snake_case    =       field(
           default=0.0   ,				metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}     )
       snake_case    =       field(
           default=20   ,				metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}     )
       snake_case    =       field(
           default=0   ,				metadata={
               "help": (
                   "language id of input for language-specific xlm models (see"
                   " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
               )
           }   ,				)
       snake_case    =       field(default=1   ,				metadata={"help": "multiple threads for converting example to features"}     )






class     _lowerCamelCase					(   lowerCamelCase_     ):




       """simple docstring"""
       snake_case    =       "train"
       snake_case    =       "dev"






class     _lowerCamelCase					(   lowerCamelCase_     ):




       """simple docstring"""
       snake_case    =       42
       snake_case    =       42
       snake_case    =       42
       snake_case    =       42



       def __init__( self							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE = None							,			_SCREAMING_SNAKE_CASE = Split.train							,			_SCREAMING_SNAKE_CASE = False							,			_SCREAMING_SNAKE_CASE = None							,			_SCREAMING_SNAKE_CASE = "pt"							,			)->Union[str, Any]:




         '''simple docstring'''





         A_ :							Tuple							=   args
         A_ :							Dict							=   is_language_sensitive
         A_ :							int							=   SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
         if isinstance(snake_case__							,			snake_case__						):
           try:
             A_ :							Any							=   Split[mode]
           except KeyError:
             raise KeyError('''mode is not a valid split name'''						)
         A_ :							Any							=   mode
         # Load data features from cache or dataset file
         A_ :							Optional[Any]							=   'v2' if args.version_2_with_negative else 'v1'
         A_ :							Optional[Any]							=   os.path.join(
             cache_dir if cache_dir is not None else args.data_dir							,			F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'''							,			)

         # Make sure only the first process in distributed training processes the dataset,
         # and the others will use the cache.
         A_ :							Any							=   cached_features_file + '.lock'
         with FileLock(snake_case__						):
           if os.path.exists(snake_case__						) and not args.overwrite_cache:
             A_ :							Tuple							=   time.time()
             A_ :							List[Any]							=   torch.load(snake_case__						)

             # Legacy cache files have only features, while new cache files
             # will have dataset and examples also.
             A_ :							List[Any]							=   self.old_features['features']
             A_ :							Optional[Any]							=   self.old_features.get('''dataset'''							,			snake_case__						)
             A_ :							Dict							=   self.old_features.get('''examples'''							,			snake_case__						)
             logger.info(
                 F'''Loading features from cached file {cached_features_file} [took %.3f s]'''							,			time.time() - start						)

             if self.dataset is None or self.examples is None:
               logger.warning(
                   F'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
                   ''' future run'''						)
           else:
             if mode == Split.dev:
               A_ :							str							=   self.processor.get_dev_examples(args.data_dir						)
             else:
               A_ :							List[str]							=   self.processor.get_train_examples(args.data_dir						)

             A_ :							List[str]							=   squad_convert_examples_to_features(
                 examples=self.examples							,			tokenizer=snake_case__							,			max_seq_length=args.max_seq_length							,			doc_stride=args.doc_stride							,			max_query_length=args.max_query_length							,			is_training=mode == Split.train							,			threads=args.threads							,			return_dataset=snake_case__							,			)

             A_ :							Optional[int]							=   time.time()
             torch.save(
                 {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}							,			snake_case__							,			)
             # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
             logger.info(
                 F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''						)



       def __len__( self						)->Optional[Any]:




         '''simple docstring'''





         return len(self.features						)







       def __getitem__( self							,			_SCREAMING_SNAKE_CASE						)->Any:




         '''simple docstring'''





         A_ :							Union[str, Any]							=   self.features[i]

         A_ :							str							=   torch.tensor(feature.input_ids							,			dtype=torch.long						)
         A_ :							int							=   torch.tensor(feature.attention_mask							,			dtype=torch.long						)
         A_ :							List[Any]							=   torch.tensor(feature.token_type_ids							,			dtype=torch.long						)
         A_ :							Optional[int]							=   torch.tensor(feature.cls_index							,			dtype=torch.long						)
         A_ :							Union[str, Any]							=   torch.tensor(feature.p_mask							,			dtype=torch.float						)
         A_ :							Optional[Any]							=   torch.tensor(feature.is_impossible							,			dtype=torch.float						)

         A_ :							Optional[int]							=   {
             'input_ids': input_ids,
             'attention_mask': attention_mask,
             'token_type_ids': token_type_ids,
         }

         if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
           del inputs["token_type_ids"]

         if self.args.model_type in ["xlnet", "xlm"]:
           inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask}						)
           if self.args.version_2_with_negative:
             inputs.update({'''is_impossible''': is_impossible}						)
           if self.is_language_sensitive:
             inputs.update({'''langs''': (torch.ones(input_ids.shape							,			dtype=torch.intaa						) * self.args.lang_id)}						)

         if self.mode == Split.train:
           A_ :							Any							=   torch.tensor(feature.start_position							,			dtype=torch.long						)
           A_ :							Optional[Any]							=   torch.tensor(feature.end_position							,			dtype=torch.long						)
           inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}						)

         return inputs










from typing import List, Optional, TypeVar

from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal


UpperCamelCase__ :   Optional[Any]						=							logging.get_logger(__name__)


UpperCamelCase__ :   int						=							TypeVar('''DatasetType''', Dataset, IterableDataset)





def        __UpperCAmelCase						(							lowerCamelCase_ :     List[DatasetType]  ,							lowerCamelCase_ :     Optional[List[float]] = None  ,							lowerCamelCase_ :     Optional[int] = None  ,							lowerCamelCase_ :     Optional[DatasetInfo] = None  ,							lowerCamelCase_ :     Optional[NamedSplit] = None  ,							lowerCamelCase_ :     Literal["first_exhausted", "all_exhausted"] = "first_exhausted"  ,							)       ->  DatasetType:







			"""simple docstring"""





			from .arrow_dataset import Dataset
			from .iterable_dataset import IterableDataset

			if not datasets:
						raise ValueError('Unable to interleave an empty list of datasets.'  )
			for i, dataset in enumerate(lowerCamelCase_  ):
						if not isinstance(lowerCamelCase_  ,							(Dataset, IterableDataset)  ):
									if isinstance(lowerCamelCase_  ,							(DatasetDict, IterableDatasetDict)  ):
												if not dataset:
															raise ValueError(
															    F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} '
															    'is an empty dataset dictionary.'  )
												raise ValueError(
												    F'Dataset at position {i} has at least one split: {list(lowerCamelCase_  )}\n'
												    F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(lowerCamelCase_  )  )}\']'  )
									raise ValueError(
									    F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowerCamelCase_  ).__name__}.'  )
						if i == 0:
									SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Dict					  =      (
									    (Dataset, IterableDataset) if isinstance(lowerCamelCase_  ,							lowerCamelCase_  ) else (IterableDataset, Dataset)
									)
						elif not isinstance(lowerCamelCase_  ,							lowerCamelCase_  ):
									raise ValueError(
									    F'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.'  )
			if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
						raise ValueError(F'{stopping_strategy} is not supported. Please enter a valid stopping_strategy.'  )
			if dataset_type is Dataset:
						return _interleave_map_style_datasets(
						    lowerCamelCase_  ,							lowerCamelCase_  ,							lowerCamelCase_  ,							info=lowerCamelCase_  ,							split=lowerCamelCase_  ,							stopping_strategy=lowerCamelCase_  )
			else:
						return _interleave_iterable_datasets(
						    lowerCamelCase_  ,							lowerCamelCase_  ,							lowerCamelCase_  ,							info=lowerCamelCase_  ,							split=lowerCamelCase_  ,							stopping_strategy=lowerCamelCase_  )





def        __UpperCAmelCase						(							lowerCamelCase_ :     List[DatasetType]  ,							lowerCamelCase_ :     Optional[DatasetInfo] = None  ,							lowerCamelCase_ :     Optional[NamedSplit] = None  ,							lowerCamelCase_ :     int = 0  ,							)       ->  DatasetType:







			"""simple docstring"""





			if not dsets:
						raise ValueError('Unable to concatenate an empty list of datasets.'  )
			for i, dataset in enumerate(lowerCamelCase_  ):
						if not isinstance(lowerCamelCase_  ,							(Dataset, IterableDataset)  ):
									if isinstance(lowerCamelCase_  ,							(DatasetDict, IterableDatasetDict)  ):
												if not dataset:
															raise ValueError(
															    F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} '
															    'is an empty dataset dictionary.'  )
												raise ValueError(
												    F'Dataset at position {i} has at least one split: {list(lowerCamelCase_  )}\n'
												    F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(lowerCamelCase_  )  )}\']'  )
									raise ValueError(
									    F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowerCamelCase_  ).__name__}.'  )
						if i == 0:
									SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Any					  =      (
									    (Dataset, IterableDataset) if isinstance(lowerCamelCase_  ,							lowerCamelCase_  ) else (IterableDataset, Dataset)
									)
						elif not isinstance(lowerCamelCase_  ,							lowerCamelCase_  ):
									raise ValueError(
									    F'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.'  )
			if dataset_type is Dataset:
						return _concatenate_map_style_datasets(lowerCamelCase_  ,							info=lowerCamelCase_  ,							split=lowerCamelCase_  ,							axis=lowerCamelCase_  )
			else:
						return _concatenate_iterable_datasets(lowerCamelCase_  ,							info=lowerCamelCase_  ,							split=lowerCamelCase_  ,							axis=lowerCamelCase_  )



