




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  _lowerCAmelCase     :

      def __init__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase=13      ,				__UpperCAmelCase=30      ,				__UpperCAmelCase=2      ,				__UpperCAmelCase=3      ,				__UpperCAmelCase=True      ,				__UpperCAmelCase=True      ,				__UpperCAmelCase=32      ,				__UpperCAmelCase=2      ,				__UpperCAmelCase=4      ,				__UpperCAmelCase=37      ,				__UpperCAmelCase="gelu"      ,				__UpperCAmelCase=0.1      ,				__UpperCAmelCase=0.1      ,				__UpperCAmelCase=10      ,				__UpperCAmelCase=0.02      ,				__UpperCAmelCase=3      ,				__UpperCAmelCase=None      ,				):
        lowerCAmelCase__				:  str		       =     parent
        lowerCAmelCase__				:  List[str]		       =     batch_size
        lowerCAmelCase__				:  Union[str, Any]		       =     image_size
        lowerCAmelCase__				:  Dict		       =     patch_size
        lowerCAmelCase__				:  Tuple		       =     num_channels
        lowerCAmelCase__				:  int		       =     is_training
        lowerCAmelCase__				:  Optional[int]		       =     use_labels
        lowerCAmelCase__				:  Any		       =     hidden_size
        lowerCAmelCase__				:  Any		       =     num_hidden_layers
        lowerCAmelCase__				:  int		       =     num_attention_heads
        lowerCAmelCase__				:  List[Any]		       =     intermediate_size
        lowerCAmelCase__				:  Optional[Any]		       =     hidden_act
        lowerCAmelCase__				:  Any		       =     hidden_dropout_prob
        lowerCAmelCase__				:  str		       =     attention_probs_dropout_prob
        lowerCAmelCase__				:  Optional[int]		       =     type_sequence_label_size
        lowerCAmelCase__				:  List[Any]		       =     initializer_range
        lowerCAmelCase__				:  List[Any]		       =     scope

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

      def 	__magic_name__(   self		):
        lowerCAmelCase__				:  Tuple		       =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

        lowerCAmelCase__				:  Dict		       =     None
        if self.use_labels:
          lowerCAmelCase__				:  Union[str, Any]		       =     ids_tensor([self.batch_size]      ,				self.type_sequence_label_size		)

        lowerCAmelCase__				:  Tuple		       =     self.get_config()

        return config, pixel_values, labels

      def 	__magic_name__(   self		):
        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=lowerCAmelCase_      ,				initializer_range=self.initializer_range      ,				)

      def 	__magic_name__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase      ,				__UpperCAmelCase		):
        lowerCAmelCase__				:  Any		       =     TFViTModel(config=lowerCAmelCase_		)
        lowerCAmelCase__				:  List[Any]		       =     model(lowerCAmelCase_      ,				training=lowerCAmelCase_		)
        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.
        lowerCAmelCase__				:  Dict		       =     self.image_size // 2
        lowerCAmelCase__				:  List[str]		       =     pixel_values[:, :, :image_size, :image_size]
        lowerCAmelCase__				:  Union[str, Any]		       =     model(lowerCAmelCase_      ,				interpolate_pos_encoding=lowerCAmelCase_      ,				training=lowerCAmelCase_		)
        lowerCAmelCase__				:  Tuple		       =     (image_size // self.patch_size) ** 2 + 1
        self.parent.assertEqual(result.last_hidden_state.shape      ,				(self.batch_size, seq_length, self.hidden_size)		)

      def 	__magic_name__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase      ,				__UpperCAmelCase		):
        lowerCAmelCase__				:  Dict		       =     self.type_sequence_label_size
        lowerCAmelCase__				:  List[Any]		       =     TFViTForImageClassification(lowerCAmelCase_		)
        lowerCAmelCase__				:  Union[str, Any]		       =     model(lowerCAmelCase_      ,				labels=lowerCAmelCase_      ,				training=lowerCAmelCase_		)
        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.
        lowerCAmelCase__				:  Optional[int]		       =     self.image_size // 2
        lowerCAmelCase__				:  int		       =     pixel_values[:, :, :image_size, :image_size]
        lowerCAmelCase__				:  Tuple		       =     model(lowerCAmelCase_      ,				interpolate_pos_encoding=lowerCAmelCase_      ,				training=lowerCAmelCase_		)
        self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.type_sequence_label_size)		)

        # test greyscale images
        lowerCAmelCase__				:  Tuple		       =     1
        lowerCAmelCase__				:  List[Any]		       =     TFViTForImageClassification(lowerCAmelCase_		)
        lowerCAmelCase__				:  List[Any]		       =     floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
        lowerCAmelCase__				:  Tuple		       =     model(lowerCAmelCase_		)
        self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.type_sequence_label_size)		)







      def 	__magic_name__(   self		):
        lowerCAmelCase__				:  Union[str, Any]		       =     self.prepare_config_and_inputs()
        lowerCAmelCase__       ,			lowerCAmelCase__       ,			lowerCAmelCase__				:  List[Any]		       =     config_and_inputs
        lowerCAmelCase__				:  Dict		       =     {'''pixel_values''': pixel_values}
        return config, inputs_dict






@require_tf
class  _lowerCAmelCase     (  __UpperCAmelCase    ,			__UpperCAmelCase    ,			unittest.TestCase	):
      A__		     =		(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
      A__		     =		(
          {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
          if is_tf_available()
          else {}
      )

      A__		     =		False
      A__		     =		False
      A__		     =		False

      def 	__magic_name__(   self		):
        lowerCAmelCase__				:  Union[str, Any]		       =     TFViTModelTester(self		)
        lowerCAmelCase__				:  Optional[Any]		       =     ConfigTester(self      ,				config_class=lowerCAmelCase_      ,				has_text_modality=lowerCAmelCase_      ,				hidden_size=37		)

      def 	__magic_name__(   self		):
        self.config_tester.run_common_tests()

      @unittest.skip(reason='''ViT does not use inputs_embeds'''		)
      def 	__magic_name__(   self		):
        pass

      @unittest.skip(reason='''ViT does not use inputs_embeds'''		)
      def 	__magic_name__(   self		):
        pass

      def 	__magic_name__(   self		):
        lowerCAmelCase__       ,			lowerCAmelCase__				:  Any		       =     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          lowerCAmelCase__				:  Optional[Any]		       =     model_class(lowerCAmelCase_		)
          self.assertIsInstance(model.get_input_embeddings()      ,				(tf.keras.layers.Layer)		)
          lowerCAmelCase__				:  List[str]		       =     model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(lowerCAmelCase_      ,				tf.keras.layers.Layer		)		)

      def 	__magic_name__(   self		):
        lowerCAmelCase__       ,			lowerCAmelCase__				:  Optional[int]		       =     self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase__				:  str		       =     ['''pixel_values''']
          self.assertListEqual(arg_names[:1]      ,				lowerCAmelCase_		)

      def 	__magic_name__(   self		):
        lowerCAmelCase__				:  Tuple		       =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase_		)

      def 	__magic_name__(   self		):
        lowerCAmelCase__				:  Optional[Any]		       =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_		)







      @slow
      def 	__magic_name__(   self		):
        lowerCAmelCase__				:  Any		       =     TFViTModel.from_pretrained('''google/vit-base-patch16-224'''		)
        self.assertIsNotNone(lowerCAmelCase_		)



def      __lowerCAmelCase			(					)     ->	List[Any]:
  lowerCAmelCase__				:  Any		       =     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
  return image






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

      @cached_property
      def 	__magic_name__(   self		):
        return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224'''		) if is_vision_available() else None







      @slow
      def 	__magic_name__(   self		):
        lowerCAmelCase__				:  str		       =     TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''		)

        lowerCAmelCase__				:  Union[str, Any]		       =     self.default_image_processor
        lowerCAmelCase__				:  Tuple		       =     prepare_img()
        lowerCAmelCase__				:  Any		       =     image_processor(images=lowerCAmelCase_      ,				return_tensors='''tf'''		)

        # forward pass
        lowerCAmelCase__				:  List[Any]		       =     model(**lowerCAmelCase_		)

        # verify the logits
        lowerCAmelCase__				:  Tuple		       =     tf.TensorShape((1, 1000)		)
        self.assertEqual(outputs.logits.shape      ,				lowerCAmelCase_		)

        lowerCAmelCase__				:  List[str]		       =     tf.constant([-0.2744, 0.8215, -0.0836]		)

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







import os
from datetime import datetime as dt

from github import Github


lowerCAmelCase_					    = [
    """good first issue""",
    """good second issue""",
    """good difficult issue""",
    """enhancement""",
    """new pipeline/model""",
    """new scheduler""",
    """wip""",
]



def      __lowerCAmelCase			(					)     ->	List[Any]:
  lowerCAmelCase__				:  str		       =     Github(os.environ['''GITHUB_TOKEN''']      )
  lowerCAmelCase__				:  str		       =     g.get_repo('''huggingface/diffusers'''      )
  lowerCAmelCase__				:  List[str]		       =     repo.get_issues(state='''open'''      )

  for issue in open_issues:
    lowerCAmelCase__				:  Optional[Any]		       =     sorted(issue.get_comments()	,      key=lambda UpperCamelCase      : i.created_at	,      reverse=UpperCamelCase      )
    lowerCAmelCase__				:  int		       =     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()      )
    ):
      # Closes the issue after 7 days of inactivity since the Stalebot notification.
      issue.edit(state='''closed'''      )
    elif (
        "stale" in issue.get_labels()
        and last_comment is not None
        and last_comment.user.login != "github-actions[bot]"
    ):
      # Opens the issue if someone other than Stalebot commented.
      issue.edit(state='''open'''      )
      issue.remove_from_labels('''stale'''      )
    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()      )
    ):
      # Post a Stalebot notification after 23 days of inactivity.
      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/diffusers/blob/main/CONTRIBUTING.md) '''
          '''are likely to be ignored.'''      )
      issue.add_to_labels('''stale'''      )


if __name__ == "__main__":
     main()

