





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


SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__							:      Dict         =    list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
SCREAMING_SNAKE_CASE__							:      Dict         =    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class 	__lowerCAmelCase      :
   _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=128		,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=128		,metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}		,)
   _UpperCamelCase			:    int  		=					field(
       default=64		,metadata={
           """help""": (
               """The maximum number of tokens for the question. Questions longer than this will """
               """be truncated to this length."""
           )
       }		,)
   _UpperCamelCase			:    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."""
           )
       }		,)
   _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=20		,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 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    Union[str, Any]  		=					"""train"""
   _UpperCamelCase			:    Tuple  		=					"""dev"""







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    SquadDataTrainingArguments
   _UpperCamelCase			:    List[SquadFeatures]
   _UpperCamelCase			:    Split
   _UpperCamelCase			:    bool





   def __init__(			self       ,      snake_case       ,      snake_case       ,      snake_case = None       ,      snake_case = Split.train       ,      snake_case = False       ,      snake_case = None       ,      snake_case = "pt"       ,      )					->	List[Any]:
      """simple docstring"""





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

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

            a__		,  a__						:    int   		=	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__						:    Optional[int]   		=	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   )					->	str:
      """simple docstring"""





      return len(self.features   )





   def __getitem__(			self       ,      snake_case   )					->	Dict[str, torch.Tensor]:
      """simple docstring"""





      a__						:    str   		=	self.features[i]

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

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

      return inputs








import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


SCREAMING_SNAKE_CASE__							:      Tuple         =    logging.get_logger(__name__)


SCREAMING_SNAKE_CASE__							:      int         =    """▁"""

SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    {"""vocab_file""": """spiece.model"""}

SCREAMING_SNAKE_CASE__							:      Optional[int]         =    {
    """vocab_file""": {
        """google/reformer-crime-and-punishment""": (
            """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model"""
        )
    }
}

SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    {
    """google/reformer-crime-and-punishment""": 5_2_4_2_8_8,
}







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    List[Any]  		=					VOCAB_FILES_NAMES
   _UpperCamelCase			:    Any  		=					PRETRAINED_VOCAB_FILES_MAP
   _UpperCamelCase			:    Any  		=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   _UpperCamelCase			:    Tuple  		=					["""input_ids""", """attention_mask"""]





   def __init__(			self       ,      snake_case       ,      snake_case="</s>"       ,      snake_case="<unk>"       ,      snake_case=[]       ,      snake_case = None       ,      **snake_case       ,      )					->	None:
      """simple docstring"""





      a__						:    Optional[Any]   		=	{} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          eos_token=snake_case       ,      unk_token=snake_case       ,      additional_special_tokens=snake_case       ,      sp_model_kwargs=self.sp_model_kwargs       ,      **snake_case       ,      )

      a__						:    Union[str, Any]   		=	vocab_file
      a__						:    Optional[Any]   		=	spm.SentencePieceProcessor(**self.sp_model_kwargs   )
      self.sp_model.Load(snake_case   )





   @property
   def 						_snake_case			(			self   )					->	str:
      """simple docstring"""





      return self.sp_model.get_piece_size()





   def 						_snake_case			(			self   )					->	Dict[str, int]:
      """simple docstring"""





      a__						:    Dict   		=	{self.convert_ids_to_tokens(snake_case   ): i for i in range(self.vocab_size   )}
      vocab.update(self.added_tokens_encoder   )
      return vocab





   def __getstate__(			self   )					->	Any:
      """simple docstring"""





      a__						:    Tuple   		=	self.__dict__.copy()
      a__						:    Optional[int]   		=	None
      return state





   def __setstate__(			self       ,      snake_case   )					->	Union[str, Any]:
      """simple docstring"""





      a__						:    List[Any]   		=	d

      # for backward compatibility
      if not hasattr(self       ,      "sp_model_kwargs"   ):
         a__						:    List[Any]   		=	{}

      a__						:    int   		=	spm.SentencePieceProcessor(**self.sp_model_kwargs   )
      self.sp_model.Load(self.vocab_file   )





   def 						_snake_case			(			self       ,      snake_case   )					->	List[str]:
      """simple docstring"""





      return self.sp_model.encode(snake_case       ,      out_type=snake_case   )





   def 						_snake_case			(			self       ,      snake_case   )					->	Union[str, Any]:
      """simple docstring"""





      return self.sp_model.piece_to_id(snake_case   )





   def 						_snake_case			(			self       ,      snake_case   )					->	Any:
      """simple docstring"""





      if index < self.sp_model.get_piece_size():
         a__						:    Optional[Any]   		=	self.sp_model.IdToPiece(snake_case   )
      return token





   def 						_snake_case			(			self       ,      snake_case   )					->	Any:
      """simple docstring"""





      a__						:    int   		=	[]
      a__						:    Dict   		=	""
      for token in tokens:
         # make sure that special tokens are not decoded using sentencepiece model
         if token in self.all_special_tokens:
            out_string += self.sp_model.decode(snake_case   ) + token
            a__						:    Dict   		=	[]
         else:
            current_sub_tokens.append(snake_case   )
      out_string += self.sp_model.decode(snake_case   )
      return out_string.strip()





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case = None   )					->	Tuple[str]:
      """simple docstring"""





      if not os.path.isdir(snake_case   ):
         logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""   )
         return
      a__						:    Tuple   		=	os.path.join(
          snake_case       ,      (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]   )

      if os.path.abspath(self.vocab_file   ) != os.path.abspath(snake_case   ) and os.path.isfile(self.vocab_file   ):
         copyfile(self.vocab_file       ,      snake_case   )
      elif not os.path.isfile(self.vocab_file   ):
         with open(snake_case       ,      "wb"   ) as fi:
            a__						:    str   		=	self.sp_model.serialized_model_proto()
            fi.write(snake_case   )

      return (out_vocab_file,)

