


"""simple docstring"""







from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
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 TFViTForImageClassification, TFViTModel


if is_vision_available():
		from PIL import Image

		from transformers import ViTImageProcessor




class 			UpperCamelCase_     :

	"""simple docstring"""





	def __init__(			self      :    int      ,      UpperCAmelCase__      :    Tuple      ,      UpperCAmelCase__      :    Tuple=1_3      ,      UpperCAmelCase__      :    Optional[Any]=3_0      ,      UpperCAmelCase__      :    Tuple=2      ,      UpperCAmelCase__      :    Any=3      ,      UpperCAmelCase__      :    List[str]=True      ,      UpperCAmelCase__      :    Tuple=True      ,      UpperCAmelCase__      :    Union[str, Any]=3_2      ,      UpperCAmelCase__      :    str=2      ,      UpperCAmelCase__      :    Optional[Any]=4      ,      UpperCAmelCase__      :    Union[str, Any]=3_7      ,      UpperCAmelCase__      :    int="gelu"      ,      UpperCAmelCase__      :    Any=0.1      ,      UpperCAmelCase__      :    str=0.1      ,      UpperCAmelCase__      :    int=1_0      ,      UpperCAmelCase__      :    Union[str, Any]=0.02      ,      UpperCAmelCase__      :    int=3      ,      UpperCAmelCase__      :    int=None      ,      )	->     Tuple:
						__SCREAMING_SNAKE_CASE						       =    parent
						__SCREAMING_SNAKE_CASE						       =    batch_size
						__SCREAMING_SNAKE_CASE						       =    image_size
						__SCREAMING_SNAKE_CASE						       =    patch_size
						__SCREAMING_SNAKE_CASE						       =    num_channels
						__SCREAMING_SNAKE_CASE						       =    is_training
						__SCREAMING_SNAKE_CASE						       =    use_labels
						__SCREAMING_SNAKE_CASE						       =    hidden_size
						__SCREAMING_SNAKE_CASE						       =    num_hidden_layers
						__SCREAMING_SNAKE_CASE						       =    num_attention_heads
						__SCREAMING_SNAKE_CASE						       =    intermediate_size
						__SCREAMING_SNAKE_CASE						       =    hidden_act
						__SCREAMING_SNAKE_CASE						       =    hidden_dropout_prob
						__SCREAMING_SNAKE_CASE						       =    attention_probs_dropout_prob
						__SCREAMING_SNAKE_CASE						       =    type_sequence_label_size
						__SCREAMING_SNAKE_CASE						       =    initializer_range
						__SCREAMING_SNAKE_CASE						       =    scope

						# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
						__SCREAMING_SNAKE_CASE						       =    (image_size // patch_size) ** 2
						__SCREAMING_SNAKE_CASE						       =    num_patches + 1




	def   UpperCAmelCase_				(			self      :    Union[str, Any]       )	->     Tuple:
						__SCREAMING_SNAKE_CASE						       =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

						__SCREAMING_SNAKE_CASE						       =    None
						if self.use_labels:
											__SCREAMING_SNAKE_CASE						       =    ids_tensor([self.batch_size]      ,      self.type_sequence_label_size       )

						__SCREAMING_SNAKE_CASE						       =    self.get_config()

						return config, pixel_values, labels




	def   UpperCAmelCase_				(			self      :    Union[str, Any]       )	->     Any:
						return ViTConfig(
						    image_size=self.image_size      ,      patch_size=self.patch_size      ,      num_channels=self.num_channels      ,      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      ,      is_decoder=_UpperCAmelCase      ,      initializer_range=self.initializer_range      ,      )




	def   UpperCAmelCase_				(			self      :    List[Any]      ,      UpperCAmelCase__      :    List[str]      ,      UpperCAmelCase__      :    Union[str, Any]      ,      UpperCAmelCase__      :    List[str]       )	->     Any:
						__SCREAMING_SNAKE_CASE						       =    TFViTModel(config=_UpperCAmelCase       )
						__SCREAMING_SNAKE_CASE						       =    model(_UpperCAmelCase      ,      training=_UpperCAmelCase       )
						self.parent.assertEqual(result.last_hidden_state.shape      ,      (self.batch_size, self.seq_length, self.hidden_size)       )

						# Test with an image with different size than the one specified in config.
						__SCREAMING_SNAKE_CASE						       =    self.image_size // 2
						__SCREAMING_SNAKE_CASE						       =    pixel_values[:, :, :image_size, :image_size]
						__SCREAMING_SNAKE_CASE						       =    model(_UpperCAmelCase      ,      interpolate_pos_encoding=_UpperCAmelCase      ,      training=_UpperCAmelCase       )
						__SCREAMING_SNAKE_CASE						       =    (image_size // self.patch_size) ** 2 + 1
						self.parent.assertEqual(result.last_hidden_state.shape      ,      (self.batch_size, seq_length, self.hidden_size)       )




	def   UpperCAmelCase_				(			self      :    Any      ,      UpperCAmelCase__      :    List[str]      ,      UpperCAmelCase__      :    int      ,      UpperCAmelCase__      :    Tuple       )	->     Dict:
						__SCREAMING_SNAKE_CASE						       =    self.type_sequence_label_size
						__SCREAMING_SNAKE_CASE						       =    TFViTForImageClassification(_UpperCAmelCase       )
						__SCREAMING_SNAKE_CASE						       =    model(_UpperCAmelCase      ,      labels=_UpperCAmelCase      ,      training=_UpperCAmelCase       )
						self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.type_sequence_label_size)       )

						# Test with an image with different size than the one specified in config.
						__SCREAMING_SNAKE_CASE						       =    self.image_size // 2
						__SCREAMING_SNAKE_CASE						       =    pixel_values[:, :, :image_size, :image_size]
						__SCREAMING_SNAKE_CASE						       =    model(_UpperCAmelCase      ,      interpolate_pos_encoding=_UpperCAmelCase      ,      training=_UpperCAmelCase       )
						self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.type_sequence_label_size)       )

						# test greyscale images
						__SCREAMING_SNAKE_CASE						       =    1
						__SCREAMING_SNAKE_CASE						       =    TFViTForImageClassification(_UpperCAmelCase       )
						__SCREAMING_SNAKE_CASE						       =    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
						__SCREAMING_SNAKE_CASE						       =    model(_UpperCAmelCase       )
						self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.type_sequence_label_size)       )




	def   UpperCAmelCase_				(			self      :    List[Any]       )	->     Optional[int]:
						__SCREAMING_SNAKE_CASE						       =    self.prepare_config_and_inputs()
						__SCREAMING_SNAKE_CASE						       =    config_and_inputs
						__SCREAMING_SNAKE_CASE						       =    {'''pixel_values''': pixel_values}
						return config, inputs_dict




@require_tf
class 			UpperCamelCase_     (			_UpperCAmelCase      ,  _UpperCAmelCase      ,  unittest.TestCase):

	"""simple docstring"""





	snake_case__    :  int    =      (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
	snake_case__    :  Optional[int]    =      (
	    {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification}
	    if is_tf_available()
	    else {}
	)

	snake_case__    :  Any    =      False
	snake_case__    :  Any    =      False
	snake_case__    :  List[str]    =      False




	def   UpperCAmelCase_				(			self      :    Any       )	->     Any:
						__SCREAMING_SNAKE_CASE						       =    TFViTModelTester(self       )
						__SCREAMING_SNAKE_CASE						       =    ConfigTester(self      ,      config_class=_UpperCAmelCase      ,      has_text_modality=_UpperCAmelCase      ,      hidden_size=3_7       )




	def   UpperCAmelCase_				(			self      :    Any       )	->     int:
						self.config_tester.run_common_tests()




	@unittest.skip(reason="ViT does not use inputs_embeds"       )
	def   UpperCAmelCase_				(			self      :    Optional[Any]       )	->     Any:
						pass




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




	def   UpperCAmelCase_				(			self      :    int       )	->     Union[str, Any]:
						__SCREAMING_SNAKE_CASE						       =    self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											__SCREAMING_SNAKE_CASE						       =    model_class(_UpperCAmelCase       )
											self.assertIsInstance(model.get_input_embeddings()      ,      (tf.keras.layers.Layer)       )
											__SCREAMING_SNAKE_CASE						       =    model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(_UpperCAmelCase      ,      tf.keras.layers.Layer       )       )




	def   UpperCAmelCase_				(			self      :    Tuple       )	->     List[str]:
						__SCREAMING_SNAKE_CASE						       =    self.model_tester.prepare_config_and_inputs_for_common()

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

											__SCREAMING_SNAKE_CASE						       =    ['''pixel_values''']
											self.assertListEqual(arg_names[:1]      ,      _UpperCAmelCase       )




	def   UpperCAmelCase_				(			self      :    Optional[Any]       )	->     Dict:
						__SCREAMING_SNAKE_CASE						       =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*_UpperCAmelCase       )




	def   UpperCAmelCase_				(			self      :    Optional[int]       )	->     Optional[int]:
						__SCREAMING_SNAKE_CASE						       =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase       )




	@slow
	def   UpperCAmelCase_				(			self      :    List[str]       )	->     Tuple:
						__SCREAMING_SNAKE_CASE						       =    TFViTModel.from_pretrained("google/vit-base-patch16-224"       )
						self.assertIsNotNone(_UpperCAmelCase       )




def        UpperCAmelCase__	():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
					return image




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

	"""simple docstring"""





	@cached_property
	def   UpperCAmelCase_				(			self      :    List[str]       )	->     Dict:
						return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"       ) if is_vision_available() else None




	@slow
	def   UpperCAmelCase_				(			self      :    Tuple       )	->     List[str]:
						__SCREAMING_SNAKE_CASE						       =    TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"       )

						__SCREAMING_SNAKE_CASE						       =    self.default_image_processor
						__SCREAMING_SNAKE_CASE						       =    prepare_img()
						__SCREAMING_SNAKE_CASE						       =    image_processor(images=_UpperCAmelCase      ,      return_tensors="tf"       )

						# forward pass
						__SCREAMING_SNAKE_CASE						       =    model(**_UpperCAmelCase       )

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

						__SCREAMING_SNAKE_CASE						       =    tf.constant([-0.2_744, 0.8_215, -0.0_836]       )

						tf.debugging.assert_near(outputs.logits[0, :3]      ,      _UpperCAmelCase      ,      atol=1E-4       )









"""simple docstring"""







from __future__ import annotations

import requests




def        UpperCAmelCase__	(lowerCAmelCase_       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty"""
					return requests.get(lowerCAmelCase_       ).json()




def        UpperCAmelCase__	(lowerCAmelCase_ = 10       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
					__SCREAMING_SNAKE_CASE						       =    requests.get(lowerCAmelCase_       ).json()[:max_stories]
					return [get_hackernews_story(lowerCAmelCase_       ) for story_id in story_ids]




def        UpperCAmelCase__	(lowerCAmelCase_ = 10       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    hackernews_top_stories(lowerCAmelCase_       )
					return "\n".join("* [{title}]({url})".format(**lowerCAmelCase_       ) for story in stories       )


if __name__ == "__main__":
		print(hackernews_top_stories_as_markdown())
