

import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import CvtForImageClassification, CvtModel
      from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor






class 						__magic_name__    (       a__    ):


 def _UpperCamelCase	(						self		: Any    )    ->      Tuple:
   UpperCAmelCase					      =  self.config_class(**self.inputs_dict    )
   self.parent.assertTrue(hasattr(lowerCamelCase_			,						"embed_dim"    )    )
   self.parent.assertTrue(hasattr(lowerCamelCase_			,						"num_heads"    )    )






class 						__magic_name__    :


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


 def _UpperCamelCase	(						self		: Any    )    ->      List[str]:
   UpperCAmelCase					      =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

   UpperCAmelCase					      =  None
   if self.use_labels:
     UpperCAmelCase					      =  ids_tensor([self.batch_size]			,						self.num_labels    )

   UpperCAmelCase					      =  self.get_config()
   return config, pixel_values, labels


 def _UpperCamelCase	(						self		: List[str]    )    ->      List[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 _UpperCamelCase	(						self		: List[Any]			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: Dict    )    ->      Optional[Any]:
   UpperCAmelCase					      =  CvtModel(config=lowerCamelCase_    )
   model.to(lowerCamelCase_    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCamelCase_    )
   UpperCAmelCase					      =  (self.image_size, self.image_size)
   UpperCAmelCase      ,	UpperCAmelCase					      =  image_size[0], image_size[1]
   for i in range(len(self.depth    )    ):
     UpperCAmelCase					      =  floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
     UpperCAmelCase					      =  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		: int			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Any			,						lowerCAmelCase__		: Union[str, Any]    )    ->      Tuple:
   UpperCAmelCase					      =  self.num_labels
   UpperCAmelCase					      =  CvtForImageClassification(lowerCamelCase_    )
   model.to(lowerCamelCase_    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCamelCase_			,						labels=lowerCamelCase_    )
   self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels)    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      str:
   UpperCAmelCase					      =  self.prepare_config_and_inputs()
   UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase					      =  config_and_inputs
   UpperCAmelCase					      =  {"pixel_values": pixel_values}
   return config, inputs_dict






@require_torch
class 						__magic_name__    (       a__	,						a__	,						unittest.TestCase    ):
 UpperCAmelCase							    =						(CvtModel, CvtForImageClassification) if is_torch_available() else ()
 UpperCAmelCase							    =						(
     {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
     if is_torch_available()
     else {}
 )

 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False


 def _UpperCamelCase	(						self		: str    )    ->      Optional[Any]:
   UpperCAmelCase					      =  CvtModelTester(self    )
   UpperCAmelCase					      =  ConfigTester(self			,						config_class=lowerCamelCase_			,						has_text_modality=lowerCamelCase_			,						hidden_size=3_7    )


 def _UpperCamelCase	(						self		: Any    )    ->      Dict:
   self.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()


 def _UpperCamelCase	(						self		: int    )    ->      Tuple:
   return


 @unittest.skip(reason="Cvt does not output attentions"    )
 def _UpperCamelCase	(						self		: Tuple    )    ->      Optional[int]:
   pass


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


 @unittest.skip(reason="Cvt does not support input and output embeddings"    )
 def _UpperCamelCase	(						self		: Tuple    )    ->      Tuple:
   pass


 def _UpperCamelCase	(						self		: Dict    )    ->      int:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     UpperCAmelCase					      =  model_class(lowerCamelCase_    )
     UpperCAmelCase					      =  inspect.signature(model.forward    )
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     UpperCAmelCase					      =  [*signature.parameters.keys()]

     UpperCAmelCase					      =  ["pixel_values"]
     self.assertListEqual(arg_names[:1]			,						lowerCamelCase_    )


 def _UpperCamelCase	(						self		: str    )    ->      int:
   UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCamelCase_    )


 def _UpperCamelCase	(						self		: str    )    ->      Tuple:
   def check_hidden_states_output(lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: str    ):
     UpperCAmelCase					      =  model_class(lowerCamelCase_    )
     model.to(lowerCamelCase_    )
     model.eval()

     with torch.no_grad():
       UpperCAmelCase					      =  model(**self._prepare_for_class(lowerCamelCase_			,						lowerCamelCase_    )    )

     UpperCAmelCase					      =  outputs.hidden_states

     UpperCAmelCase					      =  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,
         ]			,						)

   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     UpperCAmelCase					      =  True
     check_hidden_states_output(lowerCamelCase_			,						lowerCamelCase_			,						lowerCamelCase_    )

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     UpperCAmelCase					      =  True

     check_hidden_states_output(lowerCamelCase_			,						lowerCamelCase_			,						lowerCamelCase_    )


 def _UpperCamelCase	(						self		: int    )    ->      Tuple:
   UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_    )


 @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."    )
 def _UpperCamelCase	(						self		: Any    )    ->      Union[str, Any]:
   pass


 @slow
 def _UpperCamelCase	(						self		: Union[str, Any]    )    ->      int:
   for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase					      =  CvtModel.from_pretrained(lowerCamelCase_    )
     self.assertIsNotNone(lowerCamelCase_    )

def      _lowerCAmelCase(	):
  UpperCAmelCase					      =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
  return image






@require_torch
@require_vision
class 						__magic_name__    (       unittest.TestCase    ):


 @cached_property
 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Optional[Any]:
   return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )


 @slow
 def _UpperCamelCase	(						self		: str    )    ->      str:
   UpperCAmelCase					      =  CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    ).to(lowerCamelCase_    )

   UpperCAmelCase					      =  self.default_image_processor
   UpperCAmelCase					      =  prepare_img()
   UpperCAmelCase					      =  image_processor(images=lowerCamelCase_			,						return_tensors="pt"    ).to(lowerCamelCase_    )

   # forward pass
   with torch.no_grad():
     UpperCAmelCase					      =  model(**lowerCamelCase_    )

   # verify the logits
   UpperCAmelCase					      =  torch.Size((1, 1_0_0_0)    )
   self.assertEqual(outputs.logits.shape			,						lowerCamelCase_    )

   UpperCAmelCase					      =  torch.tensor([0.9_285, 0.9_015, -0.3_150]    ).to(lowerCamelCase_    )

   self.assertTrue(torch.allclose(outputs.logits[0, :3]			,						lowerCamelCase_			,						atol=1e-4    )    )






from __future__ import annotations

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

lowerCAmelCase__       = {"UserAgent": UserAgent().random}
def      _lowerCAmelCase(	__A			):
  UpperCAmelCase					      =  script.contents[0]
  UpperCAmelCase					      =  json.loads(data[data.find("{\"config\""			) : -1]			)
  return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]






class 						__magic_name__    :


 def __init__(						self		: Optional[Any]			,						lowerCAmelCase__		: Optional[int]    )    ->      Any:
   UpperCAmelCase					      =  f"https://www.instagram.com/{username}/"
   UpperCAmelCase					      =  self.get_json()


 def _UpperCamelCase	(						self		: List[str]    )    ->      dict:
   UpperCAmelCase					      =  requests.get(self.url			,						headers=lowerCAmelCase__    ).text
   UpperCAmelCase					      =  BeautifulSoup(lowerCAmelCase__			,						"html.parser"    ).find_all("script"    )
   try:
     return extract_user_profile(scripts[4]    )
   except (json.decoder.JSONDecodeError, KeyError):
     return extract_user_profile(scripts[3]    )


 def __repr__(						self		: Tuple    )    ->      str:
   return f"{self.__class__.__name__}('{self.username}')"


 def __str__(						self		: Optional[int]    )    ->      str:
   return f"{self.fullname} ({self.username}) is {self.biography}"


 @property
 def _UpperCamelCase	(						self		: Any    )    ->      str:
   return self.user_data["username"]


 @property
 def _UpperCamelCase	(						self		: List[Any]    )    ->      str:
   return self.user_data["full_name"]


 @property
 def _UpperCamelCase	(						self		: List[str]    )    ->      str:
   return self.user_data["biography"]


 @property
 def _UpperCamelCase	(						self		: Optional[int]    )    ->      str:
   return self.user_data["business_email"]


 @property
 def _UpperCamelCase	(						self		: str    )    ->      str:
   return self.user_data["external_url"]


 @property
 def _UpperCamelCase	(						self		: int    )    ->      int:
   return self.user_data["edge_followed_by"]["count"]


 @property
 def _UpperCamelCase	(						self		: List[Any]    )    ->      int:
   return self.user_data["edge_follow"]["count"]


 @property
 def _UpperCamelCase	(						self		: List[str]    )    ->      int:
   return self.user_data["edge_owner_to_timeline_media"]["count"]


 @property
 def _UpperCamelCase	(						self		: Tuple    )    ->      str:
   return self.user_data["profile_pic_url_hd"]


 @property
 def _UpperCamelCase	(						self		: Optional[int]    )    ->      bool:
   return self.user_data["is_verified"]


 @property
 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      bool:
   return self.user_data["is_private"]

def      _lowerCAmelCase(	__A = "github"			):
  import os

  if os.environ.get("CI"			):
    return  # test failing on GitHub Actions
  UpperCAmelCase					      =  InstagramUser(__A			)
  assert instagram_user.user_data
  assert isinstance(instagram_user.user_data   ,       __A			)
  assert instagram_user.username == username
  if username != "github":
    return
  assert instagram_user.fullname == "GitHub"
  assert instagram_user.biography == "Built for developers."
  assert instagram_user.number_of_posts > 150
  assert instagram_user.number_of_followers > 120000
  assert instagram_user.number_of_followings > 15
  assert instagram_user.email == "support@github.com"
  assert instagram_user.website == "https://github.com/readme"
  assert instagram_user.profile_picture_url.startswith("https://instagram."			)
  assert instagram_user.is_verified is True
  assert instagram_user.is_private is False


if __name__ == "__main__":
      import doctest

      doctest.testmod()
      lowerCAmelCase__       = InstagramUser("github")
      print(instagram_user)
      print(f"{instagram_user.number_of_posts = }")
      print(f"{instagram_user.number_of_followers = }")
      print(f"{instagram_user.number_of_followings = }")
      print(f"{instagram_user.email = }")
      print(f"{instagram_user.website = }")
      print(f"{instagram_user.profile_picture_url = }")
      print(f"{instagram_user.is_verified = }")
      print(f"{instagram_user.is_private = }")



