


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

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


__UpperCamelCase       :       int						       =				logging.get_logger(__name__)
__UpperCamelCase       :       Any						       =				{"vocab_file": "spiece.model"}

__UpperCamelCase       :       List[Any]						       =				{
    "vocab_file": {
        "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model",
        "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model",
        "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model",
        "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model",
        "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model",
        "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model",
        "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model",
        "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model",
    }
}

__UpperCamelCase       :       Optional[Any]						       =				{
    "albert-base-v1": 512,
    "albert-large-v1": 512,
    "albert-xlarge-v1": 512,
    "albert-xxlarge-v1": 512,
    "albert-base-v2": 512,
    "albert-large-v2": 512,
    "albert-xlarge-v2": 512,
    "albert-xxlarge-v2": 512,
}

__UpperCamelCase       :       Union[str, Any]						       =				"▁"

class       __magic_name__	(     __lowerCAmelCase):
     A:		Union[str, Any]			=      VOCAB_FILES_NAMES
     A:		int			=      PRETRAINED_VOCAB_FILES_MAP
     A:		Union[str, Any]			=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES


     def __init__(      self							:     Any							,	lowerCamelCase__							:     str							,	lowerCamelCase__							:     str=True							,	lowerCamelCase__							:     Union[str, Any]=True							,	lowerCamelCase__							:     List[Any]=False							,	lowerCamelCase__							:     Optional[Any]="[CLS]"							,	lowerCamelCase__							:     List[str]="[SEP]"							,	lowerCamelCase__							:     Any="<unk>"							,	lowerCamelCase__							:     Optional[int]="[SEP]"							,	lowerCamelCase__							:     List[str]="<pad>"							,	lowerCamelCase__							:     int="[CLS]"							,	lowerCamelCase__							:     Dict="[MASK]"							,	lowerCamelCase__							:     Optional[Dict[str, Any]] = None							,	**lowerCamelCase__							:     Optional[Any]							,	)  ->      None:





      '''simple docstring'''






      UpperCamelCase__					:    Any          =   (
          AddedToken(lowerCamelCase__							,	lstrip=lowerCamelCase__							,	rstrip=lowerCamelCase__							,	normalized=lowerCamelCase__			)
          if isinstance(lowerCamelCase__							,	lowerCamelCase__			)
          else mask_token
      )

      UpperCamelCase__					:    Dict          =   {} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          do_lower_case=lowerCamelCase__							,	remove_space=lowerCamelCase__							,	keep_accents=lowerCamelCase__							,	bos_token=lowerCamelCase__							,	eos_token=lowerCamelCase__							,	unk_token=lowerCamelCase__							,	sep_token=lowerCamelCase__							,	pad_token=lowerCamelCase__							,	cls_token=lowerCamelCase__							,	mask_token=lowerCamelCase__							,	sp_model_kwargs=self.sp_model_kwargs							,	**lowerCamelCase__							,	)

      UpperCamelCase__					:    Optional[Any]          =   do_lower_case
      UpperCamelCase__					:    Tuple          =   remove_space
      UpperCamelCase__					:    Union[str, Any]          =   keep_accents
      UpperCamelCase__					:    str          =   vocab_file

      UpperCamelCase__					:    str          =   spm.SentencePieceProcessor(**self.sp_model_kwargs			)
      self.sp_model.Load(lowerCamelCase__			)


     @property
     def      UpperCAmelCase__	(      self							:     List[str]			)  ->      int:





      '''simple docstring'''






      return len(self.sp_model			)


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





      '''simple docstring'''






      UpperCamelCase__					:    Any          =   {self.convert_ids_to_tokens(lowerCamelCase__			): i for i in range(self.vocab_size			)}
      vocab.update(self.added_tokens_encoder			)
      return vocab


     def __getstate__(      self							:     Union[str, Any]			)  ->      Any:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   self.__dict__.copy()
      UpperCamelCase__					:    Any          =   None
      return state


     def __setstate__(      self							:     Optional[int]							,	lowerCamelCase__							:     List[str]			)  ->      str:





      '''simple docstring'''






      UpperCamelCase__					:    Any          =   d

      # for backward compatibility
      if not hasattr(self							,	'''sp_model_kwargs'''			):
       UpperCamelCase__					:    Tuple          =   {}

      UpperCamelCase__					:    Dict          =   spm.SentencePieceProcessor(**self.sp_model_kwargs			)
      self.sp_model.Load(self.vocab_file			)


     def      UpperCAmelCase__	(      self							:     int							,	lowerCamelCase__							:     Optional[int]			)  ->      Dict:





      '''simple docstring'''






      if self.remove_space:
       UpperCamelCase__					:    List[str]          =   ''' '''.join(inputs.strip().split()			)
      else:
       UpperCamelCase__					:    Tuple          =   inputs
      UpperCamelCase__					:    Optional[Any]          =   outputs.replace('''``'''							,	'''"'''			).replace('''\'\''''							,	'''"'''			)

      if not self.keep_accents:
       UpperCamelCase__					:    Any          =   unicodedata.normalize('''NFKD'''							,	lowerCamelCase__			)
       UpperCamelCase__					:    Dict          =   ''''''.join([c for c in outputs if not unicodedata.combining(lowerCamelCase__			)]			)
      if self.do_lower_case:
       UpperCamelCase__					:    int          =   outputs.lower()

      return outputs


     def      UpperCAmelCase__	(      self							:     str							,	lowerCamelCase__							:     str			)  ->      List[str]:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   self.preprocess_text(lowerCamelCase__			)
      UpperCamelCase__					:    Optional[Any]          =   self.sp_model.encode(lowerCamelCase__							,	out_type=lowerCamelCase__			)
      UpperCamelCase__					:    int          =   []
      for piece in pieces:
       if len(lowerCamelCase__			) > 1 and piece[-1] == str(''','''			) and piece[-2].isdigit():
        UpperCamelCase__					:    Tuple          =   self.sp_model.EncodeAsPieces(piece[:-1].replace(lowerCamelCase__							,	''''''			)			)
        if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
         if len(cur_pieces[0]			) == 1:
          UpperCamelCase__					:    Optional[Any]          =   cur_pieces[1:]
         else:
          UpperCamelCase__					:    List[str]          =   cur_pieces[0][1:]
        cur_pieces.append(piece[-1]			)
        new_pieces.extend(lowerCamelCase__			)
       else:
        new_pieces.append(lowerCamelCase__			)

      return new_pieces


     def      UpperCAmelCase__	(      self							:     Tuple							,	lowerCamelCase__							:     Union[str, Any]			)  ->      int:





      '''simple docstring'''






      return self.sp_model.PieceToId(lowerCamelCase__			)


     def      UpperCAmelCase__	(      self							:     Dict							,	lowerCamelCase__							:     Union[str, Any]			)  ->      List[str]:





      '''simple docstring'''






      return self.sp_model.IdToPiece(lowerCamelCase__			)


     def      UpperCAmelCase__	(      self							:     Any							,	lowerCamelCase__							:     Optional[int]			)  ->      int:





      '''simple docstring'''






      UpperCamelCase__					:    str          =   []
      UpperCamelCase__					:    Any          =   ''''''
      UpperCamelCase__					:    Optional[int]          =   False
      for token in tokens:
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
        if not prev_is_special:
         out_string += " "
        out_string += self.sp_model.decode(lowerCamelCase__			) + token
        UpperCamelCase__					:    str          =   True
        UpperCamelCase__					:    Any          =   []
       else:
        current_sub_tokens.append(lowerCamelCase__			)
        UpperCamelCase__					:    Any          =   False
      out_string += self.sp_model.decode(lowerCamelCase__			)
      return out_string.strip()


     def      UpperCAmelCase__	(      self							:     Optional[int]							,	lowerCamelCase__							:     List[int]							,	lowerCamelCase__							:     Optional[List[int]] = None			)  ->      List[int]:





      '''simple docstring'''






      UpperCamelCase__					:    List[str]          =   [self.sep_token_id]
      UpperCamelCase__					:    List[Any]          =   [self.cls_token_id]
      if token_ids_a is None:
       return cls + token_ids_a + sep
      return cls + token_ids_a + sep + token_ids_a + sep


     def      UpperCAmelCase__	(      self							:     Tuple							,	lowerCamelCase__							:     List[int]							,	lowerCamelCase__							:     Optional[List[int]] = None							,	lowerCamelCase__							:     bool = False			)  ->      List[int]:





      '''simple docstring'''






      if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=lowerCamelCase__							,	token_ids_a=lowerCamelCase__							,	already_has_special_tokens=lowerCamelCase__			)

      if token_ids_a is not None:
       return [1] + ([0] * len(lowerCamelCase__			)) + [1] + ([0] * len(lowerCamelCase__			)) + [1]
      return [1] + ([0] * len(lowerCamelCase__			)) + [1]


     def      UpperCAmelCase__	(      self							:     Optional[int]							,	lowerCamelCase__							:     List[int]							,	lowerCamelCase__							:     Optional[List[int]] = None			)  ->      List[int]:





      '''simple docstring'''






      UpperCamelCase__					:    List[str]          =   [self.sep_token_id]
      UpperCamelCase__					:    Optional[int]          =   [self.cls_token_id]

      if token_ids_a is None:
       return len(cls + token_ids_a + sep			) * [0]
      return len(cls + token_ids_a + sep			) * [0] + len(token_ids_a + sep			) * [1]


     def      UpperCAmelCase__	(      self							:     Dict							,	lowerCamelCase__							:     str							,	lowerCamelCase__							:     Optional[str] = None			)  ->      Tuple[str]:





      '''simple docstring'''






      if not os.path.isdir(lowerCamelCase__			):
       logger.error(F"Vocabulary path ({save_directory}) should be a directory"			)
       return
      UpperCamelCase__					:    Union[str, Any]          =   os.path.join(
          lowerCamelCase__							,	(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']			)

      if os.path.abspath(self.vocab_file			) != os.path.abspath(lowerCamelCase__			) and os.path.isfile(self.vocab_file			):
       copyfile(self.vocab_file							,	lowerCamelCase__			)
      elif not os.path.isfile(self.vocab_file			):
       with open(lowerCamelCase__							,	'''wb'''			) as fi:
        UpperCamelCase__					:    List[str]          =   self.sp_model.serialized_model_proto()
        fi.write(lowerCamelCase__			)

      return (out_vocab_file,)






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       :       List[str]						       =				logging.get_logger(__name__)

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

@dataclass
class       __magic_name__	:
     A:		str			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "Model type selected in the list: " + ", ".join(__lowerCAmelCase)})
     A:		str			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."})
     A:		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."
             )
         }					,				)
     A:		int			=      field(
         default=1_2_8					,				metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}					,				)
     A:		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."
             )
         }					,				)
     A:		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."
             )
         }					,				)
     A:		bool			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "Overwrite the cached training and evaluation sets"})
     A:		bool			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."})
     A:		float			=      field(
         default=0.0					,				metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."})
     A:		int			=      field(
         default=2_0					,				metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."})
     A:		int			=      field(
         default=0					,				metadata={
             "help": (
                 "language id of input for language-specific xlm models (see"
                 " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
             )
         }					,				)
     A:		int			=      field(default=1					,				metadata={"help": "multiple threads for converting example to features"})



class       __magic_name__	(     __lowerCAmelCase):
     A:		Union[str, Any]			=      "train"
     A:		List[str]			=      "dev"



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


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





      '''simple docstring'''






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

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

        UpperCamelCase__       ,				UpperCamelCase__					:    Union[str, Any]          =   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__					:    Tuple          =   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							:     Any			)  ->      List[str]:





      '''simple docstring'''






      return len(self.features			)


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





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   self.features[i]

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

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

      return inputs


