


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 SPIECE_UNDERLINE, logging


SCREAMING_SNAKE_CASE		:Dict     						=   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE		:int     						=   {'''vocab_file''': '''spiece.model'''}

SCREAMING_SNAKE_CASE		:List[str]     						=   {
    '''vocab_file''': {
        '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''',
        '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''',
    }
}

SCREAMING_SNAKE_CASE		:int     						=   {
    '''xlnet-base-cased''': None,
    '''xlnet-large-cased''': None,
}

# Segments (not really needed)
SCREAMING_SNAKE_CASE		:str     						=   0
SCREAMING_SNAKE_CASE		:Dict     						=   1
SCREAMING_SNAKE_CASE		:Tuple     						=   2
SCREAMING_SNAKE_CASE		:int     						=   3
SCREAMING_SNAKE_CASE		:Optional[int]     						=   4


class 			__lowerCAmelCase   (       snake_case_    ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE									=				VOCAB_FILES_NAMES
  _SCREAMING_SNAKE_CASE									=				PRETRAINED_VOCAB_FILES_MAP
  _SCREAMING_SNAKE_CASE									=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  _SCREAMING_SNAKE_CASE									=				'left'



  def __init__(   self				:				Tuple			, _lowerCAmelCase				:				Dict			, _lowerCAmelCase				:				Dict=False			, _lowerCAmelCase				:				str=True			, _lowerCAmelCase				:				List[Any]=False			, _lowerCAmelCase				:				Optional[int]="<s>"			, _lowerCAmelCase				:				List[Any]="</s>"			, _lowerCAmelCase				:				List[str]="<unk>"			, _lowerCAmelCase				:				Any="<sep>"			, _lowerCAmelCase				:				str="<pad>"			, _lowerCAmelCase				:				Any="<cls>"			, _lowerCAmelCase				:				Any="<mask>"			, _lowerCAmelCase				:				Tuple=["<eop>", "<eod>"]			, _lowerCAmelCase				:				List[str] = None			, **_lowerCAmelCase				:				str			, )      ->       None:




     """simple docstring"""
     # Mask token behave like a normal word, i.e. include the space before it
     snake_case_    			=    AddedToken(_lowerCAmelCase			, lstrip=_lowerCAmelCase			, rstrip=_lowerCAmelCase     ) if isinstance(_lowerCAmelCase			, _lowerCAmelCase     ) else mask_token

     snake_case_    			=    {} 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			, additional_special_tokens=_lowerCAmelCase			, sp_model_kwargs=self.sp_model_kwargs			, **_lowerCAmelCase			, )

     snake_case_    			=    3

     snake_case_    			=    do_lower_case
     snake_case_    			=    remove_space
     snake_case_    			=    keep_accents
     snake_case_    			=    vocab_file

     snake_case_    			=    spm.SentencePieceProcessor(**self.sp_model_kwargs     )
     self.sp_model.Load(_lowerCAmelCase     )



  @property
  def     lowerCAmelCase__     (   self				:				Union[str, Any]     )      ->       int:




     """simple docstring"""
     return len(self.sp_model     )



  def     lowerCAmelCase__     (   self				:				List[Any]     )      ->       Optional[int]:




     """simple docstring"""
     snake_case_    			=    {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]     )      ->       str:




     """simple docstring"""
     snake_case_    			=    self.__dict__.copy()
     snake_case_    			=    None
     return state



  def __setstate__(   self				:				Union[str, Any]			, _lowerCAmelCase				:				Optional[int]     )      ->       Optional[Any]:




     """simple docstring"""
     snake_case_    			=    d

     # for backward compatibility
     if not hasattr(self			, "sp_model_kwargs"     ):
        snake_case_    			=    {}

     snake_case_    			=    spm.SentencePieceProcessor(**self.sp_model_kwargs     )
     self.sp_model.Load(self.vocab_file     )



  def     lowerCAmelCase__     (   self				:				str			, _lowerCAmelCase				:				Optional[int]     )      ->       Any:




     """simple docstring"""
     if self.remove_space:
        snake_case_    			=    " ".join(inputs.strip().split()     )
     else:
        snake_case_    			=    inputs
     snake_case_    			=    outputs.replace("``"			, "\""     ).replace("''"			, "\""     )

     if not self.keep_accents:
        snake_case_    			=    unicodedata.normalize("NFKD"			, _lowerCAmelCase     )
        snake_case_    			=    "".join([c for c in outputs if not unicodedata.combining(_lowerCAmelCase     )]     )
     if self.do_lower_case:
        snake_case_    			=    outputs.lower()

     return outputs



  def     lowerCAmelCase__     (   self				:				Optional[Any]			, _lowerCAmelCase				:				Any     )      ->       List[str]:




     """simple docstring"""
     snake_case_    			=    self.preprocess_text(_lowerCAmelCase     )
     snake_case_    			=    self.sp_model.encode(_lowerCAmelCase			, out_type=_lowerCAmelCase     )
     snake_case_    			=    []
     for piece in pieces:
        if len(_lowerCAmelCase     ) > 1 and piece[-1] == str(","     ) and piece[-2].isdigit():
           snake_case_    			=    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:
                 snake_case_    			=    cur_pieces[1:]
              else:
                 snake_case_    			=    cur_pieces[0][1:]
           cur_pieces.append(piece[-1]     )
           new_pieces.extend(_lowerCAmelCase     )
        else:
           new_pieces.append(_lowerCAmelCase     )

     return new_pieces



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




     """simple docstring"""
     return self.sp_model.PieceToId(_lowerCAmelCase     )



  def     lowerCAmelCase__     (   self				:				Tuple			, _lowerCAmelCase				:				Union[str, Any]     )      ->       List[Any]:




     """simple docstring"""
     return self.sp_model.IdToPiece(_lowerCAmelCase     )



  def     lowerCAmelCase__     (   self				:				Union[str, Any]			, _lowerCAmelCase				:				int     )      ->       Tuple:




     """simple docstring"""
     snake_case_    			=    "".join(_lowerCAmelCase     ).replace(_lowerCAmelCase			, " "     ).strip()
     return out_string



  def     lowerCAmelCase__     (   self				:				Optional[int]			, _lowerCAmelCase				:				Any			, _lowerCAmelCase				:				Dict = False			, _lowerCAmelCase				:				Any = None			, _lowerCAmelCase				:				Any = True			, **_lowerCAmelCase				:				List[Any]			, )      ->       str:




     """simple docstring"""
     snake_case_    			=    kwargs.pop("use_source_tokenizer"			, _lowerCAmelCase     )

     snake_case_    			=    self.convert_ids_to_tokens(_lowerCAmelCase			, skip_special_tokens=_lowerCAmelCase     )

     # To avoid mixing byte-level and unicode for byte-level BPT
     # we need to build string separately for added tokens and byte-level tokens
     # cf. https://github.com/huggingface/transformers/issues/1133
     snake_case_    			=    []
     snake_case_    			=    []
     for token in filtered_tokens:
        if skip_special_tokens and token in self.all_special_ids:
           continue
        if token in self.added_tokens_encoder:
           if current_sub_text:
              sub_texts.append(self.convert_tokens_to_string(_lowerCAmelCase     )     )
              snake_case_    			=    []
           sub_texts.append(_lowerCAmelCase     )
        else:
           current_sub_text.append(_lowerCAmelCase     )
     if current_sub_text:
        sub_texts.append(self.convert_tokens_to_string(_lowerCAmelCase     )     )

     # Mimic the behavior of the Rust tokenizer:
     # By default, there are no spaces between special tokens
     snake_case_    			=    "".join(_lowerCAmelCase     )

     snake_case_    			=    (
         clean_up_tokenization_spaces
         if clean_up_tokenization_spaces is not None
         else self.clean_up_tokenization_spaces
     )
     if clean_up_tokenization_spaces:
        snake_case_    			=    self.clean_up_tokenization(_lowerCAmelCase     )
        return clean_text
     else:
        return text



  def     lowerCAmelCase__     (   self				:				Optional[Any]			, _lowerCAmelCase				:				Tuple			, _lowerCAmelCase				:				List[str] = None     )      ->       List[int]:




     """simple docstring"""
     snake_case_    			=    [self.sep_token_id]
     snake_case_    			=    [self.cls_token_id]
     if token_ids_a is None:
        return token_ids_a + sep + cls
     return token_ids_a + sep + token_ids_a + sep + cls



  def     lowerCAmelCase__     (   self				:				Union[str, Any]			, _lowerCAmelCase				:				Dict			, _lowerCAmelCase				:				str = None			, _lowerCAmelCase				:				int = 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 ([0] * len(_lowerCAmelCase     )) + [1] + ([0] * len(_lowerCAmelCase     )) + [1, 1]
     return ([0] * len(_lowerCAmelCase     )) + [1, 1]



  def     lowerCAmelCase__     (   self				:				Optional[int]			, _lowerCAmelCase				:				str			, _lowerCAmelCase				:				Tuple = None     )      ->       List[int]:




     """simple docstring"""
     snake_case_    			=    [self.sep_token_id]
     snake_case_    			=    [2]

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



  def     lowerCAmelCase__     (   self				:				List[str]			, _lowerCAmelCase				:				str			, _lowerCAmelCase				:				Dict = None     )      ->       Tuple[str]:




     """simple docstring"""
     if not os.path.isdir(_lowerCAmelCase     ):
        logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''     )
        return
     snake_case_    			=    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:
           snake_case_    			=    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


__A				=logging.get_logger(__name__)

__A				=list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__A				=tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




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




class     _SCREAMING_SNAKE_CASE     (      snake_case_						):
	lowerCAmelCase__         = 'train'
	lowerCAmelCase__         = 'dev'




class     _SCREAMING_SNAKE_CASE     (      snake_case_						):
	lowerCAmelCase__         = 42
	lowerCAmelCase__         = 42
	lowerCAmelCase__         = 42
	lowerCAmelCase__         = 42



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

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

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

													lowerCamelCase_						=			time.time()
													torch.save(
													    {"features": self.features, "dataset": self.dataset, "examples": self.examples}						,  lowercase						,  )
													# ^ 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 )				->       Tuple:
					return len(self.features )



	def __getitem__(    self						,  lowercase )				->       Dict[str, torch.Tensor]:
					# Convert to Tensors and build dataset
					lowerCamelCase_						=			self.features[i]

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

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

					return inputs


