




'''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     _a						(			__lowerCamelCase				):
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.config_class(**self.inputs_dict       )
           self.parent.assertTrue(hasattr(a_     ,       '''embed_dim'''       )       )
           self.parent.assertTrue(hasattr(a_     ,       '''num_heads'''       )       )






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



           '''simple docstring'''

           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 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

           UpperCAmelCase     =	self.get_config()
           return config, pixel_values, labels
       def 					A   (			self		:			Union[str, Any]       ):



           '''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 					A   (			self		:			Optional[Any]     ,       lowercase		:			str     ,       lowercase		:			List[str]     ,       lowercase		:			str       ):



           '''simple docstring'''

           UpperCAmelCase     =	TFCvtModel(config=a_       )
           UpperCAmelCase     =	model(a_     ,       training=a_       )
           UpperCAmelCase     =	(self.image_size, self.image_size)
           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 					A   (			self		:			Optional[Any]     ,       lowercase		:			Any     ,       lowercase		:			int     ,       lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.num_labels
           UpperCAmelCase     =	TFCvtForImageClassification(a_       )
           UpperCAmelCase     =	model(a_     ,       labels=a_     ,       training=a_       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.num_labels)       )







       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.prepare_config_and_inputs()
           UpperCAmelCase     =	config_and_inputs
           UpperCAmelCase     =	{"pixel_values": pixel_values}
           return config, inputs_dict






@require_tf
class     _a						(			__lowerCamelCase							,							__lowerCamelCase							,							unittest.TestCase				):
       __a       :  int            =      (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
       __a       :  Union[str, Any]            =      (
           {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
           if is_tf_available()
           else {}
       )
       __a       :  Optional[int]            =      False
       __a       :  Tuple            =      False
       __a       :  List[Any]            =      False
       __a       :  Optional[Any]            =      False
       __a       :  Optional[int]            =      False
       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	TFCvtModelTester(self       )
           UpperCAmelCase     =	TFCvtConfigTester(self     ,       config_class=a_     ,       has_text_modality=a_     ,       hidden_size=37       )
       def 					A   (			self		:			List[str]       ):



           '''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 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           pass
       @unittest.skip(reason='''Cvt does not use inputs_embeds'''       )
       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

           pass
       @unittest.skip(reason='''Cvt does not support input and output embeddings'''       )
       def 					A   (			self		:			Union[str, Any]       ):



           '''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 					A   (			self		:			str       ):



           '''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 					A   (			self		:			List[Any]       ):



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



           '''simple docstring'''

           UpperCAmelCase     =	tf.keras.mixed_precision.Policy('''mixed_float16'''       )
           tf.keras.mixed_precision.set_global_policy(a_       )
           super().test_keras_fit()
           tf.keras.mixed_precision.set_global_policy('''float32'''       )
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs_for_common()

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

               UpperCAmelCase     =	["pixel_values"]
               self.assertListEqual(arg_names[:1]     ,       a_       )
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           def check_hidden_states_output(lowercase		:			Optional[int]     ,       lowercase		:			Dict     ,       lowercase		:			int       ):
               UpperCAmelCase     =	model_class(a_       )

               UpperCAmelCase     =	model(**self._prepare_for_class(a_     ,       a_       )       )
               UpperCAmelCase     =	outputs.hidden_states

               UpperCAmelCase     =	len(self.model_tester.depth       )
               self.assertEqual(len(a_       )     ,       a_       )

               # 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     =	self.model_tester.prepare_config_and_inputs_for_common()

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

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

               check_hidden_states_output(a_     ,       a_     ,       a_       )
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*a_       )
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*a_       )







       @slow
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase     =	TFCvtModel.from_pretrained(a_       )
               self.assertIsNotNone(a_       )






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







@require_tf
@require_vision
class     _a						(			unittest.TestCase				):
       @cached_property
       def 					A   (			self		:			Tuple       ):



           '''simple docstring'''

           return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )







       @slow
       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

           UpperCAmelCase     =	self.default_image_processor
           UpperCAmelCase     =	prepare_img()
           UpperCAmelCase     =	image_processor(images=a_     ,       return_tensors='''tf'''       )

           # forward pass
           UpperCAmelCase     =	model(**a_       )

           # verify the logits
           UpperCAmelCase     =	tf.TensorShape((1, 1_000)       )
           self.assertEqual(outputs.logits.shape     ,       a_       )

           UpperCAmelCase     =	tf.constant([0.9285, 0.9015, -0.3150]       )
           self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,       a_     ,       atol=1E-4       )       )









'''simple docstring'''







from __future__ import annotations

import requests





def 		snake_case_							(_a			:							str  ):
    UpperCAmelCase     =	F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty"
    return requests.get(_a  ).json()





def 		snake_case_							(_a			:							int = 1_0  ):
    UpperCAmelCase     =	'''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'''
    UpperCAmelCase     =	requests.get(_a  ).json()[:max_stories]
    return [get_hackernews_story(_a  ) for story_id in story_ids]





def 		snake_case_							(_a			:							int = 1_0  ):
    UpperCAmelCase     =	hackernews_top_stories(_a  )
    return "\n".join('''* [{title}]({url})'''.format(**_a  ) for story in stories  )


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




