




from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
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 (
					    TFDeiTForImageClassification,
					    TFDeiTForImageClassificationWithTeacher,
					    TFDeiTForMaskedImageModeling,
					    TFDeiTModel,
					)
					from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import DeiTImageProcessor







class        __lowerCAmelCase					:

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__     ,		lowerCamelCase__=13     ,		lowerCamelCase__=30     ,		lowerCamelCase__=2     ,		lowerCamelCase__=3     ,		lowerCamelCase__=True     ,		lowerCamelCase__=True     ,		lowerCamelCase__=32     ,		lowerCamelCase__=2     ,		lowerCamelCase__=4     ,		lowerCamelCase__=37     ,		lowerCamelCase__="gelu"     ,		lowerCamelCase__=0.1     ,		lowerCamelCase__=0.1     ,		lowerCamelCase__=10     ,		lowerCamelCase__=0.02     ,		lowerCamelCase__=3     ,		lowerCamelCase__=None     ,		lowerCamelCase__=2     ,		)       -> Any:



							'''simple docstring'''
							__lowerCamelCase									=       parent
							__lowerCamelCase									=       batch_size
							__lowerCamelCase									=       image_size
							__lowerCamelCase									=       patch_size
							__lowerCamelCase									=       num_channels
							__lowerCamelCase									=       is_training
							__lowerCamelCase									=       use_labels
							__lowerCamelCase									=       hidden_size
							__lowerCamelCase									=       num_hidden_layers
							__lowerCamelCase									=       num_attention_heads
							__lowerCamelCase									=       intermediate_size
							__lowerCamelCase									=       hidden_act
							__lowerCamelCase									=       hidden_dropout_prob
							__lowerCamelCase									=       attention_probs_dropout_prob
							__lowerCamelCase									=       type_sequence_label_size
							__lowerCamelCase									=       initializer_range
							__lowerCamelCase									=       scope
							__lowerCamelCase									=       encoder_stride

							# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
							__lowerCamelCase									=       (image_size // patch_size) ** 2
							__lowerCamelCase									=       num_patches + 2


			def  lowercase_       ( self				)       -> Optional[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

							__lowerCamelCase									=       self.get_config()

							return config, pixel_values, labels


			def  lowercase_       ( self				)       -> Optional[int]:



							'''simple docstring'''
							return DeiTConfig(
							    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=lowerCamelCase__     ,		initializer_range=self.initializer_range     ,		encoder_stride=self.encoder_stride     ,		)


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)       -> Optional[int]:



							'''simple docstring'''
							__lowerCamelCase									=       TFDeiTModel(config=lowerCamelCase__				)
							__lowerCamelCase									=       model(lowerCamelCase__				)
							self.parent.assertEqual(result.last_hidden_state.shape     ,		(self.batch_size, self.seq_length, self.hidden_size)				)


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       TFDeiTForMaskedImageModeling(config=lowerCamelCase__				)
							__lowerCamelCase									=       model(lowerCamelCase__				)
							self.parent.assertEqual(
							    result.reconstruction.shape     ,		(self.batch_size, self.num_channels, self.image_size, self.image_size)				)

							# test greyscale images
							__lowerCamelCase									=       1
							__lowerCamelCase									=       TFDeiTForMaskedImageModeling(lowerCamelCase__				)

							__lowerCamelCase									=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
							__lowerCamelCase									=       model(lowerCamelCase__				)
							self.parent.assertEqual(result.reconstruction.shape     ,		(self.batch_size, 1, self.image_size, self.image_size)				)


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)       -> Dict:



							'''simple docstring'''
							__lowerCamelCase									=       self.type_sequence_label_size
							__lowerCamelCase									=       TFDeiTForImageClassification(lowerCamelCase__				)
							__lowerCamelCase									=       model(lowerCamelCase__     ,		labels=lowerCamelCase__				)
							self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.type_sequence_label_size)				)

							# test greyscale images
							__lowerCamelCase									=       1
							__lowerCamelCase									=       TFDeiTForImageClassification(lowerCamelCase__				)

							__lowerCamelCase									=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
							__lowerCamelCase									=       model(lowerCamelCase__     ,		labels=lowerCamelCase__				)
							self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.type_sequence_label_size)				)






			def  lowercase_       ( self				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       self.prepare_config_and_inputs()
							__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase									=       config_and_inputs
							__lowerCamelCase									=       {'pixel_values': pixel_values}
							return config, inputs_dict







@require_tf
class        __lowerCAmelCase					(			__magic_name__     ,							__magic_name__     ,							unittest.TestCase					):

			"""simple docstring"""







			snake_case_  						=			(
			    (
			        TFDeiTModel,
			        TFDeiTForImageClassification,
			        TFDeiTForImageClassificationWithTeacher,
			        TFDeiTForMaskedImageModeling,
			    )
			    if is_tf_available()
			    else ()
			)
			snake_case_  						=			(
			    {
			        '''feature-extraction''': TFDeiTModel,
			        '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
			    }
			    if is_tf_available()
			    else {}
			)

			snake_case_  						=			False
			snake_case_  						=			False
			snake_case_  						=			False
			snake_case_  						=			False


			def  lowercase_       ( self				)       -> Tuple:



							'''simple docstring'''
							__lowerCamelCase									=       TFDeiTModelTester(self				)
							__lowerCamelCase									=       ConfigTester(self     ,		config_class=lowerCamelCase__     ,		has_text_modality=lowerCamelCase__     ,		hidden_size=37				)


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



							'''simple docstring'''
							self.config_tester.run_common_tests()


			@unittest.skip(reason='DeiT does not use inputs_embeds'				)
			def  lowercase_       ( self				)       -> str:



							'''simple docstring'''
							pass


			def  lowercase_       ( self				)       -> Dict:



							'''simple docstring'''
							__lowerCamelCase			,		__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs_for_common()

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


			def  lowercase_       ( self				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase			,		__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs_for_common()

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

											__lowerCamelCase									=       ['pixel_values']
											self.assertListEqual(arg_names[:1]     ,		lowerCamelCase__				)


			def  lowercase_       ( self				)       -> int:



							'''simple docstring'''
							__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__				)


			def  lowercase_       ( self				)       -> Optional[int]:



							'''simple docstring'''
							__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase__				)


			def  lowercase_       ( self				)       -> Any:



							'''simple docstring'''
							__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__				)


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__=False				)       -> Tuple:



							'''simple docstring'''
							__lowerCamelCase									=       super()._prepare_for_class(lowerCamelCase__     ,		lowerCamelCase__     ,		return_labels=lowerCamelCase__				)

							if return_labels:
											if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call				).parameters:
															del inputs_dict["labels"]

							return inputs_dict






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



							'''simple docstring'''
							for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCamelCase									=       TFDeiTModel.from_pretrained(lowerCamelCase__				)
											self.assertIsNotNone(lowerCamelCase__				)







def      lowerCamelCase_						(			)	->			List[str]:





				"""simple docstring"""


				__lowerCamelCase									=       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
				return image







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

			"""simple docstring"""







			@cached_property
			def  lowercase_       ( self				)       -> List[str]:



							'''simple docstring'''
							return (
							    DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224'				)
							    if is_vision_available()
							    else None
							)






			@slow
			def  lowercase_       ( self				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224'				)

							__lowerCamelCase									=       self.default_image_processor
							__lowerCamelCase									=       prepare_img()
							__lowerCamelCase									=       image_processor(images=lowerCamelCase__     ,		return_tensors='tf'				)

							# forward pass
							__lowerCamelCase									=       model(**lowerCamelCase__				)

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

							__lowerCamelCase									=       tf.constant([-1.02_66, 0.19_12, -1.28_61]				)

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








from datetime import datetime as dt
import os

from github import Github


__A								=       [
    "good first issue",
    "good second issue",
    "good difficult issue",
    "feature request",
    "new model",
    "wip",
]







def      lowerCamelCase_						(			)	->			int:





				"""simple docstring"""


				__lowerCamelCase									=       Github(os.environ['GITHUB_TOKEN'] )
				__lowerCamelCase									=       g.get_repo('huggingface/transformers' )
				__lowerCamelCase									=       repo.get_issues(state='open' )

				for issue in open_issues:
								__lowerCamelCase									=       sorted([comment for comment in issue.get_comments()]					,	key=lambda UpperCamelCase__ : i.created_at					,	reverse=UpperCamelCase__ )
								__lowerCamelCase									=       comments[0] if len(UpperCamelCase__ ) > 0 else None
								if (
								    last_comment is not None
								    and last_comment.user.login == "github-actions[bot]"
								    and (dt.utcnow() - issue.updated_at).days > 7
								    and (dt.utcnow() - issue.created_at).days >= 30
								    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
								):
												# print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
												issue.edit(state='closed' )
								elif (
								    (dt.utcnow() - issue.updated_at).days > 23
								    and (dt.utcnow() - issue.created_at).days >= 30
								    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
								):
												# print(f"Would add stale comment to {issue.number}")
												issue.create_comment(
												    'This issue has been automatically marked as stale because it has not had '
												    'recent activity. If you think this still needs to be addressed '
												    'please comment on this thread.\n\nPlease note that issues that do not follow the '
												    '[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) '
												    'are likely to be ignored.' )


if __name__ == "__main__":
					main()


