



"""simple docstring"""






import json
import os
import re
import unittest

from transformers import CodeGenTokenizer, CodeGenTokenizerFast
from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_		,   unittest.TestCase   ):


					'''simple docstring'''





					_a   			=							CodeGenTokenizer
					_a   			=							CodeGenTokenizerFast
					_a   			=							True
					_a   			=							{'add_prefix_space': True}
					_a   			=							False



					def 		snake_case       (       self							:  Union[str, Any]     )->					Optional[Any]:
								super().setUp()

								# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
								lowerCamelCase__		:		List[str]			=[
								    '''l''',
								    '''o''',
								    '''w''',
								    '''e''',
								    '''r''',
								    '''s''',
								    '''t''',
								    '''i''',
								    '''d''',
								    '''n''',
								    '''\u0120''',
								    '''\u0120l''',
								    '''\u0120n''',
								    '''\u0120lo''',
								    '''\u0120low''',
								    '''er''',
								    '''\u0120lowest''',
								    '''\u0120newer''',
								    '''\u0120wider''',
								    '''<unk>''',
								    '''<|endoftext|>''',
								]
								lowerCamelCase__		:		Tuple			=dict(zip(lowerCamelCase,  range(len(lowerCamelCase     )     )     )     )
								lowerCamelCase__		:		Optional[int]			=['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
								lowerCamelCase__		:		str			={'''unk_token''': '''<unk>'''}

								lowerCamelCase__		:		str			=os.path.join(self.tmpdirname,  VOCAB_FILES_NAMES['''vocab_file''']     )
								lowerCamelCase__		:		Dict			=os.path.join(self.tmpdirname,  VOCAB_FILES_NAMES['''merges_file''']     )
								with open(self.vocab_file,  '''w''',  encoding='''utf-8'''     ) as fp:
											fp.write(json.dumps(lowerCamelCase     ) + '''\n'''     )
								with open(self.merges_file,  '''w''',  encoding='''utf-8'''     ) as fp:
											fp.write('''\n'''.join(lowerCamelCase     )     )



					def 		snake_case       (       self							:  str,  **lowerCamelCase							:  Optional[Any]     )->					Dict:
								kwargs.update(self.special_tokens_map     )
								return CodeGenTokenizer.from_pretrained(self.tmpdirname,  **lowerCamelCase     )



					def 		snake_case       (       self							:  Dict,  **lowerCamelCase							:  Optional[Any]     )->					Tuple:
								kwargs.update(self.special_tokens_map     )
								return CodeGenTokenizerFast.from_pretrained(self.tmpdirname,  **lowerCamelCase     )



					def 		snake_case       (       self							:  List[str],  lowerCamelCase							:  Union[str, Any]     )->					List[str]:
								lowerCamelCase__		:		str			='''lower newer'''
								lowerCamelCase__		:		Any			='''lower newer'''
								return input_text, output_text



					def 		snake_case       (       self							:  int     )->					int:
								lowerCamelCase__		:		List[str]			=CodeGenTokenizer(self.vocab_file,  self.merges_file,  **self.special_tokens_map     )
								lowerCamelCase__		:		List[Any]			='''lower newer'''
								lowerCamelCase__		:		Union[str, Any]			=['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er''']
								lowerCamelCase__		:		Optional[Any]			=tokenizer.tokenize(lowerCamelCase,  add_prefix_space=lowerCamelCase     )
								self.assertListEqual(lowerCamelCase,  lowerCamelCase     )

								lowerCamelCase__		:		Any			=tokens + [tokenizer.unk_token]
								lowerCamelCase__		:		str			=[14, 15, 10, 9, 3, 2, 15, 19]
								self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase     ),  lowerCamelCase     )



					def 		snake_case       (       self							:  Optional[Any]     )->					Dict:
								if not self.test_rust_tokenizer:
											return

								lowerCamelCase__		:		Dict			=self.get_tokenizer()
								lowerCamelCase__		:		List[str]			=self.get_rust_tokenizer(add_prefix_space=lowerCamelCase     )

								lowerCamelCase__		:		Dict			='''lower newer'''

								# Testing tokenization
								lowerCamelCase__		:		str			=tokenizer.tokenize(lowerCamelCase,  add_prefix_space=lowerCamelCase     )
								lowerCamelCase__		:		str			=rust_tokenizer.tokenize(lowerCamelCase     )
								self.assertListEqual(lowerCamelCase,  lowerCamelCase     )

								# Testing conversion to ids without special tokens
								lowerCamelCase__		:		Tuple			=tokenizer.encode(lowerCamelCase,  add_special_tokens=lowerCamelCase,  add_prefix_space=lowerCamelCase     )
								lowerCamelCase__		:		List[str]			=rust_tokenizer.encode(lowerCamelCase,  add_special_tokens=lowerCamelCase     )
								self.assertListEqual(lowerCamelCase,  lowerCamelCase     )

								# Testing conversion to ids with special tokens
								lowerCamelCase__		:		Any			=self.get_rust_tokenizer(add_prefix_space=lowerCamelCase     )
								lowerCamelCase__		:		Optional[Any]			=tokenizer.encode(lowerCamelCase,  add_prefix_space=lowerCamelCase     )
								lowerCamelCase__		:		str			=rust_tokenizer.encode(lowerCamelCase     )
								self.assertListEqual(lowerCamelCase,  lowerCamelCase     )

								# Testing the unknown token
								lowerCamelCase__		:		List[str]			=tokens + [rust_tokenizer.unk_token]
								lowerCamelCase__		:		Tuple			=[14, 15, 10, 9, 3, 2, 15, 19]
								self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(lowerCamelCase     ),  lowerCamelCase     )



					def 		snake_case       (       self							:  List[str],  *lowerCamelCase							:  Optional[Any],  **lowerCamelCase							:  Optional[Any]     )->					str:
								# It's very difficult to mix/test pretokenization with byte-level
								# And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string)
								pass



					def 		snake_case       (       self							:  Tuple,  lowerCamelCase							:  Tuple=15     )->					Optional[Any]:
								for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
											with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''     ):
														lowerCamelCase__		:		int			=self.rust_tokenizer_class.from_pretrained(lowerCamelCase,  **lowerCamelCase     )

														# Simple input
														lowerCamelCase__		:		Optional[Any]			='''This is a simple input'''
														lowerCamelCase__		:		Optional[int]			=['''This is a simple input 1''', '''This is a simple input 2''']
														lowerCamelCase__		:		Any			=('''This is a simple input''', '''This is a pair''')
														lowerCamelCase__		:		List[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(lowerCamelCase,  tokenizer_r.encode,  lowerCamelCase,  max_length=lowerCamelCase,  padding='''max_length'''     )

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

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

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

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

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



					def 		snake_case       (       self							:  List[Any]     )->					str:
								lowerCamelCase__		:		List[str]			=CodeGenTokenizer.from_pretrained(self.tmpdirname,  pad_token='''<pad>'''     )

								# Simple input
								lowerCamelCase__		:		Dict			='''This is a simple input'''
								lowerCamelCase__		:		Tuple			=['''This is a simple input looooooooong''', '''This is a simple input''']
								lowerCamelCase__		:		Dict			=('''This is a simple input''', '''This is a pair''')
								lowerCamelCase__		:		Dict			=[
								    ('''This is a simple input loooooong''', '''This is a simple input'''),
								    ('''This is a simple pair loooooong''', '''This is a simple pair'''),
								]

								lowerCamelCase__		:		int			=tokenizer.pad_token_id

								lowerCamelCase__		:		str			=tokenizer(lowerCamelCase,  padding='''max_length''',  max_length=30,  return_tensors='''np'''     )
								lowerCamelCase__		:		Any			=tokenizer(lowerCamelCase,  padding=lowerCamelCase,  truncate=lowerCamelCase,  return_tensors='''np'''     )
								lowerCamelCase__		:		List[str]			=tokenizer(*lowerCamelCase,  padding='''max_length''',  max_length=60,  return_tensors='''np'''     )
								lowerCamelCase__		:		Tuple			=tokenizer(lowerCamelCase,  padding=lowerCamelCase,  truncate=lowerCamelCase,  return_tensors='''np'''     )

								# s
								# test single string max_length padding
								self.assertEqual(out_s['''input_ids'''].shape[-1],  30     )
								self.assertTrue(pad_token_id in out_s['''input_ids''']     )
								self.assertTrue(0 in out_s['''attention_mask''']     )

								# s2
								# test automatic padding
								self.assertEqual(out_sa['''input_ids'''].shape[-1],  33     )
								# long slice doesn't have padding
								self.assertFalse(pad_token_id in out_sa['''input_ids'''][0]     )
								self.assertFalse(0 in out_sa['''attention_mask'''][0]     )
								# short slice does have padding
								self.assertTrue(pad_token_id in out_sa['''input_ids'''][1]     )
								self.assertTrue(0 in out_sa['''attention_mask'''][1]     )

								# p
								# test single pair max_length padding
								self.assertEqual(out_p['''input_ids'''].shape[-1],  60     )
								self.assertTrue(pad_token_id in out_p['''input_ids''']     )
								self.assertTrue(0 in out_p['''attention_mask''']     )

								# p2
								# test automatic padding pair
								self.assertEqual(out_pa['''input_ids'''].shape[-1],  52     )
								# long slice pair doesn't have padding
								self.assertFalse(pad_token_id in out_pa['''input_ids'''][0]     )
								self.assertFalse(0 in out_pa['''attention_mask'''][0]     )
								# short slice pair does have padding
								self.assertTrue(pad_token_id in out_pa['''input_ids'''][1]     )
								self.assertTrue(0 in out_pa['''attention_mask'''][1]     )



					def 		snake_case       (       self							:  List[Any]     )->					Any:
								lowerCamelCase__		:		Optional[Any]			='''$$$'''
								lowerCamelCase__		:		Union[str, Any]			=CodeGenTokenizer.from_pretrained(self.tmpdirname,  bos_token=lowerCamelCase,  add_bos_token=lowerCamelCase     )

								lowerCamelCase__		:		Tuple			='''This is a simple input'''
								lowerCamelCase__		:		Optional[int]			=['''This is a simple input 1''', '''This is a simple input 2''']

								lowerCamelCase__		:		Optional[int]			=tokenizer.bos_token_id

								lowerCamelCase__		:		Any			=tokenizer(lowerCamelCase     )
								lowerCamelCase__		:		int			=tokenizer(lowerCamelCase     )

								self.assertEqual(out_s.input_ids[0],  lowerCamelCase     )
								self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids     )     )

								lowerCamelCase__		:		Optional[int]			=tokenizer.decode(out_s.input_ids     )
								lowerCamelCase__		:		Dict			=tokenizer.batch_decode(out_sa.input_ids     )

								self.assertEqual(decode_s.split()[0],  lowerCamelCase     )
								self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa     )     )



					@slow
					def 		snake_case       (       self							:  int     )->					str:
								lowerCamelCase__		:		Any			=CodeGenTokenizer.from_pretrained('''Salesforce/codegen-350M-mono'''     )

								lowerCamelCase__		:		Dict			='''\nif len_a > len_b:\n    result = a\nelse:\n    result = b\n\n\n\n#'''
								lowerCamelCase__		:		Union[str, Any]			='''\nif len_a > len_b:      result = a\nelse:      result = b'''

								lowerCamelCase__		:		Optional[Any]			=tokenizer.encode(lowerCamelCase     )
								lowerCamelCase__		:		int			=['''^#''', re.escape('''<|endoftext|>'''     ), '''^\'\'\'''', '''^"""''', '''\n\n\n''']
								lowerCamelCase__		:		int			=tokenizer.decode(lowerCamelCase,  truncate_before_pattern=lowerCamelCase     )
								self.assertEqual(lowerCamelCase,  lowerCamelCase     )




					def 		snake_case       (       self							:  Tuple     )->					Optional[Any]:
								pass









"""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 : Optional[int]      						=						logging.get_logger(__name__)

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

@dataclass
class        __SCREAMING_SNAKE_CASE	:


					'''simple docstring'''





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





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							'train'
					_a   			=							'dev'





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							42
					_a   			=							42
					_a   			=							42
					_a   			=							42



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

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

														lowerCamelCase__	,   lowerCamelCase__		:		List[str]			=squad_convert_examples_to_features(
														    examples=self.examples,  tokenizer=lowerCamelCase,  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=lowerCamelCase,  )

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




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

								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.input_ids,  dtype=torch.long     )
								lowerCamelCase__		:		List[str]			=torch.tensor(feature.attention_mask,  dtype=torch.long     )
								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.token_type_ids,  dtype=torch.long     )
								lowerCamelCase__		:		Optional[int]			=torch.tensor(feature.cls_index,  dtype=torch.long     )
								lowerCamelCase__		:		Optional[int]			=torch.tensor(feature.p_mask,  dtype=torch.float     )
								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.is_impossible,  dtype=torch.float     )

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

								return inputs




