

import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import UperNetForSemanticSegmentation
  from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor





class  __lowerCAmelCase     :




  def __init__(				self							,   lowerCAmelCase							,   lowerCAmelCase=13							,   lowerCAmelCase=32							,   lowerCAmelCase=3							,   lowerCAmelCase=4							,   lowerCAmelCase=[10, 20, 30, 40]							,   lowerCAmelCase=[2, 2, 3, 2]							,   lowerCAmelCase=True							,   lowerCAmelCase=True							,   lowerCAmelCase=37							,   lowerCAmelCase="gelu"							,   lowerCAmelCase=10							,   lowerCAmelCase=0.02							,   lowerCAmelCase=["stage2", "stage3", "stage4"]							,   lowerCAmelCase=3							,   lowerCAmelCase=None							,   )  -> Union[str, Any]:
        '''simple docstring'''






        _lowercase	       =parent
        _lowercase	       =batch_size
        _lowercase	       =image_size
        _lowercase	       =num_channels
        _lowercase	       =num_stages
        _lowercase	       =hidden_sizes
        _lowercase	       =depths
        _lowercase	       =is_training
        _lowercase	       =use_labels
        _lowercase	       =intermediate_size
        _lowercase	       =hidden_act
        _lowercase	       =type_sequence_label_size
        _lowercase	       =initializer_range
        _lowercase	       =out_features
        _lowercase	       =num_labels
        _lowercase	       =scope
        _lowercase	       =num_stages




  def   A__     (				self					)  -> Dict:
        '''simple docstring'''






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

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

        _lowercase	       =self.get_config()

        return config, pixel_values, labels




  def   A__     (				self					)  -> List[str]:
        '''simple docstring'''






        return ConvNextConfig(
            num_channels=self.num_channels							,   num_stages=self.num_stages							,   hidden_sizes=self.hidden_sizes							,   depths=self.depths							,   is_training=self.is_training							,   intermediate_size=self.intermediate_size							,   hidden_act=self.hidden_act							,   out_features=self.out_features							,   )




  def   A__     (				self					)  -> List[Any]:
        '''simple docstring'''






        return UperNetConfig(
            backbone_config=self.get_backbone_config()							,   hidden_size=512							,   pool_scales=[1, 2, 3, 6]							,   use_auxiliary_head=lowerCAmelCase							,   auxiliary_loss_weight=0.4							,   auxiliary_in_channels=40							,   auxiliary_channels=256							,   auxiliary_num_convs=1							,   auxiliary_concat_input=lowerCAmelCase							,   loss_ignore_index=255							,   num_labels=self.num_labels							,   )




  def   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					)  -> int:
        '''simple docstring'''






        _lowercase	       =UperNetForSemanticSegmentation(config=lowerCAmelCase					)
        model.to(lowerCAmelCase					)
        model.eval()
        _lowercase	       =model(lowerCAmelCase					)
        self.parent.assertEqual(
            result.logits.shape							,   (self.batch_size, self.num_labels, self.image_size, self.image_size)					)




  def   A__     (				self					)  -> Optional[int]:
        '''simple docstring'''






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





@require_torch
class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE			,			unittest.TestCase							):
  _a									=  (UperNetForSemanticSegmentation,) if is_torch_available() else ()
  _a									=  {"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
  _a									=  False
  _a									=  False
  _a									=  False
  _a									=  False
  _a									=  False
  _a									=  False




  def   A__     (				self					)  -> List[Any]:
        '''simple docstring'''






        _lowercase	       =UperNetModelTester(self					)
        _lowercase	       =ConfigTester(self							,   config_class=lowerCAmelCase							,   has_text_modality=lowerCAmelCase							,   hidden_size=37					)




  def   A__     (				self					)  -> Dict:
        '''simple docstring'''






        self.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()




  def   A__     (				self					)  -> Optional[Any]:
        '''simple docstring'''






        return




  def   A__     (				self					)  -> Tuple:
        '''simple docstring'''






        _lowercase       ,       _lowercase	       =self.model_tester.prepare_config_and_inputs_for_common()

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

              _lowercase	       =['pixel_values']
              self.assertListEqual(arg_names[:1]							,   lowerCAmelCase					)




  def   A__     (				self					)  -> int:
        '''simple docstring'''






        _lowercase	       =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase					)




  @unittest.skip(reason='UperNet does not use inputs_embeds'					)
  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






        pass




  @unittest.skip(reason='UperNet does not support input and output embeddings'					)
  def   A__     (				self					)  -> int:
        '''simple docstring'''






        pass




  @unittest.skip(reason='UperNet does not have a base model'					)
  def   A__     (				self					)  -> Optional[int]:
        '''simple docstring'''






        pass




  @unittest.skip(reason='UperNet does not have a base model'					)
  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






        pass




  @require_torch_multi_gpu
  @unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'					)
  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






        pass




  @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'					)
  def   A__     (				self					)  -> List[str]:
        '''simple docstring'''






        pass




  def   A__     (				self					)  -> List[str]:
        '''simple docstring'''






        def check_hidden_states_output(lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					):
              _lowercase	       =model_class(lowerCAmelCase					)
              model.to(lowerCAmelCase					)
              model.eval()

              with torch.no_grad():
                    _lowercase	       =model(**self._prepare_for_class(lowerCAmelCase							,   lowerCAmelCase					)					)

              _lowercase	       =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              _lowercase	       =self.model_tester.num_stages
              self.assertEqual(len(lowerCAmelCase					)							,   expected_num_stages + 1					)

              # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
              self.assertListEqual(
                  list(hidden_states[0].shape[-2:]					)							,   [self.model_tester.image_size // 4, self.model_tester.image_size // 4]							,   )

        _lowercase       ,       _lowercase	       =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _lowercase	       =True
              check_hidden_states_output(lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					)

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

              check_hidden_states_output(lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					)




  def   A__     (				self					)  -> int:
        '''simple docstring'''






        _lowercase       ,       _lowercase	       =self.model_tester.prepare_config_and_inputs_for_common()

        _lowercase	       =_config_zero_init(lowerCAmelCase					)
        _lowercase	       =_config_zero_init(configs_no_init.backbone_config					)
        for model_class in self.all_model_classes:
              _lowercase	       =model_class(config=lowerCAmelCase					)
              for name, param in model.named_parameters():
                    if param.requires_grad:
                          self.assertIn(
                              ((param.data.mean() * 1e9).round() / 1e9).item()							,   [0.0, 1.0]							,   msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''							,   )




  @unittest.skip(reason='UperNet does not have tied weights'					)
  def   A__     (				self					)  -> List[str]:
        '''simple docstring'''






        pass




  @slow
  def   A__     (				self					)  -> str:
        '''simple docstring'''






        for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _lowercase	       =UperNetForSemanticSegmentation.from_pretrained(lowerCAmelCase					)
              self.assertIsNotNone(lowerCAmelCase					)
def      a      (			)    ->      Dict:





      """simple docstring"""



      _lowercase	       =hf_hub_download(
          repo_id='hf-internal-testing/fixtures_ade20k'      ,   repo_type='dataset'      ,   filename='ADE_val_00000001.jpg'     )
      _lowercase	       =Image.open(A__     ).convert('RGB'     )
      return image







@require_torch
@require_vision
@slow
class  __lowerCAmelCase     (					unittest.TestCase							):




  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






        _lowercase	       =AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'					)
        _lowercase	       =UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'					).to(lowerCAmelCase					)

        _lowercase	       =prepare_img()
        _lowercase	       =processor(images=lowerCAmelCase							,   return_tensors='pt'					).to(lowerCAmelCase					)

        with torch.no_grad():
              _lowercase	       =model(**lowerCAmelCase					)

        _lowercase	       =torch.Size((1, model.config.num_labels, 512, 512)					)
        self.assertEqual(outputs.logits.shape							,   lowerCAmelCase					)

        _lowercase	       =torch.tensor(
            [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]					).to(lowerCAmelCase					)
        self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]							,   lowerCAmelCase							,   atol=1e-4					)					)




  def   A__     (				self					)  -> str:
        '''simple docstring'''






        _lowercase	       =AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'					)
        _lowercase	       =UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'					).to(lowerCAmelCase					)

        _lowercase	       =prepare_img()
        _lowercase	       =processor(images=lowerCAmelCase							,   return_tensors='pt'					).to(lowerCAmelCase					)

        with torch.no_grad():
              _lowercase	       =model(**lowerCAmelCase					)

        _lowercase	       =torch.Size((1, model.config.num_labels, 512, 512)					)
        self.assertEqual(outputs.logits.shape							,   lowerCAmelCase					)

        _lowercase	       =torch.tensor(
            [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]					).to(lowerCAmelCase					)
        self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]							,   lowerCAmelCase							,   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']}")


