


"""simple docstring"""


import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
	import torch

	from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
	from transformers.models.mobilevitva.modeling_mobilevitva import (
	    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
	    make_divisible,
	)


if is_vision_available():
	from PIL import Image

	from transformers import MobileViTImageProcessor
class   _UpperCamelCase  (   __SCREAMING_SNAKE_CASE		):
							'''simple docstring'''







							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			self.config_class(**self.inputs_dict	)
										self.parent.assertTrue(hasattr(__a    ,   "width_multiplier"	)	)
class   _UpperCamelCase  :
							'''simple docstring'''







							def __init__(     self    ,   __a    ,   __a=13    ,   __a=64    ,   __a=2    ,   __a=3    ,   __a="swish"    ,   __a=3    ,   __a=32    ,   __a=0.1    ,   __a=0.0_2    ,   __a=True    ,   __a=True    ,   __a=10    ,   __a=None    ,   __a=0.2_5    ,   __a=0.0    ,   __a=0.0    ,   ):
										__lowerCAmelCase				    =			parent
										__lowerCAmelCase				    =			batch_size
										__lowerCAmelCase				    =			image_size
										__lowerCAmelCase				    =			patch_size
										__lowerCAmelCase				    =			num_channels
										__lowerCAmelCase				    =			make_divisible(5_12 * width_multiplier    ,   divisor=8	)
										__lowerCAmelCase				    =			hidden_act
										__lowerCAmelCase				    =			conv_kernel_size
										__lowerCAmelCase				    =			output_stride
										__lowerCAmelCase				    =			classifier_dropout_prob
										__lowerCAmelCase				    =			use_labels
										__lowerCAmelCase				    =			is_training
										__lowerCAmelCase				    =			num_labels
										__lowerCAmelCase				    =			initializer_range
										__lowerCAmelCase				    =			scope
										__lowerCAmelCase				    =			width_multiplier
										__lowerCAmelCase				    =			ffn_dropout
										__lowerCAmelCase				    =			attn_dropout

							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

										__lowerCAmelCase				    =			None
										__lowerCAmelCase				    =			None
										if self.use_labels:
													__lowerCAmelCase				    =			ids_tensor([self.batch_size]    ,   self.num_labels	)
													__lowerCAmelCase				    =			ids_tensor([self.batch_size, self.image_size, self.image_size]    ,   self.num_labels	)

										__lowerCAmelCase				    =			self.get_config()

										return config, pixel_values, labels, pixel_labels

							def 			snake_case				(     self	):
										return MobileViTVaConfig(
										    image_size=self.image_size    ,   patch_size=self.patch_size    ,   num_channels=self.num_channels    ,   hidden_act=self.hidden_act    ,   conv_kernel_size=self.conv_kernel_size    ,   output_stride=self.output_stride    ,   classifier_dropout_prob=self.classifier_dropout_prob    ,   initializer_range=self.initializer_range    ,   width_multiplier=self.width_multiplier    ,   ffn_dropout=self.ffn_dropout_prob    ,   attn_dropout=self.attn_dropout_prob    ,   )

							def 			snake_case				(     self    ,   __a    ,   __a    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			MobileViTVaModel(config=__a	)
										model.to(__a	)
										model.eval()
										__lowerCAmelCase				    =			model(__a	)
										self.parent.assertEqual(
										    result.last_hidden_state.shape    ,   (
										        self.batch_size,
										        self.last_hidden_size,
										        self.image_size // self.output_stride,
										        self.image_size // self.output_stride,
										    )    ,   )

							def 			snake_case				(     self    ,   __a    ,   __a    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			self.num_labels
										__lowerCAmelCase				    =			MobileViTVaForImageClassification(__a	)
										model.to(__a	)
										model.eval()
										__lowerCAmelCase				    =			model(__a    ,   labels=__a	)
										self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.num_labels)	)

							def 			snake_case				(     self    ,   __a    ,   __a    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			self.num_labels
										__lowerCAmelCase				    =			MobileViTVaForSemanticSegmentation(__a	)
										model.to(__a	)
										model.eval()
										__lowerCAmelCase				    =			model(__a	)
										self.parent.assertEqual(
										    result.logits.shape    ,   (
										        self.batch_size,
										        self.num_labels,
										        self.image_size // self.output_stride,
										        self.image_size // self.output_stride,
										    )    ,   )
										__lowerCAmelCase				    =			model(__a    ,   labels=__a	)
										self.parent.assertEqual(
										    result.logits.shape    ,   (
										        self.batch_size,
										        self.num_labels,
										        self.image_size // self.output_stride,
										        self.image_size // self.output_stride,
										    )    ,   )



							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			self.prepare_config_and_inputs()
										__lowerCAmelCase    ,	__lowerCAmelCase    ,	__lowerCAmelCase    ,	__lowerCAmelCase				    =			config_and_inputs
										__lowerCAmelCase				    =			{"pixel_values": pixel_values}
										return config, inputs_dict
@require_torch
class   _UpperCamelCase  (   __SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE       ,unittest.TestCase		):
							'''simple docstring'''







							__UpperCAmelCase						:    Optional[Any]				      =(
							    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)

							__UpperCAmelCase						:    Union[str, Any]				      =(
							    {
							        """feature-extraction""": MobileViTVaModel,
							        """image-classification""": MobileViTVaForImageClassification,
							        """image-segmentation""": MobileViTVaForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							__UpperCAmelCase						:    Optional[int]				      =False
							__UpperCAmelCase						:    List[Any]				      =False
							__UpperCAmelCase						:    Tuple				      =False
							__UpperCAmelCase						:    List[Any]				      =False

							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			MobileViTVaModelTester(self	)
										__lowerCAmelCase				    =			MobileViTVaConfigTester(self    ,   config_class=__a    ,   has_text_modality=__a	)

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

							@unittest.skip(reason="MobileViTV2 does not use inputs_embeds"	)
							def 			snake_case				(     self	):
										pass

							@unittest.skip(reason="MobileViTV2 does not support input and output embeddings"	)
							def 			snake_case				(     self	):
										pass

							@unittest.skip(reason="MobileViTV2 does not output attentions"	)
							def 			snake_case				(     self	):
										pass

							@require_torch_multi_gpu
							@unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."	)
							def 			snake_case				(     self	):
										pass

							@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."	)
							def 			snake_case				(     self	):
										pass

							def 			snake_case				(     self	):
										__lowerCAmelCase    ,	__lowerCAmelCase				    =			self.model_tester.prepare_config_and_inputs_for_common()

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

													__lowerCAmelCase				    =			["pixel_values"]
													self.assertListEqual(arg_names[:1]    ,   __a	)

							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__a	)

							def 			snake_case				(     self	):
										def check_hidden_states_output(__a    ,   __a    ,   __a	):
													__lowerCAmelCase				    =			model_class(__a	)
													model.to(__a	)
													model.eval()

													with torch.no_grad():
																__lowerCAmelCase				    =			model(**self._prepare_for_class(__a    ,   __a	)	)

													__lowerCAmelCase				    =			outputs.hidden_states

													__lowerCAmelCase				    =			5
													self.assertEqual(len(__a	)    ,   __a	)

													# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
													# with the width and height being successively divided by 2.
													__lowerCAmelCase				    =			2
													for i in range(len(__a	)	):
																self.assertListEqual(
																    list(hidden_states[i].shape[-2:]	)    ,   [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]    ,   )
																divisor *= 2

													self.assertEqual(self.model_tester.output_stride    ,   divisor // 2	)

										__lowerCAmelCase    ,	__lowerCAmelCase				    =			self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													__lowerCAmelCase				    =			True
													check_hidden_states_output(__a    ,   __a    ,   __a	)

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

													check_hidden_states_output(__a    ,   __a    ,   __a	)

							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__a	)

							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*__a	)



							@slow
							def 			snake_case				(     self	):
										for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__lowerCAmelCase				    =			MobileViTVaModel.from_pretrained(__a	)
													self.assertIsNotNone(__a	)


def _lowerCamelCase	(		):

			'''simple docstring'''




			__lowerCAmelCase				    =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
			return image


@require_torch
@require_vision
class   _UpperCamelCase  (   unittest.TestCase		):
							'''simple docstring'''







							@cached_property
							def 			snake_case				(     self	):
										return (
										    MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"	)
										    if is_vision_available()
										    else None
										)

							@slow
							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"	).to(
										    __a	)

										__lowerCAmelCase				    =			self.default_image_processor
										__lowerCAmelCase				    =			prepare_img()
										__lowerCAmelCase				    =			image_processor(images=__a    ,   return_tensors="pt"	).to(__a	)

										# forward pass
										with torch.no_grad():
													__lowerCAmelCase				    =			model(**__a	)

										# verify the logits
										__lowerCAmelCase				    =			torch.Size((1, 10_00)	)
										self.assertEqual(outputs.logits.shape    ,   __a	)

										__lowerCAmelCase				    =			torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1]	).to(__a	)

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

							@slow
							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"	)
										__lowerCAmelCase				    =			model.to(__a	)

										__lowerCAmelCase				    =			MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"	)

										__lowerCAmelCase				    =			prepare_img()
										__lowerCAmelCase				    =			image_processor(images=__a    ,   return_tensors="pt"	).to(__a	)

										# forward pass
										with torch.no_grad():
													__lowerCAmelCase				    =			model(**__a	)
										__lowerCAmelCase				    =			outputs.logits

										# verify the logits
										__lowerCAmelCase				    =			torch.Size((1, 21, 32, 32)	)
										self.assertEqual(logits.shape    ,   __a	)

										__lowerCAmelCase				    =			torch.tensor(
										    [
										        [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]],
										        [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]],
										        [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]],
										    ]    ,   device=__a    ,   )

										self.assertTrue(torch.allclose(logits[0, :3, :3, :3]    ,   __a    ,   atol=1e-4	)	)



							@slow
							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"	)
										__lowerCAmelCase				    =			model.to(__a	)

										__lowerCAmelCase				    =			MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"	)

										__lowerCAmelCase				    =			prepare_img()
										__lowerCAmelCase				    =			image_processor(images=__a    ,   return_tensors="pt"	).to(__a	)

										# forward pass
										with torch.no_grad():
													__lowerCAmelCase				    =			model(**__a	)

										__lowerCAmelCase				    =			outputs.logits.detach().cpu()

										__lowerCAmelCase				    =			image_processor.post_process_semantic_segmentation(outputs=__a    ,   target_sizes=[(50, 60)]	)
										__lowerCAmelCase				    =			torch.Size((50, 60)	)
										self.assertEqual(segmentation[0].shape    ,   __a	)

										__lowerCAmelCase				    =			image_processor.post_process_semantic_segmentation(outputs=__a	)
										__lowerCAmelCase				    =			torch.Size((32, 32)	)
										self.assertEqual(segmentation[0].shape    ,   __a	)






import argparse
import math
import traceback

import dateutil.parser as date_parser
import requests


def 						UpperCAmelCase			(	a_						)		->	str:







				"""simple docstring"""



				__A   			= {}

				__A   			= job["started_at"]
				__A   			= job["completed_at"]

				__A   			= date_parser.parse(a_						)
				__A   			= date_parser.parse(a_						)

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

				__A   			= start
				__A   			= end
				__A   			= duration_in_min

				return job_info


def 						UpperCAmelCase			(	a_		,   a_=None						)		->	str:







				"""simple docstring"""



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

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

				try:
								job_time.update({job["name"]: extract_time_from_single_job(a_						) for job in result["jobs"]}						)
								__A   			= math.ceil((result["total_count"] - 1_0_0) / 1_0_0						)

								for i in range(a_						):
												__A   			= 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__":
					SCREAMING_SNAKE_CASE							:Union[str, Any]							 =				argparse.ArgumentParser()
					# Required parameters
					parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.')
					SCREAMING_SNAKE_CASE							:Optional[int]							 =				parser.parse_args()

					SCREAMING_SNAKE_CASE							:Union[str, Any]							 =				get_job_time(args.workflow_run_id)
					SCREAMING_SNAKE_CASE							:Optional[int]							 =				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"]}''')
