
'''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


snake_case_ :  int     =					logging.get_logger(__name__)

snake_case_ :  Union[str, Any]     =					list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
snake_case_ :  int     =					tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)


@dataclass
class 						lowercase__	:






   '''simple docstring'''







   _snake_case		   =							field(
       default=snake_case_,					metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(snake_case_   )}   )
   _snake_case		   =							field(
       default=snake_case_,					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=snake_case_,					metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}   )
   _snake_case		   =							field(
       default=snake_case_,					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 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   _snake_case		   =							'''train'''
   _snake_case		   =							'''dev'''




class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   _snake_case		   =							42
   _snake_case		   =							42
   _snake_case		   =							42
   _snake_case		   =							42







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ = None ,   lowerCamelCase__ = Split.train ,   lowerCamelCase__ = False ,   lowerCamelCase__ = None ,   lowerCamelCase__ = "pt" ,   ):

      '''simple docstring'''







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

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

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

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

      '''simple docstring'''







      return len(self.features   )







   def __getitem__(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  self.features[i]

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

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

      return inputs







'''simple docstring'''


def  __snake_case     (    _UpperCAmelCase					:       list[list[float]]):
   UpperCamelCase       =  []
   for data in source_data:
      for i, el in enumerate(_UpperCAmelCase):
         if len(_UpperCAmelCase) < i + 1:
            data_lists.append([])
         data_lists[i].append(float(_UpperCAmelCase))
   return data_lists



def  __snake_case     (    _UpperCAmelCase					:       list[list[float]],      _UpperCAmelCase					:       list[int]):
   UpperCamelCase       =  []
   for dlist, weight in zip(_UpperCAmelCase,      _UpperCAmelCase):
      UpperCamelCase       =  min(_UpperCAmelCase)
      UpperCamelCase       =  max(_UpperCAmelCase)

      UpperCamelCase       =  []
      # for weight 0 score is 1 - actual score
      if weight == 0:
         for item in dlist:
            try:
               score.append(1 - ((item - mind) / (maxd - mind)))
            except ZeroDivisionError:
               score.append(1)

      elif weight == 1:
         for item in dlist:
            try:
               score.append((item - mind) / (maxd - mind))
            except ZeroDivisionError:
               score.append(0)

        # weight not 0 or 1
      else:
         UpperCamelCase       =  f'Invalid weight of {weight:f} provided'
         raise ValueError(_UpperCAmelCase)

      score_lists.append(_UpperCAmelCase)

   return score_lists



def  __snake_case     (    _UpperCAmelCase					:       list[list[float]]):
   UpperCamelCase       =  [0 for i in range(len(score_lists[0]))]

   for slist in score_lists:
      for j, ele in enumerate(_UpperCAmelCase):
         UpperCamelCase       =  final_scores[j] + ele

   return final_scores



def  __snake_case     (    _UpperCAmelCase					:       list[list[float]],      _UpperCAmelCase					:       list[int]):
   UpperCamelCase       =  get_data(_UpperCAmelCase)
   UpperCamelCase       =  calculate_each_score(_UpperCAmelCase,      _UpperCAmelCase)
   UpperCamelCase       =  generate_final_scores(_UpperCAmelCase)

   # append scores to source data
   for i, ele in enumerate(_UpperCAmelCase):
      source_data[i].append(_UpperCAmelCase)

   return source_data





