
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


__A				='''▁'''

__A				={'''vocab_file''': '''spiece.model'''}

__A				={
    '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''}
}

__A				={
    '''google/pegasus-xsum''': 5_1_2,
}


__A				=logging.get_logger(__name__)




class     _SCREAMING_SNAKE_CASE     (      snake_case_						):
	lowerCAmelCase__         = VOCAB_FILES_NAMES

	lowerCAmelCase__         = VOCAB_FILES_NAMES
	lowerCAmelCase__         = PRETRAINED_VOCAB_FILES_MAP
	lowerCAmelCase__         = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowerCAmelCase__         = ['input_ids', 'attention_mask']



	def __init__(    self						,  lowercase						,  lowercase="<pad>"						,  lowercase="</s>"						,  lowercase="<unk>"						,  lowercase="<mask_2>"						,  lowercase="<mask_1>"						,  lowercase=None						,  lowercase=103						,  lowercase = None						,  **lowercase						,  )				->       None:
					lowerCamelCase_						=			offset
					if additional_special_tokens is not None:
									if not isinstance(lowercase						,  lowercase ):
													raise TypeError(
													    f'additional_special_tokens should be of type {type(lowercase )}, but is'
													    f' {type(lowercase )}' )

									lowerCamelCase_						=			(
									    ([mask_token_sent] + additional_special_tokens)
									    if mask_token_sent not in additional_special_tokens and mask_token_sent is not None
									    else additional_special_tokens
									)
									# fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken
									additional_special_tokens_extended += [
									    f'<unk_{i}>' for i in range(len(lowercase )						,  self.offset - 1 )
									]

									if len(set(lowercase ) ) != len(lowercase ):
													raise ValueError(
													    "Please make sure that the provided additional_special_tokens do not contain an incorrectly"
													    f' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' )
									lowerCamelCase_						=			additional_special_tokens_extended
					else:
									lowerCamelCase_						=			[mask_token_sent] if mask_token_sent is not None else []
									additional_special_tokens += [f'<unk_{i}>' for i in range(2						,  self.offset )]

					lowerCamelCase_						=			{} if sp_model_kwargs is None else sp_model_kwargs

					super().__init__(
					    eos_token=lowercase						,  unk_token=lowercase						,  mask_token=lowercase						,  pad_token=lowercase						,  mask_token_sent=lowercase						,  offset=lowercase						,  additional_special_tokens=lowercase						,  sp_model_kwargs=self.sp_model_kwargs						,  **lowercase						,  )
					lowerCamelCase_						=			mask_token_sent
					lowerCamelCase_						=			vocab_file
					lowerCamelCase_						=			spm.SentencePieceProcessor(**self.sp_model_kwargs )
					self.sp_model.Load(lowercase )

					# add special tokens to encoder dict
					lowerCamelCase_						=			{
					    0: self.pad_token,
					    1: self.eos_token,
					}

					if self.mask_token_sent is not None:
									self.encoder.update(
									    {
									        2: self.mask_token_sent,
									        3: self.mask_token,
									    } )

					if self.offset > 0:
									# entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102
									# mask_token_sent is already added to list -> so start at 1
									self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1						,  self.offset - 1 )} )

					lowerCamelCase_						=			{v: k for k, v in self.encoder.items()}



	@property
	def     SCREAMING_SNAKE_CASE_(    self )				->       int:
					return len(self.sp_model ) + self.offset



	def     SCREAMING_SNAKE_CASE_(    self )				->       Dict[str, int]:
					lowerCamelCase_						=			{self.convert_ids_to_tokens(lowercase ): i for i in range(self.vocab_size )}
					vocab.update(self.added_tokens_encoder )
					return vocab



	def __getstate__(    self )				->       str:
					lowerCamelCase_						=			self.__dict__.copy()
					lowerCamelCase_						=			None
					return state



	def __setstate__(    self						,  lowercase )				->       str:
					lowerCamelCase_						=			d

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

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



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase )				->       List[str]:
					return self.sp_model.encode(lowercase						,  out_type=lowercase )



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase )				->       int:
					if token in self.decoder:
									return self.decoder[token]
					elif token in self.added_tokens_decoder:
									return self.added_tokens_decoder[token]
					lowerCamelCase_						=			self.sp_model.piece_to_id(lowercase )
					return sp_id + self.offset



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase )				->       str:
					if index in self.encoder:
									return self.encoder[index]
					elif index in self.added_tokens_encoder:
									return self.added_tokens_encoder[index]
					else:
									lowerCamelCase_						=			self.sp_model.IdToPiece(index - self.offset )
					return token



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase )				->       List[str]:
					lowerCamelCase_						=			[]
					lowerCamelCase_						=			""
					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(lowercase ) + token
													lowerCamelCase_						=			[]
									else:
													current_sub_tokens.append(lowercase )
					out_string += self.sp_model.decode(lowercase )
					return out_string.strip()



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase=False )				->       Optional[Any]:
					return 1



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase )				->       Dict:
					lowerCamelCase_						=			set(self.all_special_ids )  # call it once instead of inside list comp
					all_special_ids.remove(self.unk_token_id )  # <unk> is only sometimes special

					return [1 if x in all_special_ids else 0 for x in seq]



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase = None						,  lowercase = False )				->       List[int]:
					if already_has_special_tokens:
									return self._special_token_mask(lowercase )
					elif token_ids_a is None:
									return self._special_token_mask(lowercase ) + [1]
					else:
									return self._special_token_mask(token_ids_a + token_ids_a ) + [1]



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase=None )				->       List[int]:
					if token_ids_a is None:
									return token_ids_a + [self.eos_token_id]
					# We don't expect to process pairs, but leave the pair logic for API consistency
					return token_ids_a + token_ids_a + [self.eos_token_id]



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase = None )				->       Tuple[str]:
					if not os.path.isdir(lowercase ):
									logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
									return
					lowerCamelCase_						=			os.path.join(
					    lowercase						,  (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )

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

					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


