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 	__snake_case      :
 def __init__(     self						,      snake_case__						,      snake_case__=13						,      snake_case__=30						,      snake_case__=2						,      snake_case__=3						,      snake_case__=True						,      snake_case__=True						,      snake_case__=32						,      snake_case__=2						,      snake_case__=4						,      snake_case__=37						,      snake_case__="gelu"						,      snake_case__=0.1						,      snake_case__=0.1						,      snake_case__=10						,      snake_case__=0.02						,      snake_case__=3						,      snake_case__=None						,      snake_case__=2						,      )		->							List[Any]:
       '''simple docstring'''





       UpperCAmelCase			:       Optional[Any]			     =parent
       UpperCAmelCase			:       Any			     =batch_size
       UpperCAmelCase			:       Union[str, Any]			     =image_size
       UpperCAmelCase			:       Optional[int]			     =patch_size
       UpperCAmelCase			:       Dict			     =num_channels
       UpperCAmelCase			:       Any			     =is_training
       UpperCAmelCase			:       int			     =use_labels
       UpperCAmelCase			:       Optional[Any]			     =hidden_size
       UpperCAmelCase			:       Optional[Any]			     =num_hidden_layers
       UpperCAmelCase			:       List[Any]			     =num_attention_heads
       UpperCAmelCase			:       Dict			     =intermediate_size
       UpperCAmelCase			:       int			     =hidden_act
       UpperCAmelCase			:       List[Any]			     =hidden_dropout_prob
       UpperCAmelCase			:       List[str]			     =attention_probs_dropout_prob
       UpperCAmelCase			:       List[str]			     =type_sequence_label_size
       UpperCAmelCase			:       Optional[Any]			     =initializer_range
       UpperCAmelCase			:       int			     =scope
       UpperCAmelCase			:       Tuple			     =encoder_stride

       # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
       UpperCAmelCase			:       List[str]			     =(image_size // patch_size) ** 2
       UpperCAmelCase			:       Any			     =num_patches + 2
 def 		UpperCAmelCase__				(     self  )		->							Optional[int]:
       '''simple docstring'''





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

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

       UpperCAmelCase			:       Any			     =self.get_config()

       return config, pixel_values, labels
 def 		UpperCAmelCase__				(     self  )		->							str:
       '''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=snake_case__						,      initializer_range=self.initializer_range						,      encoder_stride=self.encoder_stride						,      )
 def 		UpperCAmelCase__				(     self						,      snake_case__						,      snake_case__						,      snake_case__  )		->							List[str]:
       '''simple docstring'''





       UpperCAmelCase			:       Optional[Any]			     =TFDeiTModel(config=snake_case__  )
       UpperCAmelCase			:       int			     =model(snake_case__  )
       self.parent.assertEqual(result.last_hidden_state.shape						,      (self.batch_size, self.seq_length, self.hidden_size)  )
 def 		UpperCAmelCase__				(     self						,      snake_case__						,      snake_case__						,      snake_case__  )		->							List[Any]:
       '''simple docstring'''





       UpperCAmelCase			:       int			     =TFDeiTForMaskedImageModeling(config=snake_case__  )
       UpperCAmelCase			:       List[str]			     =model(snake_case__  )
       self.parent.assertEqual(
           result.reconstruction.shape						,      (self.batch_size, self.num_channels, self.image_size, self.image_size)  )

       # test greyscale images
       UpperCAmelCase			:       List[Any]			     =1
       UpperCAmelCase			:       List[str]			     =TFDeiTForMaskedImageModeling(snake_case__  )

       UpperCAmelCase			:       Optional[Any]			     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
       UpperCAmelCase			:       List[Any]			     =model(snake_case__  )
       self.parent.assertEqual(result.reconstruction.shape						,      (self.batch_size, 1, self.image_size, self.image_size)  )
 def 		UpperCAmelCase__				(     self						,      snake_case__						,      snake_case__						,      snake_case__  )		->							Any:
       '''simple docstring'''





       UpperCAmelCase			:       List[Any]			     =self.type_sequence_label_size
       UpperCAmelCase			:       List[Any]			     =TFDeiTForImageClassification(snake_case__  )
       UpperCAmelCase			:       Any			     =model(snake_case__						,      labels=snake_case__  )
       self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.type_sequence_label_size)  )

       # test greyscale images
       UpperCAmelCase			:       str			     =1
       UpperCAmelCase			:       str			     =TFDeiTForImageClassification(snake_case__  )

       UpperCAmelCase			:       List[str]			     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
       UpperCAmelCase			:       Dict			     =model(snake_case__						,      labels=snake_case__  )
       self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.type_sequence_label_size)  )






 def 		UpperCAmelCase__				(     self  )		->							Any:
       '''simple docstring'''





       UpperCAmelCase			:       Tuple			     =self.prepare_config_and_inputs()
       UpperCAmelCase     ,  UpperCAmelCase     ,  UpperCAmelCase			:       Dict			     =config_and_inputs
       UpperCAmelCase			:       Optional[int]			     ={'''pixel_values''': pixel_values}
       return config, inputs_dict







@require_tf
class 	__snake_case      (   lowerCamelCase__    ,      lowerCamelCase__    ,      unittest.TestCase      ):
 __lowerCamelCase			:      Tuple           =					(
     (
         TFDeiTModel,
         TFDeiTForImageClassification,
         TFDeiTForImageClassificationWithTeacher,
         TFDeiTForMaskedImageModeling,
     )
     if is_tf_available()
     else ()
 )
 __lowerCamelCase			:      int           =					(
     {
         """feature-extraction""": TFDeiTModel,
         """image-classification""": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
     }
     if is_tf_available()
     else {}
 )

 __lowerCamelCase			:      Union[str, Any]           =					False
 __lowerCamelCase			:      str           =					False
 __lowerCamelCase			:      str           =					False
 __lowerCamelCase			:      Union[str, Any]           =					False
 def 		UpperCAmelCase__				(     self  )		->							Any:
       '''simple docstring'''





       UpperCAmelCase			:       Any			     =TFDeiTModelTester(self  )
       UpperCAmelCase			:       Optional[int]			     =ConfigTester(self						,      config_class=snake_case__						,      has_text_modality=snake_case__						,      hidden_size=37  )
 def 		UpperCAmelCase__				(     self  )		->							Union[str, Any]:
       '''simple docstring'''





       self.config_tester.run_common_tests()
 @unittest.skip(reason='''DeiT does not use inputs_embeds'''  )
 def 		UpperCAmelCase__				(     self  )		->							Optional[int]:
       '''simple docstring'''





       pass
 def 		UpperCAmelCase__				(     self  )		->							Tuple:
       '''simple docstring'''





       UpperCAmelCase     ,  UpperCAmelCase			:       Any			     =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             UpperCAmelCase			:       Optional[Any]			     =model_class(snake_case__  )
             self.assertIsInstance(model.get_input_embeddings()						,      (tf.keras.layers.Layer)  )
             UpperCAmelCase			:       Optional[int]			     =model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(snake_case__						,      tf.keras.layers.Dense  )  )
 def 		UpperCAmelCase__				(     self  )		->							List[Any]:
       '''simple docstring'''





       UpperCAmelCase     ,  UpperCAmelCase			:       Any			     =self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCAmelCase			:       Dict			     =['''pixel_values''']
             self.assertListEqual(arg_names[:1]						,      snake_case__  )
 def 		UpperCAmelCase__				(     self  )		->							str:
       '''simple docstring'''





       UpperCAmelCase			:       Any			     =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*snake_case__  )
 def 		UpperCAmelCase__				(     self  )		->							Optional[Any]:
       '''simple docstring'''





       UpperCAmelCase			:       int			     =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*snake_case__  )
 def 		UpperCAmelCase__				(     self  )		->							Dict:
       '''simple docstring'''





       UpperCAmelCase			:       List[str]			     =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*snake_case__  )
 def 		UpperCAmelCase__				(     self						,      snake_case__						,      snake_case__						,      snake_case__=False  )		->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase			:       Dict			     =super()._prepare_for_class(snake_case__						,      snake_case__						,      return_labels=snake_case__  )

       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 		UpperCAmelCase__				(     self  )		->							Tuple:
       '''simple docstring'''





       for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCAmelCase			:       Dict			     =TFDeiTModel.from_pretrained(snake_case__  )
             self.assertIsNotNone(snake_case__  )





def      lowerCAmelCase_       ( )->     str:






      '''simple docstring'''





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







@require_tf
@require_vision
class 	__snake_case      (   unittest.TestCase      ):
 @cached_property
 def 		UpperCAmelCase__				(     self  )		->							Any:
       '''simple docstring'''





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






 @slow
 def 		UpperCAmelCase__				(     self  )		->							Any:
       '''simple docstring'''





       UpperCAmelCase			:       Union[str, Any]			     =TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''  )

       UpperCAmelCase			:       str			     =self.default_image_processor
       UpperCAmelCase			:       Any			     =prepare_img()
       UpperCAmelCase			:       Optional[int]			     =image_processor(images=snake_case__						,      return_tensors='''tf'''  )

       # forward pass
       UpperCAmelCase			:       Any			     =model(**snake_case__  )

       # verify the logits
       UpperCAmelCase			:       Any			     =tf.TensorShape((1, 1000)  )
       self.assertEqual(outputs.logits.shape						,      snake_case__  )

       UpperCAmelCase			:       Dict			     =tf.constant([-1.0266, 0.1912, -1.2861]  )

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



import argparse
import math
import traceback

import dateutil.parser as date_parser
import requests
def      a      (			A__	:   Dict     )    ->      str:





      """simple docstring"""



      _lowercase	       ={}

      _lowercase	       =job['started_at']
      _lowercase	       =job['completed_at']

      _lowercase	       =date_parser.parse(A__     )
      _lowercase	       =date_parser.parse(A__     )

      _lowercase	       =round((end_datetime - start_datetime).total_seconds() / 60.0     )

      _lowercase	       =start
      _lowercase	       =end
      _lowercase	       =duration_in_min

      return job_info
def      a      (			A__	:   Dict      ,   A__	:   str=None     )    ->      Tuple:





      """simple docstring"""



      _lowercase	       =None
      if token is not None:
            _lowercase	       ={'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''}

      _lowercase	       =F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100'''
      _lowercase	       =requests.get(A__      ,   headers=A__     ).json()
      _lowercase	       ={}

      try:
            job_time.update({job['name']: extract_time_from_single_job(A__     ) for job in result['jobs']}     )
            _lowercase	       =math.ceil((result['total_count'] - 100) / 100     )

            for i in range(A__     ):
                  _lowercase	       =requests.get(url + F'''&page={i + 2}'''      ,   headers=A__     ).json()
                  job_time.update({job['name']: extract_time_from_single_job(A__     ) for job in result['jobs']}     )

            return job_time
      except Exception:
            print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}'''     )

      return {}


if __name__ == "__main__":
  lowercase_									=   argparse.ArgumentParser()
  # Required parameters
  parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.')
  lowercase_									=   parser.parse_args()

  lowercase_									=   get_job_time(args.workflow_run_id)
  lowercase_									=   dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True))

  for k, v in job_time.items():
    print(f"{k}: {v['duration']}")


