



"""simple docstring"""







import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


A    =			threading.Lock()
A    =			None

A    =			{
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

A    =			logging.WARNING

A    =			True

def   lowerCAmelCase__			(     ) ->							List[Any]:
							A         =					os.getenv('TRANSFORMERS_VERBOSITY'				,      lowerCamelCase__			)
							if env_level_str:
														if env_level_str in log_levels:
																					return log_levels[env_level_str]
														else:
																					logging.getLogger().warning(
																					    f"""Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, """
																					    f"""has to be one of: { ', '.join(log_levels.keys()			) }"""			)
							return _default_log_level

def   lowerCAmelCase__			(     ) ->							str:
							return __name__.split('.'			)[0]

def   lowerCAmelCase__			(     ) ->							logging.Logger:
							return logging.getLogger(_get_library_name()			)

def   lowerCAmelCase__			(     ) ->							None:
							global _default_handler

							with _lock:
														if _default_handler:
																					# This library has already configured the library root logger.
																					return
														A         =					logging.StreamHandler()  # Set sys.stderr as stream.
														A         =					sys.stderr.flush

														# Apply our default configuration to the library root logger.
														A         =					_get_library_root_logger()
														library_root_logger.addHandler(_default_handler			)
														library_root_logger.setLevel(_get_default_logging_level()			)
														A         =					False

def   lowerCAmelCase__			(     ) ->							None:
							global _default_handler

							with _lock:
														if not _default_handler:
																					return

														A         =					_get_library_root_logger()
														library_root_logger.removeHandler(_default_handler			)
														library_root_logger.setLevel(logging.NOTSET			)
														A         =					None

def   lowerCAmelCase__			(     ) ->							Optional[Any]:
							return log_levels

def   lowerCAmelCase__			(     lowerCamelCase__ = None			) ->							logging.Logger:

							if name is None:
														A         =					_get_library_name()

							_configure_library_root_logger()
							return logging.getLogger(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							int:
							_configure_library_root_logger()
							return _get_library_root_logger().getEffectiveLevel()

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							None:
							_configure_library_root_logger()
							_get_library_root_logger().setLevel(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							List[str]:
							return set_verbosity(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							str:
							return set_verbosity(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							Dict:
							return set_verbosity(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							Any:
							return set_verbosity(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							None:
							_configure_library_root_logger()

							assert _default_handler is not None
							_get_library_root_logger().removeHandler(_default_handler			)

def   lowerCAmelCase__			(     ) ->							None:
							_configure_library_root_logger()

							assert _default_handler is not None
							_get_library_root_logger().addHandler(_default_handler			)

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							None:
							_configure_library_root_logger()

							assert handler is not None
							_get_library_root_logger().addHandler(lowerCamelCase__			)

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							None:
							_configure_library_root_logger()

							assert handler is not None and handler not in _get_library_root_logger().handlers
							_get_library_root_logger().removeHandler(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							None:
							_configure_library_root_logger()
							A         =					False

def   lowerCAmelCase__			(     ) ->							None:
							_configure_library_root_logger()
							A         =					True

def   lowerCAmelCase__			(     ) ->							None:
							A         =					_get_library_root_logger().handlers

							for handler in handlers:
														A         =					logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'			)
														handler.setFormatter(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							None:
							A         =					_get_library_root_logger().handlers

							for handler in handlers:
														handler.setFormatter(lowerCamelCase__			)

def   lowerCAmelCase__			(     self				,      *lowerCamelCase__				,      **lowerCamelCase__			) ->							Optional[int]:
							A         =					os.getenv('TRANSFORMERS_NO_ADVISORY_WARNINGS'				,      lowerCamelCase__			)
							if no_advisory_warnings:
														return
							self.warning(*lowerCamelCase__				,      **lowerCamelCase__			)


A    =			warning_advice

@functools.lru_cache(lowerCamelCase__			)
def   lowerCAmelCase__			(     self				,      *lowerCamelCase__				,      **lowerCamelCase__			) ->							Optional[int]:
							self.warning(*lowerCamelCase__				,      **lowerCamelCase__			)


A    =			warning_once






class      UpperCAmelCase__		:



		def __init__( self  :    List[Any]      ,							*snake_case  :    Any      ,							**snake_case  :    Tuple				)			->						Any:  # pylint: disable=unused-argument






									'''simple docstring'''

									A         =					args[0] if args else None



		def __iter__( self  :    Any				)			->						int:






									'''simple docstring'''

									return iter(self._iterator				)



		def __getattr__( self  :    List[Any]      ,							snake_case  :    Optional[int]				)			->						Dict:






									'''simple docstring'''

									def empty_fn(*snake_case  :    List[str]      ,							**snake_case  :    List[Any]				):  # pylint: disable=unused-argument
																return

									return empty_fn



		def __enter__( self  :    Dict				)			->						Optional[Any]:






									'''simple docstring'''

									return self



		def __exit__( self  :    Tuple      ,							snake_case  :    List[str]      ,							snake_case  :    Optional[int]      ,							snake_case  :    Tuple				)			->						List[Any]:






									'''simple docstring'''

									return






class      UpperCAmelCase__		:



		def __call__( self  :    List[str]      ,							*snake_case  :    str      ,							**snake_case  :    int				)			->						Dict:






									'''simple docstring'''

									if _tqdm_active:
																return tqdm_lib.tqdm(*snake_case      ,							**snake_case				)
									else:
																return EmptyTqdm(*snake_case      ,							**snake_case				)



		def 					A_		( self  :    Union[str, Any]      ,							*snake_case  :    List[str]      ,							**snake_case  :    Optional[int]				)			->						List[str]:






									'''simple docstring'''

									A         =					None
									if _tqdm_active:
																return tqdm_lib.tqdm.set_lock(*snake_case      ,							**snake_case				)



		def 					A_		( self  :    Tuple				)			->						List[Any]:






									'''simple docstring'''

									if _tqdm_active:
																return tqdm_lib.tqdm.get_lock()



A    =			_tqdm_cls()

def   lowerCAmelCase__			(     ) ->							bool:
							global _tqdm_active
							return bool(_tqdm_active			)

def   lowerCAmelCase__			(     ) ->							List[str]:
							global _tqdm_active
							A         =					True
							hf_hub_utils.enable_progress_bars()

def   lowerCAmelCase__			(     ) ->							Any:
							global _tqdm_active
							A         =					False
							hf_hub_utils.disable_progress_bars()








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






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	str 							=     """train"""
		lowerCAmelCase_       :	Union[str, Any] 							=     """dev"""






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	SquadDataTrainingArguments
		lowerCAmelCase_       :	List[SquadFeatures]
		lowerCAmelCase_       :	Split
		lowerCAmelCase_       :	bool



		def __init__( self  :    List[Any]      ,							snake_case  :    SquadDataTrainingArguments      ,							snake_case  :    PreTrainedTokenizer      ,							snake_case  :    Optional[int] = None      ,							snake_case  :    Union[str, Split] = Split.train      ,							snake_case  :    Optional[bool] = False      ,							snake_case  :    Optional[str] = None      ,							snake_case  :    Optional[str] = "pt"      ,							)			->						Optional[Any]:






									'''simple docstring'''

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

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

																							A      ,  A         =					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         =					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  :    Any				)			->						Dict:






									'''simple docstring'''

									return len(self.features				)



		def __getitem__( self  :    Union[str, Any]      ,							snake_case  :    List[str]				)			->						Dict[str, torch.Tensor]:






									'''simple docstring'''

									A         =					self.features[i]

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

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

									return inputs



