

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 A__    :



 """simple docstring"""







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





class A__    ( A ):



 """simple docstring"""







 _lowercase     :					int      =						'''train'''
 _lowercase     :					Optional[Any]      =						'''dev'''





class A__    ( A ):



 """simple docstring"""







 _lowercase     :					SquadDataTrainingArguments
 _lowercase     :					List[SquadFeatures]
 _lowercase     :					Split
 _lowercase     :					bool

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






      '''simple docstring'''




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

                # Legacy cache files have only features, while new cache files
                # will have dataset and examples also.
                _lowerCAmelCase   :					Union[str, Any]        =    self.old_features["features"]
                _lowerCAmelCase   :					Tuple        =    self.old_features.get("dataset"     ,						A_       )
                _lowerCAmelCase   :					str        =    self.old_features.get("examples"     ,						A_       )
                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   :					Dict        =    self.processor.get_dev_examples(args.data_dir       )
                else:
                     _lowerCAmelCase   :					Union[str, Any]        =    self.processor.get_train_examples(args.data_dir       )

                _lowerCAmelCase   :					List[Any]        =    squad_convert_examples_to_features(
                    examples=self.examples     ,						tokenizer=A_     ,						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=A_     ,						)

                _lowerCAmelCase   :					List[Any]        =    time.time()
                torch.save(
                    {"features": self.features, "dataset": self.dataset, "examples": self.examples}     ,						A_     ,						)
                # ^ 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 :	str       ):






      '''simple docstring'''




      return len(self.features       )


 def __getitem__(		self :	List[str]     ,						A_ :	Union[str, Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    self.features[i]

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

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

      return inputs









from typing import Dict

import numpy as np
import torch

from . import residue_constants as rc
from .tensor_utils import tensor_tree_map, tree_map







def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      Dict[str, torch.Tensor]:

     """simple docstring"""







     _lowerCAmelCase   :					int        =    []
     _lowerCAmelCase   :					Tuple        =    []
     _lowerCAmelCase   :					List[Any]        =    []

     for rt in rc.restypes:
          _lowerCAmelCase   :					int        =    rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]
          restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names]				)
          _lowerCAmelCase   :					str        =    {name: i for i, name in enumerate(SCREAMING_SNAKE_CASE				)}
          restype_atomaa_to_atomaa_list.append(
              [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types]				)

          restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names]				)

     # Add dummy mapping for restype 'UNK'
     restype_atomaa_to_atomaa_list.append([0] * 14				)
     restype_atomaa_to_atomaa_list.append([0] * 37				)
     restype_atomaa_mask_list.append([0.0] * 14				)

     _lowerCAmelCase   :					List[str]        =    torch.tensor(
         SCREAMING_SNAKE_CASE		,							dtype=torch.intaa		,							device=protein["aatype"].device		,							)
     _lowerCAmelCase   :					str        =    torch.tensor(
         SCREAMING_SNAKE_CASE		,							dtype=torch.intaa		,							device=protein["aatype"].device		,							)
     _lowerCAmelCase   :					Optional[Any]        =    torch.tensor(
         SCREAMING_SNAKE_CASE		,							dtype=torch.floataa		,							device=protein["aatype"].device		,							)
     _lowerCAmelCase   :					List[str]        =    protein["aatype"].to(torch.long				)

     # create the mapping for (residx, atom14) --> atom37, i.e. an array
     # with shape (num_res, 14) containing the atom37 indices for this protein
     _lowerCAmelCase   :					Dict        =    restype_atomaa_to_atomaa[protein_aatype]
     _lowerCAmelCase   :					Optional[Any]        =    restype_atomaa_mask[protein_aatype]

     _lowerCAmelCase   :					Any        =    residx_atomaa_mask
     _lowerCAmelCase   :					Dict        =    residx_atomaa_to_atomaa.long()

     # create the gather indices for mapping back
     _lowerCAmelCase   :					Optional[int]        =    restype_atomaa_to_atomaa[protein_aatype]
     _lowerCAmelCase   :					str        =    residx_atomaa_to_atomaa.long()

     # create the corresponding mask
     _lowerCAmelCase   :					Dict        =    torch.zeros([21, 37]		,							dtype=torch.floataa		,							device=protein["aatype"].device				)
     for restype, restype_letter in enumerate(rc.restypes				):
          _lowerCAmelCase   :					Optional[Any]        =    rc.restype_atoa[restype_letter]
          _lowerCAmelCase   :					int        =    rc.residue_atoms[restype_name]
          for atom_name in atom_names:
               _lowerCAmelCase   :					Union[str, Any]        =    rc.atom_order[atom_name]
               _lowerCAmelCase   :					Dict        =    1

     _lowerCAmelCase   :					Tuple        =    restype_atomaa_mask[protein_aatype]
     _lowerCAmelCase   :					List[str]        =    residx_atomaa_mask

     return protein







def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      Dict[str, np.ndarray]:

     """simple docstring"""







     _lowerCAmelCase   :					Any        =    tree_map(lambda SCREAMING_SNAKE_CASE				: torch.tensor(SCREAMING_SNAKE_CASE		,							device=batch["aatype"].device				)		,							SCREAMING_SNAKE_CASE		,							np.ndarray				)
     _lowerCAmelCase   :					Optional[int]        =    tensor_tree_map(lambda SCREAMING_SNAKE_CASE				: np.array(SCREAMING_SNAKE_CASE				)		,							make_atomaa_masks(SCREAMING_SNAKE_CASE				)				)
     return out






