
"""simple docstring"""




from __future__ import annotations

import unittest

from transformers import DebertaVaConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      TFDebertaVaForMaskedLM,
      TFDebertaVaForQuestionAnswering,
      TFDebertaVaForSequenceClassification,
      TFDebertaVaForTokenClassification,
      TFDebertaVaModel,
  )


class 			__magic_name__       :
       def __init__(     self ,				A_ ,				A_=13 ,				A_=7 ,				A_=True ,				A_=True ,				A_=True ,				A_=True ,				A_=99 ,				A_=32 ,				A_=2 ,				A_=4 ,				A_=37 ,				A_="gelu" ,				A_=0.1 ,				A_=0.1 ,				A_=512 ,				A_=16 ,				A_=2 ,				A_=0.02 ,				A_=False ,				A_=True ,				A_="None" ,				A_=3 ,				A_=4 ,				A_=None ,				)     ->	Any:





         """simple docstring"""




         _lowercase:			int       =     parent
         _lowercase:			Union[str, Any]       =     batch_size
         _lowercase:			Dict       =     seq_length
         _lowercase:			List[str]       =     is_training
         _lowercase:			Optional[int]       =     use_input_mask
         _lowercase:			Union[str, Any]       =     use_token_type_ids
         _lowercase:			Optional[Any]       =     use_labels
         _lowercase:			Dict       =     vocab_size
         _lowercase:			Union[str, Any]       =     hidden_size
         _lowercase:			Union[str, Any]       =     num_hidden_layers
         _lowercase:			Optional[Any]       =     num_attention_heads
         _lowercase:			List[Any]       =     intermediate_size
         _lowercase:			List[str]       =     hidden_act
         _lowercase:			Optional[Any]       =     hidden_dropout_prob
         _lowercase:			Tuple       =     attention_probs_dropout_prob
         _lowercase:			Optional[Any]       =     max_position_embeddings
         _lowercase:			Union[str, Any]       =     type_vocab_size
         _lowercase:			Any       =     type_sequence_label_size
         _lowercase:			Union[str, Any]       =     initializer_range
         _lowercase:			Optional[int]       =     num_labels
         _lowercase:			Optional[Any]       =     num_choices
         _lowercase:			List[Any]       =     relative_attention
         _lowercase:			int       =     position_biased_input
         _lowercase:			str       =     pos_att_type
         _lowercase:			Any       =     scope
       def 							lowercase_							(     self       )     ->	Dict:





         """simple docstring"""




         _lowercase:			Optional[int]       =     ids_tensor([self.batch_size, self.seq_length] ,				self.vocab_size       )

         _lowercase:			Optional[Any]       =     None
         if self.use_input_mask:
           _lowercase:			Dict       =     random_attention_mask([self.batch_size, self.seq_length]       )

         _lowercase:			str       =     None
         if self.use_token_type_ids:
           _lowercase:			Any       =     ids_tensor([self.batch_size, self.seq_length] ,				self.type_vocab_size       )

         _lowercase:			int       =     None
         _lowercase:			Dict       =     None
         _lowercase:			Any       =     None
         if self.use_labels:
           _lowercase:			Union[str, Any]       =     ids_tensor([self.batch_size] ,				self.type_sequence_label_size       )
           _lowercase:			Optional[int]       =     ids_tensor([self.batch_size, self.seq_length] ,				self.num_labels       )

         _lowercase:			Dict       =     DebertaVaConfig(
             vocab_size=self.vocab_size ,				hidden_size=self.hidden_size ,				num_hidden_layers=self.num_hidden_layers ,				num_attention_heads=self.num_attention_heads ,				intermediate_size=self.intermediate_size ,				hidden_act=self.hidden_act ,				hidden_dropout_prob=self.hidden_dropout_prob ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob ,				max_position_embeddings=self.max_position_embeddings ,				type_vocab_size=self.type_vocab_size ,				relative_attention=self.relative_attention ,				position_biased_input=self.position_biased_input ,				initializer_range=self.initializer_range ,				return_dict=A_ ,				)

         return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			str       =     TFDebertaVaModel(config=A_       )
         _lowercase:			Dict       =     {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}

         _lowercase:			Dict       =     [input_ids, input_mask]
         _lowercase:			Any       =     model(A_       )

         _lowercase:			Dict       =     model(A_       )

         self.parent.assertEqual(result.last_hidden_state.shape ,				(self.batch_size, self.seq_length, self.hidden_size)       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	List[str]:





         """simple docstring"""




         _lowercase:			Dict       =     TFDebertaVaForMaskedLM(config=A_       )
         _lowercase:			str       =     {
             '''input_ids''': input_ids,
             '''attention_mask''': input_mask,
             '''token_type_ids''': token_type_ids,
         }
         _lowercase:			Tuple       =     model(A_       )
         self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.seq_length, self.vocab_size)       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Optional[int]       =     self.num_labels
         _lowercase:			str       =     TFDebertaVaForSequenceClassification(config=A_       )
         _lowercase:			Any       =     {
             '''input_ids''': input_ids,
             '''attention_mask''': input_mask,
             '''token_type_ids''': token_type_ids,
         }

         _lowercase:			Any       =     model(A_       )
         self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	Optional[Any]:





         """simple docstring"""




         _lowercase:			int       =     self.num_labels
         _lowercase:			Any       =     TFDebertaVaForTokenClassification(config=A_       )
         _lowercase:			str       =     {
             '''input_ids''': input_ids,
             '''attention_mask''': input_mask,
             '''token_type_ids''': token_type_ids,
         }
         _lowercase:			Dict       =     model(A_       )
         self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.seq_length, self.num_labels)       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Any       =     TFDebertaVaForQuestionAnswering(config=A_       )
         _lowercase:			Optional[int]       =     {
             '''input_ids''': input_ids,
             '''attention_mask''': input_mask,
             '''token_type_ids''': token_type_ids,
         }

         _lowercase:			Tuple       =     model(A_       )
         self.parent.assertEqual(result.start_logits.shape ,				(self.batch_size, self.seq_length)       )
         self.parent.assertEqual(result.end_logits.shape ,				(self.batch_size, self.seq_length)       )



       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			List[Any]       =     self.prepare_config_and_inputs()
         (
             (
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				
         ):			int       =     config_and_inputs
         _lowercase:			Tuple       =     {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
         return config, inputs_dict


@require_tf
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__   ,					SCREAMING_SNAKE_CASE__   ,					unittest.TestCase ):
       UpperCamelCase_   =		(
           (
               TFDebertaVaModel,
               TFDebertaVaForMaskedLM,
               TFDebertaVaForQuestionAnswering,
               TFDebertaVaForSequenceClassification,
               TFDebertaVaForTokenClassification,
           )
           if is_tf_available()
           else ()
       )
       UpperCamelCase_   =		(
           {
               '''feature-extraction''': TFDebertaVaModel,
               '''fill-mask''': TFDebertaVaForMaskedLM,
               '''question-answering''': TFDebertaVaForQuestionAnswering,
               '''text-classification''': TFDebertaVaForSequenceClassification,
               '''token-classification''': TFDebertaVaForTokenClassification,
               '''zero-shot''': TFDebertaVaForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )

       UpperCamelCase_   =		False
       UpperCamelCase_   =		False
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         _lowercase:			Optional[int]       =     TFDebertaVaModelTester(self       )
         _lowercase:			Tuple       =     ConfigTester(self ,				config_class=A_ ,				hidden_size=37       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         self.config_tester.run_common_tests()
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Dict       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A_       )
       def 							lowercase_							(     self       )     ->	Union[str, Any]:





         """simple docstring"""




         _lowercase:			Any       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*A_       )
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         _lowercase:			Dict       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(*A_       )
       def 							lowercase_							(     self       )     ->	Union[str, Any]:





         """simple docstring"""




         _lowercase:			int       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(*A_       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         _lowercase:			List[Any]       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*A_       )



       @slow
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         _lowercase:			str       =     TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge'''       )
         self.assertIsNotNone(A_       )


@require_tf
class 			__magic_name__       (       unittest.TestCase ):
       @unittest.skip(reason='''Model not available yet'''       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         pass



       @slow
       def 							lowercase_							(     self       )     ->	Dict:





         """simple docstring"""




         _lowercase:			str       =     TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge'''       )
         _lowercase:			Union[str, Any]       =     tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]       )
         _lowercase:			int       =     tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]       )
         _lowercase:			Tuple       =     model(A_ ,				attention_mask=A_       )[0]

         _lowercase:			Any       =     tf.constant(
             [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]]       )
         tf.debugging.assert_near(output[:, 1:4, 1:4] ,				A_ ,				atol=1E-4       )


"""simple docstring"""




import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


A__   :					List[Any]							=   datasets.utils.logging.get_logger(__name__)


@dataclass
class 			__magic_name__       (       datasets.BuilderConfig ):
       UpperCamelCase_   =		None
       UpperCamelCase_   =		"utf-8"
       UpperCamelCase_   =		None
       UpperCamelCase_   =		None
       UpperCamelCase_   =		True  # deprecated
       UpperCamelCase_   =		None  # deprecated
       UpperCamelCase_   =		10 << 20  # 10MB
       UpperCamelCase_   =		None


class 			__magic_name__       (       datasets.ArrowBasedBuilder ):
       UpperCamelCase_   =		JsonConfig
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         if self.config.block_size is not None:
           logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'''       )
           _lowercase:			List[str]       =     self.config.block_size
         if self.config.use_threads is not True:
           logger.warning(
               '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'''       )
         if self.config.newlines_in_values is not None:
           raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported'''       )
         return datasets.DatasetInfo(features=self.config.features       )
       def 							lowercase_							(     self ,				A_       )     ->	Any:





         """simple docstring"""




         if not self.config.data_files:
           raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}'''       )
         _lowercase:			int       =     dl_manager.download_and_extract(self.config.data_files       )
         if isinstance(A_ ,				(str, list, tuple)       ):
           _lowercase:			Tuple       =     data_files
           if isinstance(A_ ,				A_       ):
             _lowercase:			Optional[Any]       =     [files]
           _lowercase:			Dict       =     [dl_manager.iter_files(A_       ) for file in files]
           return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,				gen_kwargs={'''files''': files}       )]
         _lowercase:			str       =     []
         for split_name, files in data_files.items():
           if isinstance(A_ ,				A_       ):
             _lowercase:			Optional[Any]       =     [files]
           _lowercase:			str       =     [dl_manager.iter_files(A_       ) for file in files]
           splits.append(datasets.SplitGenerator(name=A_ ,				gen_kwargs={'''files''': files}       )       )
         return splits
       def 							lowercase_							(     self ,				A_       )     ->	pa.Table:





         """simple docstring"""




         if self.config.features is not None:
           # adding missing columns
           for column_name in set(self.config.features       ) - set(pa_table.column_names       ):
             _lowercase:			Any       =     self.config.features.arrow_schema.field(A_       ).type
             _lowercase:			Optional[Any]       =     pa_table.append_column(A_ ,				pa.array([None] * len(A_       ) ,				type=A_       )       )
           # more expensive cast to support nested structures with keys in a different order
           # allows str <-> int/float or str to Audio for example
           _lowercase:			Optional[int]       =     table_cast(A_ ,				self.config.features.arrow_schema       )
         return pa_table



       def 							lowercase_							(     self ,				A_       )     ->	str:





         """simple docstring"""




         for file_idx, file in enumerate(itertools.chain.from_iterable(A_       )       ):
           # If the file is one json object and if we need to look at the list of items in one specific field
           if self.config.field is not None:
             with open(A_ ,				encoding=self.config.encoding ,				errors=self.config.encoding_errors       ) as f:
               _lowercase:			Optional[int]       =     json.load(A_       )

             # We keep only the field we are interested in
             _lowercase:			str       =     dataset[self.config.field]

             # We accept two format: a list of dicts or a dict of lists
             if isinstance(A_ ,				(list, tuple)       ):
               _lowercase:			Dict       =     set().union(*[row.keys() for row in dataset]       )
               _lowercase:			List[str]       =     {col: [row.get(A_       ) for row in dataset] for col in keys}
             else:
               _lowercase:			Dict       =     dataset
             _lowercase:			Union[str, Any]       =     pa.Table.from_pydict(A_       )
             yield file_idx, self._cast_table(A_       )

           # If the file has one json object per line
           else:
             with open(A_ ,				'''rb'''       ) as f:
               _lowercase:			int       =     0
               # Use block_size equal to the chunk size divided by 32 to leverage multithreading
               # Set a default minimum value of 16kB if the chunk size is really small
               _lowercase:			Optional[int]       =     max(self.config.chunksize // 32 ,				16 << 10       )
               _lowercase:			List[Any]       =     (
                   self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
               )
               while True:
                 _lowercase:			Union[str, Any]       =     f.read(self.config.chunksize       )
                 if not batch:
                   break
                 # Finish current line
                 try:
                   batch += f.readline()
                 except (AttributeError, io.UnsupportedOperation):
                   batch += readline(A_       )
                 # PyArrow only accepts utf-8 encoded bytes
                 if self.config.encoding != "utf-8":
                   _lowercase:			Any       =     batch.decode(self.config.encoding ,				errors=A_       ).encode('''utf-8'''       )
                 try:
                   while True:
                     try:
                       _lowercase:			Optional[int]       =     paj.read_json(
                           io.BytesIO(A_       ) ,				read_options=paj.ReadOptions(block_size=A_       )       )
                       break
                     except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                       if (
                           isinstance(A_ ,				pa.ArrowInvalid       )
                           and "straddling" not in str(A_       )
                           or block_size > len(A_       )
                       ):
                         raise
                       else:
                         # Increase the block size in case it was too small.
                         # The block size will be reset for the next file.
                         logger.debug(
                             f'''Batch of {len(A_       )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.'''       )
                         block_size *= 2
                 except pa.ArrowInvalid as e:
                   try:
                     with open(
                         A_ ,				encoding=self.config.encoding ,				errors=self.config.encoding_errors       ) as f:
                       _lowercase:			Optional[Any]       =     json.load(A_       )
                   except json.JSONDecodeError:
                     logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                     raise e
                   # If possible, parse the file as a list of json objects and exit the loop
                   if isinstance(A_ ,				A_       ):  # list is the only sequence type supported in JSON
                     try:
                       _lowercase:			Optional[int]       =     set().union(*[row.keys() for row in dataset]       )
                       _lowercase:			Tuple       =     {col: [row.get(A_       ) for row in dataset] for col in keys}
                       _lowercase:			str       =     pa.Table.from_pydict(A_       )
                     except (pa.ArrowInvalid, AttributeError) as e:
                       logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                       raise ValueError(f'''Not able to read records in the JSON file at {file}.'''       ) from None
                     yield file_idx, self._cast_table(A_       )
                     break
                   else:
                     logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                     raise ValueError(
                         f'''Not able to read records in the JSON file at {file}. '''
                         f'''You should probably indicate the field of the JSON file containing your records. '''
                         f'''This JSON file contain the following fields: {str(list(dataset.keys()       )       )}. '''
                         f'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. '''       ) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                 yield (file_idx, batch_idx), self._cast_table(A_       )
                 batch_idx += 1
