





"""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


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 				__lowercase			:







     '''simple docstring'''




     __lowerCAmelCase  =  field(
         default=_UpperCamelCase   ,      metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(_UpperCamelCase							)}							)
     __lowerCAmelCase  =  field(
         default=_UpperCamelCase   ,      metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}							)
     __lowerCAmelCase  =  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.'''
             )
         }   ,      )
     __lowerCAmelCase  =  field(
         default=128   ,      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=_UpperCamelCase   ,      metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}							)
     __lowerCAmelCase  =  field(
         default=_UpperCamelCase   ,      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 				__lowercase			(			_UpperCamelCase							):







     '''simple docstring'''




     __lowerCAmelCase  =  '''train'''
     __lowerCAmelCase  =  '''dev'''






class 				__lowercase			(			_UpperCamelCase							):







     '''simple docstring'''




     __lowerCAmelCase  =  42
     __lowerCAmelCase  =  42
     __lowerCAmelCase  =  42
     __lowerCAmelCase  =  42







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

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

                 __a :						Union[str, Any]			       =  squad_convert_examples_to_features(
                     examples=self.examples	,			tokenizer=_UpperCAmelCase	,			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=_UpperCAmelCase	,			)

                 __a :						Optional[int]			       =  time.time()
                 torch.save(
                     {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}	,			_UpperCAmelCase	,			)
                 # ^ 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     ):
         return len(self.features     )







     def __getitem__(						self	,			_UpperCAmelCase     ):
         __a :						List[str]			       =  self.features[i]

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

         __a :						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:
             __a :						Any			       =  torch.tensor(feature.start_position	,			dtype=torch.long     )
             __a :						str			       =  torch.tensor(feature.end_position	,			dtype=torch.long     )
             inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}     )

         return inputs






"""simple docstring"""






import json
import os
import unittest

from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast
from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin




@require_tokenizers
class 				__lowercase			(			_UpperCamelCase   ,      unittest.TestCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  OpenAIGPTTokenizer
					__lowerCAmelCase  =  OpenAIGPTTokenizerFast
					__lowerCAmelCase  =  True
					__lowerCAmelCase  =  False







					def  _lowerCamelCase		(						self     ):
									super().setUp()

									# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
									__a :						List[str]			       =  [
									    '''l''',
									    '''o''',
									    '''w''',
									    '''e''',
									    '''r''',
									    '''s''',
									    '''t''',
									    '''i''',
									    '''d''',
									    '''n''',
									    '''w</w>''',
									    '''r</w>''',
									    '''t</w>''',
									    '''lo''',
									    '''low''',
									    '''er</w>''',
									    '''low</w>''',
									    '''lowest</w>''',
									    '''newer</w>''',
									    '''wider</w>''',
									    '''<unk>''',
									]
									__a :						str			       =  dict(zip(_UpperCAmelCase	,			range(len(_UpperCAmelCase     )     )     )     )
									__a :						List[Any]			       =  ['''#version: 0.2''', '''l o''', '''lo w''', '''e r</w>''', '''''']

									__a :						Union[str, Any]			       =  os.path.join(self.tmpdirname	,			VOCAB_FILES_NAMES['''vocab_file''']     )
									__a :						Dict			       =  os.path.join(self.tmpdirname	,			VOCAB_FILES_NAMES['''merges_file''']     )
									with open(self.vocab_file	,			'''w'''     ) as fp:
													fp.write(json.dumps(_UpperCAmelCase     )     )
									with open(self.merges_file	,			'''w'''     ) as fp:
													fp.write('''\n'''.join(_UpperCAmelCase     )     )







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase     ):
									return "lower newer", "lower newer"







					def  _lowerCamelCase		(						self     ):
									__a :						Tuple			       =  OpenAIGPTTokenizer(self.vocab_file	,			self.merges_file     )

									__a :						Tuple			       =  '''lower'''
									__a :						Union[str, Any]			       =  ['''low''', '''er</w>''']
									__a :						str			       =  tokenizer.tokenize(_UpperCAmelCase     )
									self.assertListEqual(_UpperCAmelCase	,			_UpperCAmelCase     )

									__a :						List[Any]			       =  tokens + ['''<unk>''']
									__a :						Tuple			       =  [14, 15, 20]
									self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase     )	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase=15     ):
									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
													with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""     ):
																	__a :						Any			       =  self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase	,			**_UpperCAmelCase     )

																	# Simple input
																	__a :						str			       =  '''This is a simple input'''
																	__a :						Dict			       =  ['''This is a simple input 1''', '''This is a simple input 2''']
																	__a :						List[Any]			       =  ('''This is a simple input''', '''This is a pair''')
																	__a :						Optional[Any]			       =  [
																	    ('''This is a simple input 1''', '''This is a simple input 2'''),
																	    ('''This is a simple pair 1''', '''This is a simple pair 2'''),
																	]

																	# Simple input tests
																	self.assertRaises(_UpperCAmelCase	,			tokenizer_r.encode	,			_UpperCAmelCase	,			max_length=_UpperCAmelCase	,			padding='''max_length'''     )

																	# Simple input
																	self.assertRaises(_UpperCAmelCase	,			tokenizer_r.encode_plus	,			_UpperCAmelCase	,			max_length=_UpperCAmelCase	,			padding='''max_length'''     )

																	# Simple input
																	self.assertRaises(
																	    _UpperCAmelCase	,			tokenizer_r.batch_encode_plus	,			_UpperCAmelCase	,			max_length=_UpperCAmelCase	,			padding='''max_length'''	,			)

																	# Pair input
																	self.assertRaises(_UpperCAmelCase	,			tokenizer_r.encode	,			_UpperCAmelCase	,			max_length=_UpperCAmelCase	,			padding='''max_length'''     )

																	# Pair input
																	self.assertRaises(_UpperCAmelCase	,			tokenizer_r.encode_plus	,			_UpperCAmelCase	,			max_length=_UpperCAmelCase	,			padding='''max_length'''     )

																	# Pair input
																	self.assertRaises(
																	    _UpperCAmelCase	,			tokenizer_r.batch_encode_plus	,			_UpperCAmelCase	,			max_length=_UpperCAmelCase	,			padding='''max_length'''	,			)







					def  _lowerCamelCase		(						self     ):
									pass






@require_ftfy
@require_spacy
@require_tokenizers
class 				__lowercase			(			_UpperCamelCase							):







					'''simple docstring'''




					pass