




"""simple docstring"""







import collections
import os
from typing import List, Optional, Tuple

from transformers.utils import is_jieba_available, requires_backends


if is_jieba_available():
  import jieba

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


SCREAMING_SNAKE_CASE_	     =       logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_	     =       {'vocab_file': 'vocab.txt'}

SCREAMING_SNAKE_CASE_	     =       {
    'vocab_file': {
        'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt',
    },
}

SCREAMING_SNAKE_CASE_	     =       {
    'openbmb/cpm-ant-10b': 1024,
}





def      __snake_case (				_lowercase    ):


    """simple docstring"""







    UpperCamelCase              =	collections.OrderedDict()
    with open(_lowercase			,'''r'''			,encoding='''utf-8'''    ) as reader:
        UpperCamelCase              =	reader.readlines()
    for index, token in enumerate(_lowercase    ):
        UpperCamelCase              =	token.rstrip('''\n'''    )
        UpperCamelCase              =	index
    return vocab

class 				snake_case_			(					lowerCamelCase_			):







   """simple docstring"""




   def __init__(		self       ,					lowerCamelCase_       ,					lowerCamelCase_="<unk>"       ,					lowerCamelCase_=2_0_0)				->   Any:
       UpperCamelCase              =	vocab
       UpperCamelCase              =	unk_token
       UpperCamelCase              =	max_input_chars_per_word







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Union[str, Any]:
       UpperCamelCase              =	list(lowerCamelCase_)
       if len(lowerCamelCase_) > self.max_input_chars_per_word:
           return [self.unk_token]

       UpperCamelCase              =	0
       UpperCamelCase              =	[]
       while start < len(lowerCamelCase_):
           UpperCamelCase              =	len(lowerCamelCase_)
           UpperCamelCase              =	None
           while start < end:
               UpperCamelCase              =	''''''.join(chars[start:end])
               if substr in self.vocab:
                   UpperCamelCase              =	substr
                   break
               end -= 1
           if cur_substr is None:
               sub_tokens.append(self.unk_token)
               start += 1
           else:
               sub_tokens.append(lowerCamelCase_)
               UpperCamelCase              =	end

       return sub_tokens

class 				snake_case_			(					lowerCamelCase_			):







   """simple docstring"""




   A_				      =       VOCAB_FILES_NAMES
   A_				      =       PRETRAINED_VOCAB_FILES_MAP
   A_				      =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A_				      =       ['''input_ids''', '''attention_mask''']
   A_				      =       False







   def __init__(		self       ,					lowerCamelCase_       ,					lowerCamelCase_="<d>"       ,					lowerCamelCase_="</d>"       ,					lowerCamelCase_="<s>"       ,					lowerCamelCase_="</s>"       ,					lowerCamelCase_="<pad>"       ,					lowerCamelCase_="<unk>"       ,					lowerCamelCase_="</n>"       ,					lowerCamelCase_="</_>"       ,					lowerCamelCase_="left"       ,					**lowerCamelCase_       ,					)				->   List[str]:
       requires_backends(self       ,					['''jieba'''])
       super().__init__(
           bod_token=lowerCamelCase_       ,					eod_token=lowerCamelCase_       ,					bos_token=lowerCamelCase_       ,					eos_token=lowerCamelCase_       ,					pad_token=lowerCamelCase_       ,					unk_token=lowerCamelCase_       ,					line_token=lowerCamelCase_       ,					space_token=lowerCamelCase_       ,					padding_side=lowerCamelCase_       ,					**lowerCamelCase_       ,					)
       UpperCamelCase              =	bod_token
       UpperCamelCase              =	eod_token
       UpperCamelCase              =	load_vocab(lowerCamelCase_)
       UpperCamelCase              =	self.encoder[space_token]
       UpperCamelCase              =	self.encoder[line_token]

       del self.encoder[space_token]
       del self.encoder[line_token]

       UpperCamelCase              =	collections.OrderedDict(sorted(self.encoder.items()       ,					key=lambda lowerCamelCase_: x[1]))
       UpperCamelCase              =	{v: k for k, v in self.encoder.items()}

       UpperCamelCase              =	WordpieceTokenizer(vocab=self.encoder       ,					unk_token=self.unk_token)







   @property
   def   UpperCAmelCase__			(		self)				->   Dict:
       return self.encoder[self.bod_token]







   @property
   def   UpperCAmelCase__			(		self)				->   str:
       return self.encoder[self.eod_token]







   @property
   def   UpperCAmelCase__			(		self)				->   List[Any]:
       return self.encoder["\n"]







   @property
   def   UpperCAmelCase__			(		self)				->   int:
       return len(self.encoder)







   def   UpperCAmelCase__			(		self)				->   Dict:
       return dict(self.encoder       ,					**self.added_tokens_encoder)







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Any:
       UpperCamelCase              =	[]
       for x in jieba.cut(lowerCamelCase_       ,					cut_all=lowerCamelCase_):
           output_tokens.extend(self.wordpiece_tokenizer.tokenize(lowerCamelCase_))
       return output_tokens







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_       ,					**lowerCamelCase_)				->   Tuple:
       UpperCamelCase              =	[i for i in token_ids if i >= 0]
       UpperCamelCase              =	[
           x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
       ]
       return super()._decode(lowerCamelCase_       ,					**lowerCamelCase_)







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Dict:
       return token in self.encoder







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   str:
       return "".join(lowerCamelCase_)







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Optional[int]:
       return self.encoder.get(lowerCamelCase_       ,					self.encoder.get(self.unk_token))







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Dict:
       return self.decoder.get(lowerCamelCase_       ,					self.unk_token)







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_       ,					lowerCamelCase_ = None)				->   Tuple[str]:
       if os.path.isdir(lowerCamelCase_):
           UpperCamelCase              =	os.path.join(
               lowerCamelCase_       ,					(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''])
       else:
           UpperCamelCase              =	(filename_prefix + '''-''' if filename_prefix else '''''') + save_directory
       UpperCamelCase              =	0
       if " " in self.encoder:
           UpperCamelCase              =	self.encoder[''' ''']
           del self.encoder[" "]
       if "\n" in self.encoder:
           UpperCamelCase              =	self.encoder['''\n''']
           del self.encoder["\n"]
       UpperCamelCase              =	collections.OrderedDict(sorted(self.encoder.items()       ,					key=lambda lowerCamelCase_: x[1]))
       with open(lowerCamelCase_       ,					'''w'''       ,					encoding='''utf-8''') as writer:
           for token, token_index in self.encoder.items():
               if index != token_index:
                   logger.warning(
                       F'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'
                       ''' Please check that the vocabulary is not corrupted!''')
                   UpperCamelCase              =	token_index
               writer.write(token + '''\n''')
               index += 1
       return (vocab_file,)







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_       ,					lowerCamelCase_ = None)				->   List[int]:
       if token_ids_a is None:
           return [self.bos_token_id] + token_ids_a
       return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_       ,					lowerCamelCase_ = None       ,					lowerCamelCase_ = False)				->   List[int]:

       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_))
       return [1] + ([0] * len(lowerCamelCase_))

'''simple docstring'''



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


_lowercase          =						logging.get_logger(__name__)

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




@dataclass
class     UpperCAmelCase_	:






						'''simple docstring'''






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






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: str										=  '''train'''
						_lowercase						: Union[str, Any]										=  '''dev'''






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: SquadDataTrainingArguments
						_lowercase						: List[SquadFeatures]
						_lowercase						: Split
						_lowercase						: bool




						def __init__(   self       ,  _lowercase       ,  _lowercase       ,  _lowercase = None       ,  _lowercase = Split.train       ,  _lowercase = False       ,  _lowercase = None       ,  _lowercase = "pt"       ,  ):

												"""simple docstring"""



												_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 ):

												"""simple docstring"""



												return len(self.features )




						def __getitem__(   self       ,  _lowercase ):

												"""simple docstring"""



												_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
