
"""simple docstring"""


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


A_    							=					logging.get_logger(__name__)

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




@dataclass
class  __lowerCamelCase  :
				a__:      str          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'Model type selected in the list: ' + ', '.join(lowerCAmelCase			)}			)
				a__:      str          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'}			)
				a__:      int          =    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.'
				        )
				    }						,	)
				a__:      int          =    field(
				    default=128						,	metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}						,	)
				a__:      int          =    field(
				    default=64						,	metadata={
				        'help': (
				            'The maximum number of tokens for the question. Questions longer than this will '
				            'be truncated to this length.'
				        )
				    }						,	)
				a__:      int          =    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.'
				        )
				    }						,	)
				a__:      bool          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'Overwrite the cached training and evaluation sets'}			)
				a__:      bool          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'}			)
				a__:      float          =    field(
				    default=0.0						,	metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}			)
				a__:      int          =    field(
				    default=20						,	metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}			)
				a__:      int          =    field(
				    default=0						,	metadata={
				        'help': (
				            'language id of input for language-specific xlm models (see'
				            ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
				        )
				    }						,	)
				a__:      int          =    field(default=1						,	metadata={'help': 'multiple threads for converting example to features'}			)




class  __lowerCamelCase  ( lowerCAmelCase			):
				a__:      int          =    'train'
				a__:      Any          =    'dev'




class  __lowerCamelCase  ( lowerCAmelCase			):
				a__:      SquadDataTrainingArguments
				a__:      List[SquadFeatures]
				a__:      Split
				a__:      bool




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase = None							,						UpperCAmelCase = Split.train							,						UpperCAmelCase = False							,						UpperCAmelCase = None							,						UpperCAmelCase = "pt"							,						):
							lowerCamelCase_					=  args
							lowerCamelCase_					=  is_language_sensitive
							lowerCamelCase_					=  SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
							if isinstance(UpperCAmelCase							,						UpperCAmelCase   ):
										try:
													lowerCamelCase_					=  Split[mode]
										except KeyError:
													raise KeyError('''mode is not a valid split name'''   )
							lowerCamelCase_					=  mode
							# Load data features from cache or dataset file
							lowerCamelCase_					=  '''v2''' if args.version_2_with_negative else '''v1'''
							lowerCamelCase_					=  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.
							lowerCamelCase_					=  cached_features_file + '''.lock'''
							with FileLock(UpperCAmelCase   ):
										if os.path.exists(UpperCAmelCase   ) and not args.overwrite_cache:
													lowerCamelCase_					=  time.time()
													lowerCamelCase_					=  torch.load(UpperCAmelCase   )

													# Legacy cache files have only features, while new cache files
													# will have dataset and examples also.
													lowerCamelCase_					=  self.old_features['''features''']
													lowerCamelCase_					=  self.old_features.get('''dataset'''							,						UpperCAmelCase   )
													lowerCamelCase_					=  self.old_features.get('''examples'''							,						UpperCAmelCase   )
													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:
																lowerCamelCase_					=  self.processor.get_dev_examples(args.data_dir   )
													else:
																lowerCamelCase_					=  self.processor.get_train_examples(args.data_dir   )

													lowerCamelCase_		, lowerCamelCase_					=  squad_convert_examples_to_features(
													    examples=self.examples							,						tokenizer=UpperCAmelCase							,						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=UpperCAmelCase							,						)

													lowerCamelCase_					=  time.time()
													torch.save(
													    {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}							,						UpperCAmelCase							,						)
													# ^ 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   ):
							return len(self.features   )





				def __getitem__(				self							,						UpperCAmelCase   ):
							# Convert to Tensors and build dataset
							lowerCamelCase_					=  self.features[i]

							lowerCamelCase_					=  torch.tensor(feature.input_ids							,						dtype=torch.long   )
							lowerCamelCase_					=  torch.tensor(feature.attention_mask							,						dtype=torch.long   )
							lowerCamelCase_					=  torch.tensor(feature.token_type_ids							,						dtype=torch.long   )
							lowerCamelCase_					=  torch.tensor(feature.cls_index							,						dtype=torch.long   )
							lowerCamelCase_					=  torch.tensor(feature.p_mask							,						dtype=torch.float   )
							lowerCamelCase_					=  torch.tensor(feature.is_impossible							,						dtype=torch.float   )

							lowerCamelCase_					=  {
							    '''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:
										lowerCamelCase_					=  torch.tensor(feature.start_position							,						dtype=torch.long   )
										lowerCamelCase_					=  torch.tensor(feature.end_position							,						dtype=torch.long   )
										inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}   )

							return inputs







'''simple docstring'''






import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union

from .generation.configuration_utils import GenerationConfig
from .training_args import TrainingArguments
from .utils import add_start_docstrings


__UpperCAmelCase       							=				logging.getLogger(__name__)




@dataclass
@add_start_docstrings(TrainingArguments.__doc__    )
class 						a__							(				a__    ):





							'''simple docstring'''






							lowercase__     :  bool      		= field(default=a__							,							metadata={"help": "Whether to use SortishSampler or not."}    )
							lowercase__     :  bool      		= field(
							    default=a__							,							metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."}    )
							lowercase__     :  Optional[int]      		= field(
							    default=a__							,							metadata={
							        "help": (
							            "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default "
							            "to the `max_length` value of the model configuration."
							        )
							    }							,							)
							lowercase__     :  Optional[int]      		= field(
							    default=a__							,							metadata={
							        "help": (
							            "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default "
							            "to the `num_beams` value of the model configuration."
							        )
							    }							,							)
							lowercase__     :  Optional[Union[str, Path, GenerationConfig]]      		= field(
							    default=a__							,							metadata={
							        "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction."
							    }							,							)







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Dict:
														lowerCAmelCase__			  =      super().to_dict()
														for k, v in d.items():
																					if isinstance(lowerCamelCase_   ,       lowerCamelCase_  ):
																												lowerCAmelCase__			  =      v.to_dict()
														return d