





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_    (		__lowercase						):






  def 				UpperCAmelCase__						(							self			:					Dict      )->List[Any]:






   '''simple docstring'''

   __lowerCAmelCase					:	List[Any]      =       self.config_class(**self.inputs_dict      )
   self.parent.assertTrue(hasattr(_snake_case       ,  """embed_dim"""      )      )
   self.parent.assertTrue(hasattr(_snake_case       ,  """num_heads"""      )      )






class        snake_case_    :






  def __init__(							self			:					Dict       ,  _snake_case			:					int       ,  _snake_case			:					str=13       ,  _snake_case			:					Optional[int]=64       ,  _snake_case			:					Union[str, Any]=3       ,  _snake_case			:					Any=[16, 48, 96]       ,  _snake_case			:					List[str]=[1, 3, 6]       ,  _snake_case			:					str=[1, 2, 10]       ,  _snake_case			:					Tuple=[7, 3, 3]       ,  _snake_case			:					Tuple=[4, 2, 2]       ,  _snake_case			:					Tuple=[2, 1, 1]       ,  _snake_case			:					List[str]=[2, 2, 2]       ,  _snake_case			:					Tuple=[False, False, True]       ,  _snake_case			:					int=[0.0, 0.0, 0.0]       ,  _snake_case			:					Union[str, Any]=0.02       ,  _snake_case			:					List[str]=1E-12       ,  _snake_case			:					str=True       ,  _snake_case			:					Any=True       ,  _snake_case			:					Optional[Any]=2       ,  )->List[str]:






   '''simple docstring'''

   __lowerCAmelCase					:	List[str]      =       parent
   __lowerCAmelCase					:	int      =       batch_size
   __lowerCAmelCase					:	Optional[int]      =       image_size
   __lowerCAmelCase					:	Optional[Any]      =       patch_sizes
   __lowerCAmelCase					:	Tuple      =       patch_stride
   __lowerCAmelCase					:	List[Any]      =       patch_padding
   __lowerCAmelCase					:	Tuple      =       is_training
   __lowerCAmelCase					:	str      =       use_labels
   __lowerCAmelCase					:	List[Any]      =       num_labels
   __lowerCAmelCase					:	int      =       num_channels
   __lowerCAmelCase					:	Tuple      =       embed_dim
   __lowerCAmelCase					:	Optional[int]      =       num_heads
   __lowerCAmelCase					:	Union[str, Any]      =       stride_kv
   __lowerCAmelCase					:	List[Any]      =       depth
   __lowerCAmelCase					:	int      =       cls_token
   __lowerCAmelCase					:	Optional[Any]      =       attention_drop_rate
   __lowerCAmelCase					:	Union[str, Any]      =       initializer_range
   __lowerCAmelCase					:	Any      =       layer_norm_eps






  def 				UpperCAmelCase__						(							self			:					List[str]      )->Union[str, Any]:






   '''simple docstring'''

   __lowerCAmelCase					:	Dict      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

   __lowerCAmelCase					:	List[Any]      =       self.get_config()
   return config, pixel_values, labels






  def 				UpperCAmelCase__						(							self			:					List[str]      )->int:






   '''simple docstring'''

   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			:					List[Any]       ,  _snake_case			:					int       ,  _snake_case			:					str       ,  _snake_case			:					Union[str, Any]      )->Tuple:






   '''simple docstring'''

   __lowerCAmelCase					:	str      =       TFCvtModel(config=_snake_case      )
   __lowerCAmelCase					:	Optional[Any]      =       model(_snake_case       ,  training=_snake_case      )
   __lowerCAmelCase					:	str      =       (self.image_size, self.image_size)
   __lowerCAmelCase ,					__lowerCAmelCase					:	Tuple      =       image_size[0], image_size[1]
   for i in range(len(self.depth      )      ):
    __lowerCAmelCase					:	int      =       floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1      )
    __lowerCAmelCase					:	Any      =       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			:					Tuple       ,  _snake_case			:					Optional[int]       ,  _snake_case			:					Tuple       ,  _snake_case			:					Optional[Any]      )->Dict:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[int]      =       self.num_labels
   __lowerCAmelCase					:	Optional[int]      =       TFCvtForImageClassification(_snake_case      )
   __lowerCAmelCase					:	str      =       model(_snake_case       ,  labels=_snake_case       ,  training=_snake_case      )
   self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)      )






  def 				UpperCAmelCase__						(							self			:					Tuple      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Tuple      =       self.prepare_config_and_inputs()
   __lowerCAmelCase ,					__lowerCAmelCase ,					__lowerCAmelCase					:	Any      =       config_and_inputs
   __lowerCAmelCase					:	List[str]      =       {"""pixel_values""": pixel_values}
   return config, inputs_dict






@require_tf
class        snake_case_    (		__lowercase					,__lowercase					,unittest.TestCase						):
  A_      							=   (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
  A_      							=   (
      {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification}
      if is_tf_available()
      else {}
  )
  A_      							=   False
  A_      							=   False
  A_      							=   False
  A_      							=   False
  A_      							=   False






  def 				UpperCAmelCase__						(							self			:					List[str]      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Tuple      =       TFCvtModelTester(self      )
   __lowerCAmelCase					:	Optional[Any]      =       TFCvtConfigTester(self       ,  config_class=_snake_case       ,  has_text_modality=_snake_case       ,  hidden_size=37      )






  def 				UpperCAmelCase__						(							self			:					Union[str, Any]      )->Optional[int]:






   '''simple docstring'''

   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			:					str      )->List[Any]:






   '''simple docstring'''

   pass






  @unittest.skip(reason="""Cvt does not use inputs_embeds"""      )
  def 				UpperCAmelCase__						(							self			:					Union[str, Any]      )->List[str]:






   '''simple docstring'''

   pass






  @unittest.skip(reason="""Cvt does not support input and output embeddings"""      )
  def 				UpperCAmelCase__						(							self			:					Tuple      )->Optional[int]:






   '''simple docstring'''

   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			:					Dict      )->Any:






   '''simple docstring'''

   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			:					Dict      )->Dict:






   '''simple docstring'''

   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			:					Union[str, Any]      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[int]      =       tf.keras.mixed_precision.Policy("""mixed_float16"""      )
   tf.keras.mixed_precision.set_global_policy(_snake_case      )
   super().test_keras_fit()
   tf.keras.mixed_precision.set_global_policy("""float32"""      )






  def 				UpperCAmelCase__						(							self			:					Tuple      )->Tuple:






   '''simple docstring'''

   __lowerCAmelCase ,					__lowerCAmelCase					:	Union[str, Any]      =       self.model_tester.prepare_config_and_inputs_for_common()

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

    __lowerCAmelCase					:	Any      =       ["""pixel_values"""]
    self.assertListEqual(arg_names[:1]       ,  _snake_case      )






  def 				UpperCAmelCase__						(							self			:					int      )->List[str]:






   '''simple docstring'''

   def check_hidden_states_output(_snake_case			:					Union[str, Any]       ,  _snake_case			:					Optional[Any]       ,  _snake_case			:					Optional[Any]      ):
    __lowerCAmelCase					:	Any      =       model_class(_snake_case      )

    __lowerCAmelCase					:	Any      =       model(**self._prepare_for_class(_snake_case       ,  _snake_case      )      )
    __lowerCAmelCase					:	Optional[Any]      =       outputs.hidden_states

    __lowerCAmelCase					:	Tuple      =       len(self.model_tester.depth      )
    self.assertEqual(len(_snake_case      )       ,  _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,
        ]       ,  )

   __lowerCAmelCase ,					__lowerCAmelCase					:	Union[str, Any]      =       self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    __lowerCAmelCase					:	str      =       True
    check_hidden_states_output(_snake_case       ,  _snake_case       ,  _snake_case      )

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

    check_hidden_states_output(_snake_case       ,  _snake_case       ,  _snake_case      )






  def 				UpperCAmelCase__						(							self			:					str      )->List[str]:






   '''simple docstring'''

   __lowerCAmelCase					:	str      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*_snake_case      )






  def 				UpperCAmelCase__						(							self			:					Dict      )->List[str]:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[int]      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*_snake_case      )






  @slow
  def 				UpperCAmelCase__						(							self			:					Dict      )->Union[str, Any]:






   '''simple docstring'''

   for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __lowerCAmelCase					:	List[Any]      =       TFCvtModel.from_pretrained(_snake_case      )
    self.assertIsNotNone(_snake_case      )






def 	_SCREAMING_SNAKE_CASE		(      )      ->   Tuple:
 __lowerCAmelCase					:	int      =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
 return image







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






  @cached_property
  def 				UpperCAmelCase__						(							self			:					Dict      )->List[Any]:






   '''simple docstring'''

   return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )






  @slow
  def 				UpperCAmelCase__						(							self			:					List[str]      )->Union[str, Any]:






   '''simple docstring'''

   __lowerCAmelCase					:	Any      =       TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

   __lowerCAmelCase					:	List[Any]      =       self.default_image_processor
   __lowerCAmelCase					:	Optional[int]      =       prepare_img()
   __lowerCAmelCase					:	int      =       image_processor(images=_snake_case       ,  return_tensors="""tf"""      )

   # forward pass
   __lowerCAmelCase					:	Dict      =       model(**_snake_case      )

   # verify the logits
   __lowerCAmelCase					:	Dict      =       tf.TensorShape((1, 1000)      )
   self.assertEqual(outputs.logits.shape       ,  _snake_case      )

   __lowerCAmelCase					:	Any      =       tf.constant([0.9_285, 0.9_015, -0.3_150]      )
   self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()       ,  _snake_case       ,  atol=1E-4      )      )






from datetime import datetime

import requests






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:str   )      ->   bytes:
 __lowerCAmelCase					:	List[Any]      =       """https://downloadgram.net/wp-json/wppress/video-downloader/video?url="""
 __lowerCAmelCase					:	Dict      =       requests.get(base_url + url   ).json()[0]["""urls"""][0]["""src"""]
 return requests.get(SCREAMING_SNAKE_CASE   ).content


if __name__ == "__main__":
      _UpperCAmelCase             =							input('Enter Video/IGTV url: ').strip()
      _UpperCAmelCase             =							f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4'''
      with open(file_name, 'wb') as fp:
            fp.write(download_video(url))
      print(f'''Done. Video saved to disk as {file_name}.''')