





'''simple docstring'''






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 					__snake_case  (					__SCREAMING_SNAKE_CASE							):






   '''simple docstring'''





   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Dict    =  self.config_class(**self.inputs_dict       )
    self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,		"""embed_dim"""       )       )
    self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,		"""num_heads"""       )       )



class 					__snake_case  :






   '''simple docstring'''





   def __init__(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE=1_3	,		__SCREAMING_SNAKE_CASE=6_4	,		__SCREAMING_SNAKE_CASE=3	,		__SCREAMING_SNAKE_CASE=[1_6, 4_8, 9_6]	,		__SCREAMING_SNAKE_CASE=[1, 3, 6]	,		__SCREAMING_SNAKE_CASE=[1, 2, 1_0]	,		__SCREAMING_SNAKE_CASE=[7, 3, 3]	,		__SCREAMING_SNAKE_CASE=[4, 2, 2]	,		__SCREAMING_SNAKE_CASE=[2, 1, 1]	,		__SCREAMING_SNAKE_CASE=[2, 2, 2]	,		__SCREAMING_SNAKE_CASE=[False, False, True]	,		__SCREAMING_SNAKE_CASE=[0.0, 0.0, 0.0]	,		__SCREAMING_SNAKE_CASE=0.02	,		__SCREAMING_SNAKE_CASE=1e-1_2	,		__SCREAMING_SNAKE_CASE=True	,		__SCREAMING_SNAKE_CASE=True	,		__SCREAMING_SNAKE_CASE=2	,		):
    snake_case__     :					List[str]    =  parent
    snake_case__     :					Tuple    =  batch_size
    snake_case__     :					Union[str, Any]    =  image_size
    snake_case__     :					List[Any]    =  patch_sizes
    snake_case__     :					Optional[int]    =  patch_stride
    snake_case__     :					Optional[Any]    =  patch_padding
    snake_case__     :					Any    =  is_training
    snake_case__     :					int    =  use_labels
    snake_case__     :					Dict    =  num_labels
    snake_case__     :					Optional[Any]    =  num_channels
    snake_case__     :					Optional[Any]    =  embed_dim
    snake_case__     :					Optional[int]    =  num_heads
    snake_case__     :					Optional[int]    =  stride_kv
    snake_case__     :					int    =  depth
    snake_case__     :					Optional[Any]    =  cls_token
    snake_case__     :					List[Any]    =  attention_drop_rate
    snake_case__     :					Union[str, Any]    =  initializer_range
    snake_case__     :					List[Any]    =  layer_norm_eps

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Optional[int]    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

    snake_case__     :					List[str]    =  self.get_config()
    return config, pixel_values, labels

   def 		__UpperCamelCase						(							self       ):
    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 		__UpperCamelCase						(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
    snake_case__     :					int    =  TFCvtModel(config=__SCREAMING_SNAKE_CASE       )
    snake_case__     :					List[Any]    =  model(__SCREAMING_SNAKE_CASE	,		training=__SCREAMING_SNAKE_CASE       )
    snake_case__     :					Tuple    =  (self.image_size, self.image_size)
    snake_case__  ,							snake_case__     :					str    =  image_size[0], image_size[1]
    for i in range(len(self.depth       )       ):
     snake_case__     :					Any    =  floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
     snake_case__     :					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 		__UpperCamelCase						(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
    snake_case__     :					Any    =  self.num_labels
    snake_case__     :					str    =  TFCvtForImageClassification(__SCREAMING_SNAKE_CASE       )
    snake_case__     :					List[str]    =  model(__SCREAMING_SNAKE_CASE	,		labels=__SCREAMING_SNAKE_CASE	,		training=__SCREAMING_SNAKE_CASE       )
    self.parent.assertEqual(result.logits.shape	,		(self.batch_size, self.num_labels)       )


   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					List[Any]    =  self.prepare_config_and_inputs()
    snake_case__  ,							snake_case__  ,							snake_case__     :					Any    =  config_and_inputs
    snake_case__     :					Union[str, Any]    =  {"""pixel_values""": pixel_values}
    return config, inputs_dict



@require_tf
class 					__snake_case  (					__SCREAMING_SNAKE_CASE		,				__SCREAMING_SNAKE_CASE		,				unittest.TestCase							):






   '''simple docstring'''





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

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Optional[Any]    =  TFCvtModelTester(self       )
    snake_case__     :					Any    =  TFCvtConfigTester(self	,		config_class=__SCREAMING_SNAKE_CASE	,		has_text_modality=__SCREAMING_SNAKE_CASE	,		hidden_size=3_7       )

   def 		__UpperCamelCase						(							self       ):
    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 		__UpperCamelCase						(							self       ):
    pass

   @unittest.skip(reason="""Cvt does not use inputs_embeds"""       )
   def 		__UpperCamelCase						(							self       ):
    pass

   @unittest.skip(reason="""Cvt does not support input and output embeddings"""       )
   def 		__UpperCamelCase						(							self       ):
    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 		__UpperCamelCase						(							self       ):
    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 		__UpperCamelCase						(							self       ):
    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 		__UpperCamelCase						(							self       ):
    snake_case__     :					List[str]    =  tf.keras.mixed_precision.Policy("""mixed_float16"""       )
    tf.keras.mixed_precision.set_global_policy(__SCREAMING_SNAKE_CASE       )
    super().test_keras_fit()
    tf.keras.mixed_precision.set_global_policy("""float32"""       )

   def 		__UpperCamelCase						(							self       ):
    snake_case__  ,							snake_case__     :					List[str]    =  self.model_tester.prepare_config_and_inputs_for_common()

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

     snake_case__     :					Tuple    =  ["""pixel_values"""]
     self.assertListEqual(arg_names[:1]	,		__SCREAMING_SNAKE_CASE       )

   def 		__UpperCamelCase						(							self       ):
    def check_hidden_states_output(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
     snake_case__     :					str    =  model_class(__SCREAMING_SNAKE_CASE       )

     snake_case__     :					List[Any]    =  model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )       )
     snake_case__     :					Optional[int]    =  outputs.hidden_states

     snake_case__     :					Tuple    =  len(self.model_tester.depth       )
     self.assertEqual(len(__SCREAMING_SNAKE_CASE       )	,		__SCREAMING_SNAKE_CASE       )

     # 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,
         ]	,		)

    snake_case__  ,							snake_case__     :					str    =  self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     snake_case__     :					List[Any]    =  True
     check_hidden_states_output(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )

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

     check_hidden_states_output(__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       )

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Optional[Any]    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE       )

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Union[str, Any]    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE       )


   @slow
   def 		__UpperCamelCase						(							self       ):
    for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     snake_case__     :					str    =  TFCvtModel.from_pretrained(__SCREAMING_SNAKE_CASE       )
     self.assertIsNotNone(__SCREAMING_SNAKE_CASE       )



def        UpperCamelCase__		(						)				->			str:
 '''simple docstring'''






 snake_case__     :					Union[str, Any]    =  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
 return image





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






   '''simple docstring'''





   @cached_property
   def 		__UpperCamelCase						(							self       ):
    return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )


   @slow
   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Optional[Any]    =  TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

    snake_case__     :					Union[str, Any]    =  self.default_image_processor
    snake_case__     :					int    =  prepare_img()
    snake_case__     :					Dict    =  image_processor(images=__SCREAMING_SNAKE_CASE	,		return_tensors="""tf"""       )

    # forward pass
    snake_case__     :					Optional[int]    =  model(**__SCREAMING_SNAKE_CASE       )

    # verify the logits
    snake_case__     :					str    =  tf.TensorShape((1, 1_0_0_0)       )
    self.assertEqual(outputs.logits.shape	,		__SCREAMING_SNAKE_CASE       )

    snake_case__     :					int    =  tf.constant([0.9285, 0.9015, -0.3150]       )
    self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()	,		__SCREAMING_SNAKE_CASE	,		atol=1e-4       )       )











import pytest
import requests

from datasets.utils.file_utils import http_head

from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline





@pytest.mark.integration
def  __magic_name__  (				)				-> Union[str, Any]:

							"""simple docstring"""



							with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT				):
														with pytest.raises(lowercase				):
																					requests.request("""GET"""				,       """https://huggingface.co"""				)
														with pytest.raises(requests.exceptions.ConnectTimeout				):
																					requests.request("""GET"""				,       """https://huggingface.co"""				,       timeout=1.0				)





@pytest.mark.integration
def  __magic_name__  (				)				-> Union[str, Any]:

							"""simple docstring"""



							with offline(OfflineSimulationMode.CONNECTION_FAILS				):
														with pytest.raises(requests.exceptions.ConnectionError				):
																					requests.request("""GET"""				,       """https://huggingface.co"""				)





def  __magic_name__  (				)				-> Dict:

							"""simple docstring"""



							with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1				):
														with pytest.raises(lowercase				):
																					http_head("""https://huggingface.co"""				)