



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


__snake_case		:int   	=  logging.get_logger(__name__)

__snake_case		:Dict   	=  list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__snake_case		:str   	=  tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

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


class 					_A (			__SCREAMING_SNAKE_CASE					):
       UpperCamelCase__						:					Union[str, Any]		      =		'train'
       UpperCamelCase__						:					List[Any]		      =		'dev'


class 					_A (			__SCREAMING_SNAKE_CASE					):
       UpperCamelCase__						:					SquadDataTrainingArguments
       UpperCamelCase__						:					List[SquadFeatures]
       UpperCamelCase__						:					Split
       UpperCamelCase__						:					bool



       def __init__(	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]  ,	__SCREAMING_SNAKE_CASE							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  Tuple = None  ,	__SCREAMING_SNAKE_CASE							:  Tuple = Split.train  ,	__SCREAMING_SNAKE_CASE							:  List[Any] = False  ,	__SCREAMING_SNAKE_CASE							:  Dict = None  ,	__SCREAMING_SNAKE_CASE							:  int = "pt"  ,	):


           '''simple docstring'''

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

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

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

                   __a		 =       time.time()
                   torch.save(
                       {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}  ,	_a  ,	)
                   # ^ 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):


           '''simple docstring'''

           return len(self.features)





       def __getitem__(	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  List[str]):


           '''simple docstring'''

           __a		 =       self.features[i]

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

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

           return inputs










import unittest

from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


__snake_case		:Dict   	=  get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''')

@require_sentencepiece
@require_tokenizers
class 					_A (			__UpperCAmelCase   ,unittest.TestCase					):
       UpperCamelCase__						:					List[str]		      =		GPTSwaTokenizer
       UpperCamelCase__						:					Dict		      =		False
       UpperCamelCase__						:					int		      =		True
       UpperCamelCase__						:					List[Any]		      =		False



       def 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           super().setUp()

           # We have a SentencePiece fixture for testing
           __a		 =       GPTSwaTokenizer(__SCREAMING_SNAKE_CASE  ,	eos_token='''<unk>'''  ,	bos_token='''<unk>'''  ,	pad_token='''<unk>''')

           tokenizer.save_pretrained(self.tmpdirname)



       def 	_lowerCamelCase    (	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  int):


           '''simple docstring'''

           __a		 =       '''This is a test'''
           __a		 =       '''This is a test'''
           return input_text, output_text



       def 	_lowerCamelCase    (	self							:  Dict):


           '''simple docstring'''

           __a		 =       '''<s>'''
           __a		 =       1

           self.assertEqual(self.get_tokenizer()._convert_token_to_id(__SCREAMING_SNAKE_CASE)  ,	__SCREAMING_SNAKE_CASE)
           self.assertEqual(self.get_tokenizer()._convert_id_to_token(__SCREAMING_SNAKE_CASE)  ,	__SCREAMING_SNAKE_CASE)



       def 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           __a		 =       list(self.get_tokenizer().get_vocab().keys())

           self.assertEqual(vocab_keys[0]  ,	'''<unk>''')
           self.assertEqual(vocab_keys[1]  ,	'''<s>''')
           self.assertEqual(vocab_keys[-1]  ,	'''j''')
           self.assertEqual(len(__SCREAMING_SNAKE_CASE)  ,	2_000)



       def 	_lowerCamelCase    (	self							:  Dict):


           '''simple docstring'''

           self.assertEqual(self.get_tokenizer().vocab_size  ,	2_000)



       def 	_lowerCamelCase    (	self							:  List[str]):


           '''simple docstring'''

           __a		 =       GPTSwaTokenizer(__SCREAMING_SNAKE_CASE)

           __a		 =       tokenizer.tokenize('''This is a test''')
           self.assertListEqual(__SCREAMING_SNAKE_CASE  ,	['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''])

           self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE)  ,	[465, 287, 265, 631, 842])

           __a		 =       tokenizer.tokenize('''I was born in 92000, and this is falsé.''')
           # fmt: off
           self.assertListEqual(
               __SCREAMING_SNAKE_CASE  ,	['''▁I''', '''▁was''', '''▁bor''', '''n''', '''▁in''', '''▁''', '''<0x39>''', '''2''', '''0''', '''0''', '''0''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁f''', '''al''', '''s''', '''<0xC3>''', '''<0xA9>''', '''.''']  ,	)
           # fmt: on

           __a		 =       tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE)
           self.assertListEqual(
               __SCREAMING_SNAKE_CASE  ,	[262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260]  ,	)

           __a		 =       tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE)
           # fmt: off
           self.assertListEqual(
               __SCREAMING_SNAKE_CASE  ,	['''▁I''', '''▁was''', '''▁bor''', '''n''', '''▁in''', '''▁''', '''<0x39>''', '''2''', '''0''', '''0''', '''0''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁f''', '''al''', '''s''', '''<0xC3>''', '''<0xA9>''', '''.'''])
           # fmt: on



       def 	_lowerCamelCase    (	self							:  Any):


           '''simple docstring'''

           __a		 =       GPTSwaTokenizer(__SCREAMING_SNAKE_CASE)
           __a		 =       ['''This is a test''', '''I was born in 92000, and this is falsé.''']
           __a		 =       [
               [465, 287, 265, 631, 842],
               [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
           ]

           # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
           for text, expected_ids in zip(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE):
               self.assertListEqual(tokenizer.encode_fast(__SCREAMING_SNAKE_CASE)  ,	__SCREAMING_SNAKE_CASE)

           # Test that decode_fast returns the input text
           for text, token_ids in zip(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE):
               self.assertEqual(tokenizer.decode_fast(__SCREAMING_SNAKE_CASE)  ,	__SCREAMING_SNAKE_CASE)





       @slow
       def 	_lowerCamelCase    (	self							:  Any):


           '''simple docstring'''

           __a		 =       [
               '''<|python|>def fibonacci(n)\n    if n < 0:\n        print(\'Incorrect input\')''',
               '''Hey there, how are you doing this fine day?''',
               '''This is a text with a trailing spaces followed by a dot     .''',
               '''Häj sväjs lillebrör! =)''',
               '''Det är inget fel på Mr. Cool''',
           ]

           # fmt: off
           __a		 =       {'''input_ids''': [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}
           # fmt: on
           self.tokenizer_integration_test_util(
               expected_encoding=__SCREAMING_SNAKE_CASE  ,	model_name='''AI-Sweden/gpt-sw3-126m'''  ,	sequences=__SCREAMING_SNAKE_CASE  ,	)





