


import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
    A   :					List[str]	=      "pt"
elif is_tf_available():
    A   :					str	=      "tf"
else:
    A   :					str	=      "jax"







class     _lowercase				(							lowercase__							,						unittest.TestCase):


       """simple docstring"""




       A__      		=    PerceiverTokenizer
       A__      		=    False





       def 		lowerCAmelCase  (     self							:    List[Any] ):


             '''simple docstring'''



             super().setUp()
             lowerCamelCase__	:       Tuple					=						PerceiverTokenizer()
             tokenizer.save_pretrained(self.tmpdirname )





       @cached_property
       def 		lowerCAmelCase  (     self							:    List[str] ):


             '''simple docstring'''



             return PerceiverTokenizer.from_pretrained("deepmind/language-perceiver" )





       def 		lowerCAmelCase  (     self							:    Union[str, Any]      ,   **__lowerCamelCase							:    str ):


             '''simple docstring'''



             return self.tokenizer_class.from_pretrained(self.tmpdirname      ,   **__lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Any      ,   __lowerCamelCase							:    Union[str, Any]      ,   __lowerCamelCase							:    Dict=False      ,   __lowerCamelCase							:    int=20      ,   __lowerCamelCase							:    Optional[Any]=5 ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						[]
             for i in range(len(__lowerCamelCase ) ):
                   try:
                         lowerCamelCase__	:       Any					=						tokenizer.decode([i]      ,   clean_up_tokenization_spaces=__lowerCamelCase )
                   except UnicodeDecodeError:
                         pass
                   toks.append((i, tok) )

             lowerCamelCase__	:       Union[str, Any]					=						list(filter(lambda __lowerCamelCase : re.match(R"^[ a-zA-Z]+$"      ,   t[1] )      ,   __lowerCamelCase ) )
             lowerCamelCase__	:       List[str]					=						list(filter(lambda __lowerCamelCase : [t[0]] == tokenizer.encode(t[1]      ,   add_special_tokens=__lowerCamelCase )      ,   __lowerCamelCase ) )
             if max_length is not None and len(__lowerCamelCase ) > max_length:
                   lowerCamelCase__	:       Union[str, Any]					=						toks[:max_length]
             if min_length is not None and len(__lowerCamelCase ) < min_length and len(__lowerCamelCase ) > 0:
                   while len(__lowerCamelCase ) < min_length:
                         lowerCamelCase__	:       Dict					=						toks + toks
        # toks_str = [t[1] for t in toks]
             lowerCamelCase__	:       Tuple					=						[t[0] for t in toks]

             # Ensure consistency
             lowerCamelCase__	:       Optional[int]					=						tokenizer.decode(__lowerCamelCase      ,   clean_up_tokenization_spaces=__lowerCamelCase )
             if " " not in output_txt and len(__lowerCamelCase ) > 1:
                   lowerCamelCase__	:       Any					=						(
                       tokenizer.decode([toks_ids[0]]      ,   clean_up_tokenization_spaces=__lowerCamelCase )
                       + " "
                       + tokenizer.decode(toks_ids[1:]      ,   clean_up_tokenization_spaces=__lowerCamelCase )
                   )
             if with_prefix_space:
                   lowerCamelCase__	:       Union[str, Any]					=						" " + output_txt
             lowerCamelCase__	:       List[Any]					=						tokenizer.encode(__lowerCamelCase      ,   add_special_tokens=__lowerCamelCase )
             return output_txt, output_ids





       def 		lowerCAmelCase  (     self							:    Optional[int] ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[int]					=						self.perceiver_tokenizer
             lowerCamelCase__	:       Optional[Any]					=						"Unicode €."
             lowerCamelCase__	:       Dict					=						tokenizer(__lowerCamelCase )
             lowerCamelCase__	:       List[str]					=						[4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5]
             self.assertEqual(encoded["input_ids"]      ,   __lowerCamelCase )

             # decoding
             lowerCamelCase__	:       Any					=						tokenizer.decode(__lowerCamelCase )
             self.assertEqual(__lowerCamelCase      ,   "[CLS]Unicode €.[SEP]" )

             lowerCamelCase__	:       int					=						tokenizer("e è é ê ë" )
             lowerCamelCase__	:       List[Any]					=						[4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5]
             self.assertEqual(encoded["input_ids"]      ,   __lowerCamelCase )
             # decoding
             lowerCamelCase__	:       str					=						tokenizer.decode(__lowerCamelCase )
             self.assertEqual(__lowerCamelCase      ,   "[CLS]e è é ê ë[SEP]" )

             # encode/decode, but with `encode` instead of `__call__`
             self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë" ) )      ,   "[CLS]e è é ê ë[SEP]" )





       def 		lowerCAmelCase  (     self							:    Dict ):


             '''simple docstring'''



             lowerCamelCase__	:       Union[str, Any]					=						self.perceiver_tokenizer
             lowerCamelCase__	:       Optional[int]					=						["A long paragraph for summarization.", "Another paragraph for summarization."]
             # fmt: off
             lowerCamelCase__	:       Any					=						[4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0]
             # fmt: on
             lowerCamelCase__	:       str					=						tokenizer(__lowerCamelCase      ,   padding=__lowerCamelCase      ,   return_tensors=__lowerCamelCase )
             self.assertIsInstance(__lowerCamelCase      ,   __lowerCamelCase )

             if FRAMEWORK != "jax":
                   lowerCamelCase__	:       Union[str, Any]					=						list(batch.input_ids.numpy()[0] )
             else:
                   lowerCamelCase__	:       int					=						list(batch.input_ids.tolist()[0] )

             self.assertListEqual(__lowerCamelCase      ,   __lowerCamelCase )

             self.assertEqual((2, 38)      ,   batch.input_ids.shape )
             self.assertEqual((2, 38)      ,   batch.attention_mask.shape )





       def 		lowerCAmelCase  (     self							:    List[str] ):


             '''simple docstring'''



             lowerCamelCase__	:       Union[str, Any]					=						self.perceiver_tokenizer
             lowerCamelCase__	:       Optional[int]					=						["A long paragraph for summarization.", "Another paragraph for summarization."]
             lowerCamelCase__	:       List[Any]					=						tokenizer(__lowerCamelCase      ,   padding=__lowerCamelCase      ,   return_tensors=__lowerCamelCase )
             # check if input_ids are returned and no decoder_input_ids
             self.assertIn("input_ids"      ,   __lowerCamelCase )
             self.assertIn("attention_mask"      ,   __lowerCamelCase )
             self.assertNotIn("decoder_input_ids"      ,   __lowerCamelCase )
             self.assertNotIn("decoder_attention_mask"      ,   __lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						self.perceiver_tokenizer
             lowerCamelCase__	:       Tuple					=						[
                 "Summary of the text.",
                 "Another summary.",
             ]
             lowerCamelCase__	:       List[Any]					=						tokenizer(
                 text_target=__lowerCamelCase      ,   max_length=32      ,   padding="max_length"      ,   truncation=__lowerCamelCase      ,   return_tensors=__lowerCamelCase )
             self.assertEqual(32      ,   targets["input_ids"].shape[1] )





       def 		lowerCAmelCase  (     self							:    Dict ):


             '''simple docstring'''



             lowerCamelCase__	:       Union[str, Any]					=						self.get_tokenizers()
             for tokenizer in tokenizers:
                   with self.subTest(f"{tokenizer.__class__.__name__}" ):
                         self.assertNotEqual(tokenizer.model_max_length      ,   42 )

        # Now let's start the test
             lowerCamelCase__	:       List[str]					=						self.get_tokenizers()
             for tokenizer in tokenizers:
                   with self.subTest(f"{tokenizer.__class__.__name__}" ):
                         # Isolate this from the other tests because we save additional tokens/etc
                         lowerCamelCase__	:       int					=						tempfile.mkdtemp()

                         lowerCamelCase__	:       List[Any]					=						" He is very happy, UNwant\u00E9d,running"
                         lowerCamelCase__	:       Any					=						tokenizer.encode(__lowerCamelCase      ,   add_special_tokens=__lowerCamelCase )
                         tokenizer.save_pretrained(__lowerCamelCase )

                         lowerCamelCase__	:       Optional[int]					=						tokenizer.__class__.from_pretrained(__lowerCamelCase )
                         lowerCamelCase__	:       str					=						after_tokenizer.encode(__lowerCamelCase      ,   add_special_tokens=__lowerCamelCase )
                         self.assertListEqual(__lowerCamelCase      ,   __lowerCamelCase )

                         shutil.rmtree(__lowerCamelCase )

             lowerCamelCase__	:       int					=						self.get_tokenizers(model_max_length=42 )
             for tokenizer in tokenizers:
                   with self.subTest(f"{tokenizer.__class__.__name__}" ):
                         # Isolate this from the other tests because we save additional tokens/etc
                         lowerCamelCase__	:       str					=						tempfile.mkdtemp()

                         lowerCamelCase__	:       Optional[Any]					=						" He is very happy, UNwant\u00E9d,running"
                         tokenizer.add_tokens(["bim", "bambam"] )
                         lowerCamelCase__	:       List[str]					=						tokenizer.additional_special_tokens
                         additional_special_tokens.append("new_additional_special_token" )
                         tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} )
                         lowerCamelCase__	:       Union[str, Any]					=						tokenizer.encode(__lowerCamelCase      ,   add_special_tokens=__lowerCamelCase )
                         tokenizer.save_pretrained(__lowerCamelCase )

                         lowerCamelCase__	:       Union[str, Any]					=						tokenizer.__class__.from_pretrained(__lowerCamelCase )
                         lowerCamelCase__	:       Union[str, Any]					=						after_tokenizer.encode(__lowerCamelCase      ,   add_special_tokens=__lowerCamelCase )
                         self.assertListEqual(__lowerCamelCase      ,   __lowerCamelCase )
                         self.assertIn("new_additional_special_token"      ,   after_tokenizer.additional_special_tokens )
                         self.assertEqual(after_tokenizer.model_max_length      ,   42 )

                         lowerCamelCase__	:       Any					=						tokenizer.__class__.from_pretrained(__lowerCamelCase      ,   model_max_length=43 )
                         self.assertEqual(tokenizer.model_max_length      ,   43 )

                         shutil.rmtree(__lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Optional[int] ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						[]
             if self.test_slow_tokenizer:
                   tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )

             if self.test_rust_tokenizer:
                   tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )

             for tokenizer_class, tokenizer_utils in tokenizer_list:
                   with tempfile.TemporaryDirectory() as tmp_dir:
                         tokenizer_utils.save_pretrained(__lowerCamelCase )

                         with open(os.path.join(__lowerCamelCase      ,   "special_tokens_map.json" )      ,   encoding="utf-8" ) as json_file:
                               lowerCamelCase__	:       Union[str, Any]					=						json.load(__lowerCamelCase )

                         with open(os.path.join(__lowerCamelCase      ,   "tokenizer_config.json" )      ,   encoding="utf-8" ) as json_file:
                               lowerCamelCase__	:       List[str]					=						json.load(__lowerCamelCase )

                         lowerCamelCase__	:       int					=						[f"<extra_id_{i}>" for i in range(125 )]

                         lowerCamelCase__	:       List[Any]					=						added_tokens_extra_ids + [
                             "an_additional_special_token"
                         ]
                         lowerCamelCase__	:       List[str]					=						added_tokens_extra_ids + [
                             "an_additional_special_token"
                         ]

                         with open(os.path.join(__lowerCamelCase      ,   "special_tokens_map.json" )      ,   "w"      ,   encoding="utf-8" ) as outfile:
                               json.dump(__lowerCamelCase      ,   __lowerCamelCase )
                         with open(os.path.join(__lowerCamelCase      ,   "tokenizer_config.json" )      ,   "w"      ,   encoding="utf-8" ) as outfile:
                               json.dump(__lowerCamelCase      ,   __lowerCamelCase )

                         # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
                         # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
                         # "special_tokens_map.json" files
                         lowerCamelCase__	:       List[Any]					=						tokenizer_class.from_pretrained(
                             __lowerCamelCase      ,   )
                         self.assertIn(
                             "an_additional_special_token"      ,   tokenizer_without_change_in_init.additional_special_tokens )
                         self.assertEqual(
                             ["an_additional_special_token"]      ,   tokenizer_without_change_in_init.convert_ids_to_tokens(
                                 tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"] ) )      ,   )

                         # Now we test that we can change the value of additional_special_tokens in the from_pretrained
                         lowerCamelCase__	:       int					=						added_tokens_extra_ids + [AddedToken("a_new_additional_special_token"      ,   lstrip=__lowerCamelCase )]
                         lowerCamelCase__	:       Any					=						tokenizer_class.from_pretrained(
                             __lowerCamelCase      ,   additional_special_tokens=__lowerCamelCase      ,   )

                         self.assertIn("a_new_additional_special_token"      ,   tokenizer.additional_special_tokens )
                         self.assertEqual(
                             ["a_new_additional_special_token"]      ,   tokenizer.convert_ids_to_tokens(
                                 tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"] ) )      ,   )





       def 		lowerCAmelCase  (     self							:    int ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						self.perceiver_tokenizer
             self.assertEqual(tokenizer.decode([178] )      ,   "�" )





       def 		lowerCAmelCase  (     self							:    str ):


             '''simple docstring'''



             pass





       def 		lowerCAmelCase  (     self							:    Optional[Any] ):


             '''simple docstring'''



             pass





       def 		lowerCAmelCase  (     self							:    int ):


             '''simple docstring'''



             pass





       def 		lowerCAmelCase  (     self							:    str ):


             '''simple docstring'''



             pass





       def 		lowerCAmelCase  (     self							:    Union[str, Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[int]					=						self.get_tokenizers(fast=__lowerCamelCase      ,   do_lower_case=__lowerCamelCase )
             for tokenizer in tokenizers:
                   with self.subTest(f"{tokenizer.__class__.__name__}" ):
                         lowerCamelCase__	:       Union[str, Any]					=						["[CLS]", "t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t", "[SEP]"]
                         lowerCamelCase__	:       str					=						tokenizer.convert_tokens_to_string(__lowerCamelCase )

                         self.assertIsInstance(__lowerCamelCase      ,   __lowerCamelCase )






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

A   :					Union[str, Any]	=      list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
A   :					Optional[Any]	=      tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class     _lowercase				:


       """simple docstring"""




       A__      		=    field(
           default=lowercase__							,						metadata={"help": "Model type selected in the list: " + ", ".join(lowercase__)})
       A__      		=    field(
           default=lowercase__							,						metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."})
       A__      		=    field(
           default=1_28							,						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_28							,						metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}							,						)
       A__      		=    field(
           default=64							,						metadata={
               "help": (
                   "The maximum number of tokens for the question. Questions longer than this will "
                   "be truncated to this length."
               )
           }							,						)
       A__      		=    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."
               )
           }							,						)
       A__      		=    field(
           default=lowercase__							,						metadata={"help": "Overwrite the cached training and evaluation sets"})
       A__      		=    field(
           default=lowercase__							,						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=20							,						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     _lowercase				(							lowercase__):


       """simple docstring"""




       A__      		=    "train"
       A__      		=    "dev"







class     _lowercase				(							lowercase__):


       """simple docstring"""




       A__      		=    42
       A__      		=    42
       A__      		=    42
       A__      		=    42





       def __init__(     self							:    Optional[int]      ,   __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"      ,   ):


             '''simple docstring'''



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

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

                         lowerCamelCase__					,     lowerCamelCase__	:       Tuple					=						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__	:       int					=						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							:    List[Any] ):


             '''simple docstring'''



             return len(self.features )





       def __getitem__(     self							:    List[str]      ,   __lowerCamelCase							:    Union[str, Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						self.features[i]

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

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

             return inputs


