



import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
				from test_module.custom_tokenization_fast import CustomTokenizerFast



class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  Any       )		->     Tuple:
											# A mock response for an HTTP head request to emulate server down
											A      						=    mock.Mock()
											A      						=    500
											A      						=    {}
											A      						=    HTTPError
											A      						=    {}

											# Download this model to make sure it's in the cache.
											A      						=    BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert'       )

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('requests.Session.request'						, return_value=__UpperCamelCase       ) as mock_head:
																		A      						=    BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert'       )
																		# This check we did call the fake head request
																		mock_head.assert_called()


				@require_tokenizers
				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Union[str, Any]:
											# A mock response for an HTTP head request to emulate server down
											A      						=    mock.Mock()
											A      						=    500
											A      						=    {}
											A      						=    HTTPError
											A      						=    {}

											# Download this model to make sure it's in the cache.
											A      						=    GPTaTokenizerFast.from_pretrained('gpt2'       )

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('requests.Session.request'						, return_value=__UpperCamelCase       ) as mock_head:
																		A      						=    GPTaTokenizerFast.from_pretrained('gpt2'       )
																		# This check we did call the fake head request
																		mock_head.assert_called()


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     List[str]:
											# This test is for deprecated behavior and can be removed in v5
											try:
																		A      						=    tempfile.mktemp()
																		with open(__UpperCamelCase						, 'wb'       ) as f:
																									http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'						, __UpperCamelCase       )

																		A      						=    AlbertTokenizer.from_pretrained(__UpperCamelCase       )
											finally:
																		os.remove(__UpperCamelCase       )

											# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
											# the current folder and have the right name.
											if os.path.isfile('tokenizer.json'       ):
																		# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
																		return
											try:
																		with open('tokenizer.json'						, 'wb'       ) as f:
																									http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json'						, __UpperCamelCase       )
																		A      						=    AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'       )
																		# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
																		self.assertEqual(tokenizer.vocab_size						, 1_000       )
																		# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

											finally:
																		os.remove('tokenizer.json'       )


				def __UpperCamelCase						(							self      :  str       )		->     int:
											# This test is for deprecated behavior and can be removed in v5
											A      						=    AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'       )





@is_staging_test
class        lowerCAmelCase__					(  unittest.TestCase       ):
				A_   :     str								=     ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']


				@classmethod
				def __UpperCamelCase						(							cls      :  Tuple       )		->     Dict:
											A      						=    TOKEN
											HfFolder.save_token(__UpperCamelCase       )


				@classmethod
				def __UpperCamelCase						(							cls      :  Any       )		->     Dict:
											try:
																		delete_repo(token=cls._token						, repo_id='test-tokenizer'       )
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						, repo_id='valid_org/test-tokenizer-org'       )
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						, repo_id='test-dynamic-tokenizer'       )
											except HTTPError:
																		pass


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     List[str]:
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    BertTokenizer(__UpperCamelCase       )

											tokenizer.push_to_hub('test-tokenizer'						, use_auth_token=self._token       )
											A      						=    BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer'''       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )

											# Reset repo
											delete_repo(token=self._token						, repo_id='test-tokenizer'       )

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																		tokenizer.save_pretrained(__UpperCamelCase						, repo_id='test-tokenizer'						, push_to_hub=__UpperCamelCase						, use_auth_token=self._token       )

											A      						=    BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer'''       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    BertTokenizer(__UpperCamelCase       )

											tokenizer.push_to_hub('valid_org/test-tokenizer-org'						, use_auth_token=self._token       )
											A      						=    BertTokenizer.from_pretrained('valid_org/test-tokenizer-org'       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )

											# Reset repo
											delete_repo(token=self._token						, repo_id='valid_org/test-tokenizer-org'       )

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																		tokenizer.save_pretrained(
																		    __UpperCamelCase						, repo_id='valid_org/test-tokenizer-org'						, push_to_hub=__UpperCamelCase						, use_auth_token=self._token       )

											A      						=    BertTokenizer.from_pretrained('valid_org/test-tokenizer-org'       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )


				@require_tokenizers
				def __UpperCamelCase						(							self      :  Any       )		->     Union[str, Any]:
											CustomTokenizer.register_for_auto_class()
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    CustomTokenizer(__UpperCamelCase       )

											# No fast custom tokenizer
											tokenizer.push_to_hub('test-dynamic-tokenizer'						, use_auth_token=self._token       )

											A      						=    AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer'''						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizer'       )

											# Fast and slow custom tokenizer
											CustomTokenizerFast.register_for_auto_class()
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )

																		A      						=    BertTokenizerFast.from_pretrained(__UpperCamelCase       )
																		bert_tokenizer.save_pretrained(__UpperCamelCase       )
																		A      						=    CustomTokenizerFast.from_pretrained(__UpperCamelCase       )

											tokenizer.push_to_hub('test-dynamic-tokenizer'						, use_auth_token=self._token       )

											A      						=    AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer'''						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizerFast'       )
											A      						=    AutoTokenizer.from_pretrained(
											    f'''{USER}/test-dynamic-tokenizer'''						, use_fast=__UpperCamelCase						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizer'       )





class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  List[Any]       )		->     Any:
											A      						=    Trie()
											trie.add('Hello 友達'       )
											self.assertEqual(trie.data						, {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}}       )
											trie.add('Hello'       )
											trie.data
											self.assertEqual(trie.data						, {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}}       )


				def __UpperCamelCase						(							self      :  Dict       )		->     Tuple:
											A      						=    Trie()
											self.assertEqual(trie.split('[CLS] This is a extra_id_100'       )						, ['[CLS] This is a extra_id_100']       )
											trie.add('[CLS]'       )
											trie.add('extra_id_1'       )
											trie.add('extra_id_100'       )
											self.assertEqual(trie.split('[CLS] This is a extra_id_100'       )						, ['[CLS]', ' This is a ', 'extra_id_100']       )


				def __UpperCamelCase						(							self      :  Any       )		->     Optional[int]:
											A      						=    Trie()
											trie.add('A'       )
											self.assertEqual(trie.split('ABC'       )						, ['A', 'BC']       )
											self.assertEqual(trie.split('BCA'       )						, ['BC', 'A']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     str:
											A      						=    Trie()
											trie.add('TOKEN]'       )
											trie.add('[SPECIAL_TOKEN]'       )
											self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]'       )						, ['This is something ', '[SPECIAL_TOKEN]']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Tuple:
											A      						=    Trie()
											trie.add('A'       )
											trie.add('P'       )
											trie.add('[SPECIAL_TOKEN]'       )
											self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]'       )						, ['This is something ', '[SPECIAL_TOKEN]']       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											A      						=    Trie()
											trie.add('AB'       )
											trie.add('B'       )
											trie.add('C'       )
											self.assertEqual(trie.split('ABC'       )						, ['AB', 'C']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     List[Any]:
											A      						=    Trie()
											trie.add('ABC'       )
											trie.add('B'       )
											trie.add('CD'       )
											self.assertEqual(trie.split('ABCD'       )						, ['ABC', 'D']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     List[Any]:
											# Even if the offsets are wrong, we necessarily output correct string
											# parts.
											A      						=    Trie()
											A      						=    trie.cut_text('ABC'						, [0, 0, 2, 1, 2, 3]       )
											self.assertEqual(__UpperCamelCase						, ['AB', 'C']       )




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

__snake_case     :int			       =list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__snake_case     :Optional[int]			       =tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



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





class        lowerCAmelCase__					(  _lowerCamelCase       ):
				A_   :     str								=     'train'
				A_   :     str								=     'dev'





class        lowerCAmelCase__					(  _lowerCamelCase       ):
				A_   :     SquadDataTrainingArguments
				A_   :     List[SquadFeatures]
				A_   :     Split
				A_   :     bool


				def __init__(							self      :  Optional[int]						, __UpperCamelCase      :  SquadDataTrainingArguments						, __UpperCamelCase      :  PreTrainedTokenizer						, __UpperCamelCase      :  Optional[int] = None						, __UpperCamelCase      :  Union[str, Split] = Split.train						, __UpperCamelCase      :  Optional[bool] = False						, __UpperCamelCase      :  Optional[str] = None						, __UpperCamelCase      :  Optional[str] = "pt"						, )		->     Any:
											A      						=    args
											A      						=    is_language_sensitive
											A      						=    SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
											if isinstance(__UpperCamelCase						, __UpperCamelCase       ):
																		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(__UpperCamelCase       ):
																		if os.path.exists(__UpperCamelCase       ) and not args.overwrite_cache:
																									A      						=    time.time()
																									A      						=    torch.load(__UpperCamelCase       )

																									# 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'						, __UpperCamelCase       )
																									A      						=    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      						=    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=__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      						=    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      :  Optional[Any]       )		->     Tuple:
											return len(self.features       )


				def __getitem__(							self      :  Tuple						, __UpperCamelCase      :  List[Any]       )		->     Dict[str, torch.Tensor]:
											# Convert to Tensors and build dataset
											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