





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


__lowerCamelCase       :     Dict   =     logging.get_logger(__name__)

__lowerCamelCase       :     Optional[int]   =     list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__lowerCamelCase       :     Optional[Any]   =     tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



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



class 					A__   (       UpperCamelCase__			):
      _UpperCAmelCase	:str						    =   """train"""
      _UpperCAmelCase	:List[Any]						    =   """dev"""



class 					A__   (       UpperCamelCase__			):
      _UpperCAmelCase	:SquadDataTrainingArguments
      _UpperCAmelCase	:List[SquadFeatures]
      _UpperCAmelCase	:Split
      _UpperCAmelCase	:bool





      def __init__( self       ,							A_       ,							A_       ,							A_ = None       ,							A_ = Split.train       ,							A_ = False       ,							A_ = None       ,							A_ = "pt"       ,							):
       '''simple docstring'''




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

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

         UpperCamelCase	,    UpperCamelCase	:					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       ,							)

         UpperCamelCase	:					int       	=   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   ):
       '''simple docstring'''




       return len(self.features   )





      def __getitem__( self       ,							A_   ):
       '''simple docstring'''




       UpperCamelCase	:					Any       	=   self.features[i]

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

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

       return inputs

'''simple docstring'''





from multiprocessing import Lock, Pipe, Process

# lock used to ensure that two processes do not access a pipe at the same time
SCREAMING_SNAKE_CASE_:     Optional[int]  =Lock()





def 	lowerCAmelCase_				(					snake_case_       : Dict					,    snake_case_       : Dict					,    snake_case_       : Optional[int]					,    snake_case_       : Tuple					,    snake_case_       : Any					,    snake_case_       : Optional[Any]					,    snake_case_       : Union[str, Any]			)    ->      Optional[Any]:


     '''simple docstring'''




     global process_lock

     # we perform n swaps since after n swaps we know we are sorted
     # we *could* stop early if we are sorted already, but it takes as long to
     # find out we are sorted as it does to sort the list with this algorithm
     for i in range(0					,    10			):
          if (i + position) % 2 == 0 and r_send is not None:
               # send your value to your right neighbor
               process_lock.acquire()
               r_send[1].send(snake_case_			)
               process_lock.release()

               # receive your right neighbor's value
               process_lock.acquire()
               UpperCAmelCase_           =   rr_cv[0].recv()
               process_lock.release()

               # take the lower value since you are on the left
               UpperCAmelCase_           =   min(snake_case_					,    snake_case_			)
          elif (i + position) % 2 != 0 and l_send is not None:
               # send your value to your left neighbor
               process_lock.acquire()
               l_send[1].send(snake_case_			)
               process_lock.release()

               # receive your left neighbor's value
               process_lock.acquire()
               UpperCAmelCase_           =   lr_cv[0].recv()
               process_lock.release()

               # take the higher value since you are on the right
               UpperCAmelCase_           =   max(snake_case_					,    snake_case_			)
    # after all swaps are performed, send the values back to main
     result_pipe[1].send(snake_case_			)





def 	lowerCAmelCase_				(					snake_case_       : Optional[Any]			)    ->      Dict:


     '''simple docstring'''




     UpperCAmelCase_           =   []
     UpperCAmelCase_           =   []
     # initialize the list of pipes where the values will be retrieved
     for _ in arr:
          result_pipe.append(Pipe()			)
     # creates the processes
     # the first and last process only have one neighbor so they are made outside
     # of the loop
     UpperCAmelCase_           =   Pipe()
     UpperCAmelCase_           =   Pipe()
     process_array_.append(
         Process(
             target=snake_case_					,    args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0])					,    )			)
     UpperCAmelCase_           =   temp_rs
     UpperCAmelCase_           =   temp_rr

     for i in range(1					,    len(snake_case_			) - 1			):
          UpperCAmelCase_           =   Pipe()
          UpperCAmelCase_           =   Pipe()
          process_array_.append(
              Process(
                  target=snake_case_					,    args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i])					,    )			)
          UpperCAmelCase_           =   temp_rs
          UpperCAmelCase_           =   temp_rr

     process_array_.append(
         Process(
             target=snake_case_					,    args=(
                 len(snake_case_			) - 1,
                 arr[len(snake_case_			) - 1],
                 temp_ls,
                 None,
                 temp_lr,
                 None,
                 result_pipe[len(snake_case_			) - 1],
             )					,    )			)

     # start the processes
     for p in process_array_:
          p.start()

     # wait for the processes to end and write their values to the list
     for p in range(0					,    len(snake_case_			)			):
          UpperCAmelCase_           =   result_pipe[p][0].recv()
          process_array_[p].join()
     return arr





def 	lowerCAmelCase_				(					)    ->      str:


     '''simple docstring'''




     UpperCAmelCase_           =   list(range(10					,    0					,    -1			)			)
     print("Initial List"			)
     print(*snake_case_			)
     UpperCAmelCase_           =   odd_even_transposition(snake_case_			)
     print("Sorted List\n"			)
     print(*snake_case_			)


if __name__ == "__main__":
    main()




