from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
  import tensorflow as tf

  from transformers import TFCvtForImageClassification, TFCvtModel
  from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def _lowerCAmelCase(						self			)  ->  Optional[int]:
        lowercase__    :   Dict						= self.config_class(**self.inputs_dict			)
        self.parent.assertTrue(hasattr(__lowerCAmelCase     ,       '''embed_dim'''			)			)
        self.parent.assertTrue(hasattr(__lowerCAmelCase     ,       '''num_heads'''			)			)



class       UpperCAmelCase  :





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=13     ,       __lowerCAmelCase=64     ,       __lowerCAmelCase=3     ,       __lowerCAmelCase=[16, 48, 96]     ,       __lowerCAmelCase=[1, 3, 6]     ,       __lowerCAmelCase=[1, 2, 10]     ,       __lowerCAmelCase=[7, 3, 3]     ,       __lowerCAmelCase=[4, 2, 2]     ,       __lowerCAmelCase=[2, 1, 1]     ,       __lowerCAmelCase=[2, 2, 2]     ,       __lowerCAmelCase=[False, False, True]     ,       __lowerCAmelCase=[0.0, 0.0, 0.0]     ,       __lowerCAmelCase=0.0_2     ,       __lowerCAmelCase=1E-12     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=2     ,       )  ->  Tuple:
        lowercase__    :   Union[str, Any]						= parent
        lowercase__    :   str						= batch_size
        lowercase__    :   int						= image_size
        lowercase__    :   int						= patch_sizes
        lowercase__    :   Dict						= patch_stride
        lowercase__    :   Dict						= patch_padding
        lowercase__    :   List[str]						= is_training
        lowercase__    :   Dict						= use_labels
        lowercase__    :   Any						= num_labels
        lowercase__    :   Optional[int]						= num_channels
        lowercase__    :   Optional[Any]						= embed_dim
        lowercase__    :   List[Any]						= num_heads
        lowercase__    :   Optional[int]						= stride_kv
        lowercase__    :   int						= depth
        lowercase__    :   str						= cls_token
        lowercase__    :   int						= attention_drop_rate
        lowercase__    :   str						= initializer_range
        lowercase__    :   str						= layer_norm_eps

       def _lowerCAmelCase(						self			)  ->  str:
        lowercase__    :   Dict						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

        lowercase__    :   Optional[Any]						= None
        if self.use_labels:
         # create a random int32 tensor of given shape
         lowercase__    :   Dict						= ids_tensor([self.batch_size]     ,       self.num_labels			)

        lowercase__    :   Tuple						= self.get_config()
        return config, pixel_values, labels

       def _lowerCAmelCase(						self			)  ->  str:
        return CvtConfig(
            image_size=self.image_size     ,       num_labels=self.num_labels     ,       num_channels=self.num_channels     ,       embed_dim=self.embed_dim     ,       num_heads=self.num_heads     ,       patch_sizes=self.patch_sizes     ,       patch_padding=self.patch_padding     ,       patch_stride=self.patch_stride     ,       stride_kv=self.stride_kv     ,       depth=self.depth     ,       cls_token=self.cls_token     ,       attention_drop_rate=self.attention_drop_rate     ,       initializer_range=self.initializer_range     ,       )

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  List[Any]:
        lowercase__    :   Optional[int]						= TFCvtModel(config=__lowerCAmelCase			)
        lowercase__    :   Dict						= model(__lowerCAmelCase     ,       training=__lowerCAmelCase			)
        lowercase__    :   str						= (self.image_size, self.image_size)
        lowercase__    :   Tuple						= image_size[0], image_size[1]
        for i in range(len(self.depth			)			):
         lowercase__    :   int						= floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1			)
         lowercase__    :   Optional[int]						= floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1			)
        self.parent.assertEqual(result.last_hidden_state.shape     ,       (self.batch_size, self.embed_dim[-1], height, width)			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   Optional[int]						= self.num_labels
        lowercase__    :   Optional[int]						= TFCvtForImageClassification(__lowerCAmelCase			)
        lowercase__    :   List[str]						= model(__lowerCAmelCase     ,       labels=__lowerCAmelCase     ,       training=__lowerCAmelCase			)
        self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.num_labels)			)


       def _lowerCAmelCase(						self			)  ->  Tuple:
        lowercase__    :   Tuple						= self.prepare_config_and_inputs()
        lowercase__    :   List[str]						= config_and_inputs
        lowercase__    :   Dict						= {'''pixel_values''': pixel_values}
        return config, inputs_dict



@require_tf
class       UpperCAmelCase  (						a__   ,						a__   ,						unittest.TestCase ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
       SCREAMING_SNAKE_CASE 		=   (
           {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
           if is_tf_available()
           else {}
       )
       SCREAMING_SNAKE_CASE 		=   False
       SCREAMING_SNAKE_CASE 		=   False
       SCREAMING_SNAKE_CASE 		=   False
       SCREAMING_SNAKE_CASE 		=   False
       SCREAMING_SNAKE_CASE 		=   False

       def _lowerCAmelCase(						self			)  ->  int:
        lowercase__    :   Dict						= TFCvtModelTester(self			)
        lowercase__    :   str						= TFCvtConfigTester(self     ,       config_class=__lowerCAmelCase     ,       has_text_modality=__lowerCAmelCase     ,       hidden_size=37			)

       def _lowerCAmelCase(						self			)  ->  Tuple:
        self.config_tester.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()

       @unittest.skip(reason='''Cvt does not output attentions'''			)
       def _lowerCAmelCase(						self			)  ->  List[Any]:
        pass

       @unittest.skip(reason='''Cvt does not use inputs_embeds'''			)
       def _lowerCAmelCase(						self			)  ->  List[str]:
        pass

       @unittest.skip(reason='''Cvt does not support input and output embeddings'''			)
       def _lowerCAmelCase(						self			)  ->  List[str]:
        pass

       @unittest.skipIf(
           not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''			)			) == 0     ,       reason='''TF does not support backprop for grouped convolutions on CPU.'''     ,       )
       def _lowerCAmelCase(						self			)  ->  List[str]:
        super().test_dataset_conversion()

       @unittest.skipIf(
           not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''			)			) == 0     ,       reason='''TF does not support backprop for grouped convolutions on CPU.'''     ,       )
       @slow
       def _lowerCAmelCase(						self			)  ->  List[str]:
        super().test_keras_fit()

       @unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'''			)
       def _lowerCAmelCase(						self			)  ->  Any:
        lowercase__    :   List[str]						= tf.keras.mixed_precision.Policy('''mixed_float16'''			)
        tf.keras.mixed_precision.set_global_policy(__lowerCAmelCase			)
        super().test_keras_fit()
        tf.keras.mixed_precision.set_global_policy('''float32'''			)

       def _lowerCAmelCase(						self			)  ->  Tuple:
        lowercase__    :   str						= self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         lowercase__    :   int						= model_class(__lowerCAmelCase			)
         lowercase__    :   List[str]						= inspect.signature(model.call			)
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         lowercase__    :   Any						= [*signature.parameters.keys()]

         lowercase__    :   Dict						= ['''pixel_values''']
         self.assertListEqual(arg_names[:1]     ,       __lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  str:
        def check_hidden_states_output(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			):
         lowercase__    :   int						= model_class(__lowerCAmelCase			)

         lowercase__    :   Tuple						= model(**self._prepare_for_class(__lowerCAmelCase     ,       __lowerCAmelCase			)			)
         lowercase__    :   Optional[int]						= outputs.hidden_states

         lowercase__    :   List[str]						= len(self.model_tester.depth			)
         self.assertEqual(len(__lowerCAmelCase			)     ,       __lowerCAmelCase			)

         # verify the first hidden states (first block)
         self.assertListEqual(
             list(hidden_states[0].shape[-3:]			)     ,       [
                 self.model_tester.embed_dim[0],
                 self.model_tester.image_size // 4,
                 self.model_tester.image_size // 4,
             ]     ,       )

        lowercase__    :   Optional[int]						= self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         lowercase__    :   Optional[int]						= True
         check_hidden_states_output(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         lowercase__    :   List[Any]						= True

         check_hidden_states_output(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  Optional[int]:
        lowercase__    :   str						= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        lowercase__    :   Any						= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase			)


       @slow
       def _lowerCAmelCase(						self			)  ->  int:
        for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowercase__    :   List[Any]						= TFCvtModel.from_pretrained(__lowerCAmelCase			)
         self.assertIsNotNone(__lowerCAmelCase			)


def       __UpperCamelCase	(       ):
 lowercase__    :   Any						= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
 return image





@require_tf
@require_vision
class       UpperCAmelCase  (						unittest.TestCase ):





       '''simple docstring'''



       @cached_property
       def _lowerCAmelCase(						self			)  ->  str:
        return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)


       @slow
       def _lowerCAmelCase(						self			)  ->  Dict:
        lowercase__    :   Tuple						= TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)

        lowercase__    :   Optional[Any]						= self.default_image_processor
        lowercase__    :   Optional[int]						= prepare_img()
        lowercase__    :   Dict						= image_processor(images=__lowerCAmelCase     ,       return_tensors='''tf'''			)

        # forward pass
        lowercase__    :   str						= model(**__lowerCAmelCase			)

        # verify the logits
        lowercase__    :   List[str]						= tf.TensorShape((1, 1000)			)
        self.assertEqual(outputs.logits.shape     ,       __lowerCAmelCase			)

        lowercase__    :   Optional[int]						= tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]			)
        self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,       __lowerCAmelCase     ,       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:			Tuple	       =       datasets.utils.logging.get_logger(__name__)



@dataclass
class       UpperCAmelCase  (						datasets.BuilderConfig ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   None
       SCREAMING_SNAKE_CASE 		=   "utf-8"
       SCREAMING_SNAKE_CASE 		=   None
       SCREAMING_SNAKE_CASE 		=   None
       SCREAMING_SNAKE_CASE 		=   True  # deprecated
       SCREAMING_SNAKE_CASE 		=   None  # deprecated
       SCREAMING_SNAKE_CASE 		=   1_0 << 2_0  # 10MB
       SCREAMING_SNAKE_CASE 		=   None



class       UpperCAmelCase  (						datasets.ArrowBasedBuilder ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   JsonConfig

       def _lowerCAmelCase(						self			)  ->  Any:
        if self.config.block_size is not None:
         logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'''			)
         lowercase__    :   Tuple						= 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 _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Optional[Any]:
        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__    :   List[str]						= dl_manager.download_and_extract(self.config.data_files			)
        if isinstance(__lowerCAmelCase     ,       (str, list, tuple)			):
         lowercase__    :   List[str]						= data_files
         if isinstance(__lowerCAmelCase     ,       __lowerCAmelCase			):
          lowercase__    :   Union[str, Any]						= [files]
         lowercase__    :   Dict						= [dl_manager.iter_files(__lowerCAmelCase			) 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(__lowerCAmelCase     ,       __lowerCAmelCase			):
          lowercase__    :   List[str]						= [files]
         lowercase__    :   Optional[Any]						= [dl_manager.iter_files(__lowerCAmelCase			) for file in files]
         splits.append(datasets.SplitGenerator(name=__lowerCAmelCase     ,       gen_kwargs={'''files''': files}			)			)
        return splits

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


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Optional[int]:
        for file_idx, file in enumerate(itertools.chain.from_iterable(__lowerCAmelCase			)			):
         # 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(__lowerCAmelCase     ,       encoding=self.config.encoding     ,       errors=self.config.encoding_errors			) as f:
           lowercase__    :   Dict						= json.load(__lowerCAmelCase			)

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

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

         # If the file has one json object per line
         else:
          with open(__lowerCAmelCase     ,       '''rb'''			) as f:
           lowercase__    :   Optional[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__    :   List[str]						= max(self.config.chunksize // 32     ,       16 << 10			)
           lowercase__    :   Union[str, Any]						= (
               self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
           )
           while True:
            lowercase__    :   Tuple						= f.read(self.config.chunksize			)
            if not batch:
             break
            # Finish current line
            try:
             batch += f.readline()
            except (AttributeError, io.UnsupportedOperation):
             batch += readline(__lowerCAmelCase			)
            # PyArrow only accepts utf-8 encoded bytes
            if self.config.encoding != "utf-8":
             lowercase__    :   Dict						= batch.decode(self.config.encoding     ,       errors=__lowerCAmelCase			).encode('''utf-8'''			)
            try:
             while True:
              try:
               lowercase__    :   str						= paj.read_json(
                   io.BytesIO(__lowerCAmelCase			)     ,       read_options=paj.ReadOptions(block_size=__lowerCAmelCase			)			)
               break
              except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
               if (
                   isinstance(__lowerCAmelCase     ,       pa.ArrowInvalid			)
                   and "straddling" not in str(__lowerCAmelCase			)
                   or block_size > len(__lowerCAmelCase			)
               ):
                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(__lowerCAmelCase			)} 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(
                  __lowerCAmelCase     ,       encoding=self.config.encoding     ,       errors=self.config.encoding_errors			) as f:
               lowercase__    :   Optional[int]						= json.load(__lowerCAmelCase			)
             except json.JSONDecodeError:
              logger.error(F"""Failed to read file '{file}' with error {type(__lowerCAmelCase			)}: {e}"""			)
              raise e
             # If possible, parse the file as a list of json objects and exit the loop
             if isinstance(__lowerCAmelCase     ,       __lowerCAmelCase			):  # list is the only sequence type supported in JSON
              try:
               lowercase__    :   List[Any]						= set().union(*[row.keys() for row in dataset]			)
               lowercase__    :   str						= {col: [row.get(__lowerCAmelCase			) for row in dataset] for col in keys}
               lowercase__    :   Optional[int]						= pa.Table.from_pydict(__lowerCAmelCase			)
              except (pa.ArrowInvalid, AttributeError) as e:
               logger.error(F"""Failed to read file '{file}' with error {type(__lowerCAmelCase			)}: {e}"""			)
               raise ValueError(F"""Not able to read records in the JSON file at {file}."""			) from None
              yield file_idx, self._cast_table(__lowerCAmelCase			)
              break
             else:
              logger.error(F"""Failed to read file '{file}' with error {type(__lowerCAmelCase			)}: {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(__lowerCAmelCase			)
            batch_idx += 1

