






import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, 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
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import YolosForObjectDetection, YolosModel
					from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor


class     __SCREAMING_SNAKE_CASE					:






						def __init__(	self     ,						_UpperCamelCase     ,						_UpperCamelCase=13     ,						_UpperCamelCase=[30, 30]     ,						_UpperCamelCase=2     ,						_UpperCamelCase=3     ,						_UpperCamelCase=True     ,						_UpperCamelCase=True     ,						_UpperCamelCase=32     ,						_UpperCamelCase=5     ,						_UpperCamelCase=4     ,						_UpperCamelCase=37     ,						_UpperCamelCase="gelu"     ,						_UpperCamelCase=0.1     ,						_UpperCamelCase=0.1     ,						_UpperCamelCase=10     ,						_UpperCamelCase=0.02     ,						_UpperCamelCase=3     ,						_UpperCamelCase=None     ,						_UpperCamelCase=8     ,						_UpperCamelCase=10     ,						):






												"""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__    						=						num_labels
												lowerCAmelCase__    						=						scope
												lowerCAmelCase__    						=						n_targets
												lowerCAmelCase__    						=						num_detection_tokens
												# we set the expected sequence length (which is used in several tests)
												# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
												lowerCAmelCase__    						=						(image_size[1] // patch_size) * (image_size[0] // patch_size)
												lowerCAmelCase__    						=						num_patches + 1 + self.num_detection_tokens






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]   )

												lowerCAmelCase__    						=						None
												if self.use_labels:
																		# labels is a list of Dict (each Dict being the labels for a given example in the batch)
																		lowerCAmelCase__    						=						[]
																		for i in range(self.batch_size   ):
																								lowerCAmelCase__    						=						{}
																								lowerCAmelCase__    						=						torch.randint(
																								    high=self.num_labels     ,						size=(self.n_targets,)     ,						device=_UpperCamelCase   )
																								lowerCAmelCase__    						=						torch.rand(self.n_targets     ,						4     ,						device=_UpperCamelCase   )
																								labels.append(_UpperCamelCase   )

												lowerCAmelCase__    						=						self.get_config()

												return config, pixel_values, labels






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												return YolosConfig(
												    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=_UpperCamelCase     ,						initializer_range=self.initializer_range     ,						num_detection_tokens=self.num_detection_tokens     ,						num_labels=self.num_labels     ,						)






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						YolosModel(config=_UpperCamelCase   )
												model.to(_UpperCamelCase   )
												model.eval()
												lowerCAmelCase__    						=						model(_UpperCamelCase   )
												self.parent.assertEqual(
												    result.last_hidden_state.shape     ,						(self.batch_size, self.expected_seq_len, self.hidden_size)   )






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						YolosForObjectDetection(_UpperCamelCase   )
												model.to(_UpperCamelCase   )
												model.eval()

												lowerCAmelCase__    						=						model(pixel_values=_UpperCamelCase   )
												lowerCAmelCase__    						=						model(_UpperCamelCase   )

												self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_detection_tokens, self.num_labels + 1)   )
												self.parent.assertEqual(result.pred_boxes.shape     ,						(self.batch_size, self.num_detection_tokens, 4)   )

												lowerCAmelCase__    						=						model(pixel_values=_UpperCamelCase     ,						labels=_UpperCamelCase   )

												self.parent.assertEqual(result.loss.shape     ,						()   )
												self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_detection_tokens, self.num_labels + 1)   )
												self.parent.assertEqual(result.pred_boxes.shape     ,						(self.batch_size, self.num_detection_tokens, 4)   )







						def       UpperCamelCase__      (	self   ):






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




@require_torch
class     __SCREAMING_SNAKE_CASE					(   __lowercase		,					__lowercase		,					unittest.TestCase):
						_SCREAMING_SNAKE_CASE	:       Tuple   =					(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
						_SCREAMING_SNAKE_CASE	:       int   =					(
						    {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
						)

						_SCREAMING_SNAKE_CASE	:       int   =					False
						_SCREAMING_SNAKE_CASE	:       List[str]   =					False
						_SCREAMING_SNAKE_CASE	:       Union[str, Any]   =					False
						_SCREAMING_SNAKE_CASE	:       Any   =					False






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase=False   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						super()._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase     ,						return_labels=_UpperCamelCase   )

												if return_labels:
																		if model_class.__name__ == "YolosForObjectDetection":
																								lowerCAmelCase__    						=						[]
																								for i in range(self.model_tester.batch_size   ):
																														lowerCAmelCase__    						=						{}
																														lowerCAmelCase__    						=						torch.ones(
																														    size=(self.model_tester.n_targets,)     ,						device=_UpperCamelCase     ,						dtype=torch.long   )
																														lowerCAmelCase__    						=						torch.ones(
																														    self.model_tester.n_targets     ,						4     ,						device=_UpperCamelCase     ,						dtype=torch.float   )
																														labels.append(_UpperCamelCase   )
																								lowerCAmelCase__    						=						labels

												return inputs_dict






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						YolosModelTester(self   )
												lowerCAmelCase__    						=						ConfigTester(self     ,						config_class=_UpperCamelCase     ,						has_text_modality=_UpperCamelCase     ,						hidden_size=37   )






						def       UpperCamelCase__      (	self   ):






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






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												# YOLOS does not use inputs_embeds
												pass






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		self.assertIsInstance(model.get_input_embeddings()     ,						(nn.Module)   )
																		lowerCAmelCase__    						=						model.get_output_embeddings()
																		self.assertTrue(x is None or isinstance(_UpperCamelCase     ,						nn.Linear   )   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		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]     ,						_UpperCamelCase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_UpperCamelCase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs_for_common()
												lowerCAmelCase__    						=						True

												# in YOLOS, the seq_len is different
												lowerCAmelCase__    						=						self.model_tester.expected_seq_len
												for model_class in self.all_model_classes:
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						False
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		model.to(_UpperCamelCase   )
																		model.eval()
																		with torch.no_grad():
																								lowerCAmelCase__    						=						model(**self._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase   )   )
																		lowerCAmelCase__    						=						outputs.attentions
																		self.assertEqual(len(_UpperCamelCase   )     ,						self.model_tester.num_hidden_layers   )

																		# check that output_attentions also work using config
																		del inputs_dict["output_attentions"]
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		model.to(_UpperCamelCase   )
																		model.eval()
																		with torch.no_grad():
																								lowerCAmelCase__    						=						model(**self._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase   )   )
																		lowerCAmelCase__    						=						outputs.attentions
																		self.assertEqual(len(_UpperCamelCase   )     ,						self.model_tester.num_hidden_layers   )

																		self.assertListEqual(
																		    list(attentions[0].shape[-3:]   )     ,						[self.model_tester.num_attention_heads, seq_len, seq_len]     ,						)
																		lowerCAmelCase__    						=						len(_UpperCamelCase   )

																		# Check attention is always last and order is fine
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		model.to(_UpperCamelCase   )
																		model.eval()
																		with torch.no_grad():
																								lowerCAmelCase__    						=						model(**self._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase   )   )

																		lowerCAmelCase__    						=						1
																		self.assertEqual(out_len + added_hidden_states     ,						len(_UpperCamelCase   )   )

																		lowerCAmelCase__    						=						outputs.attentions

																		self.assertEqual(len(_UpperCamelCase   )     ,						self.model_tester.num_hidden_layers   )
																		self.assertListEqual(
																		    list(self_attentions[0].shape[-3:]   )     ,						[self.model_tester.num_attention_heads, seq_len, seq_len]     ,						)






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												def check_hidden_states_output(_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		model.to(_UpperCamelCase   )
																		model.eval()

																		with torch.no_grad():
																								lowerCAmelCase__    						=						model(**self._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase   )   )

																		lowerCAmelCase__    						=						outputs.hidden_states

																		lowerCAmelCase__    						=						getattr(
																		    self.model_tester     ,						'expected_num_hidden_layers'     ,						self.model_tester.num_hidden_layers + 1   )
																		self.assertEqual(len(_UpperCamelCase   )     ,						_UpperCamelCase   )

																		# YOLOS has a different seq_length
																		lowerCAmelCase__    						=						self.model_tester.expected_seq_len

																		self.assertListEqual(
																		    list(hidden_states[0].shape[-2:]   )     ,						[seq_length, self.model_tester.hidden_size]     ,						)

												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(_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   )

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

																		check_hidden_states_output(_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_object_detection(*_UpperCamelCase   )







						@slow
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		lowerCAmelCase__    						=						YolosModel.from_pretrained(_UpperCamelCase   )
																		self.assertIsNotNone(_UpperCamelCase   )







def 	_UpperCamelCase   (    )  ->   List[Any]:

						"""simple docstring"""



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


@require_torch
@require_vision
class     __SCREAMING_SNAKE_CASE					(   unittest.TestCase):






						@cached_property
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												return AutoImageProcessor.from_pretrained('hustvl/yolos-small'   ) if is_vision_available() else None







						@slow
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						YolosForObjectDetection.from_pretrained('hustvl/yolos-small'   ).to(_UpperCamelCase   )

												lowerCAmelCase__    						=						self.default_image_processor
												lowerCAmelCase__    						=						prepare_img()
												lowerCAmelCase__    						=						image_processor(images=_UpperCamelCase     ,						return_tensors='pt'   ).to(_UpperCamelCase   )

												# forward pass
												with torch.no_grad():
																		lowerCAmelCase__    						=						model(inputs.pixel_values   )

												# verify outputs
												lowerCAmelCase__    						=						torch.Size((1, 1_00, 92)   )
												self.assertEqual(outputs.logits.shape     ,						_UpperCamelCase   )

												lowerCAmelCase__    						=						torch.tensor(
												    [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]]     ,						device=_UpperCamelCase     ,						)
												lowerCAmelCase__    						=						torch.tensor(
												    [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]]     ,						device=_UpperCamelCase   )
												self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]     ,						_UpperCamelCase     ,						atol=1E-4   )   )
												self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]     ,						_UpperCamelCase     ,						atol=1E-4   )   )

												# verify postprocessing
												lowerCAmelCase__    						=						image_processor.post_process_object_detection(
												    _UpperCamelCase     ,						threshold=0.3     ,						target_sizes=[image.size[::-1]]   )[0]
												lowerCAmelCase__    						=						torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]   ).to(_UpperCamelCase   )
												lowerCAmelCase__    						=						[75, 75, 17, 63, 17]
												lowerCAmelCase__    						=						torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]   ).to(_UpperCamelCase   )

												self.assertEqual(len(results['scores']   )     ,						5   )
												self.assertTrue(torch.allclose(results['scores']     ,						_UpperCamelCase     ,						atol=1E-4   )   )
												self.assertSequenceEqual(results['labels'].tolist()     ,						_UpperCamelCase   )
												self.assertTrue(torch.allclose(results['boxes'][0, :]     ,						_UpperCamelCase   )   )













from __future__ import annotations

import pandas as pd







def 	_UpperCamelCase   (    UpperCamelCase_       :					list[int]    ,       UpperCamelCase_       :					list[int]    ,       UpperCamelCase_       :					int		)  ->   list[int]:

						"""simple docstring"""



						lowerCAmelCase__    						=						[0] * no_of_processes
						lowerCAmelCase__    						=						[0] * no_of_processes
						# Copy the burst time into remaining_time[]
						for i in range(UpperCamelCase_		):
												lowerCAmelCase__    						=						burst_time[i]

						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						9_9999_9999
						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						False

						# Process until all processes are completed
						while complete != no_of_processes:
												for j in range(UpperCamelCase_		):
																		if arrival_time[j] <= increment_time and remaining_time[j] > 0:
																								if remaining_time[j] < minm:
																														lowerCAmelCase__    						=						remaining_time[j]
																														lowerCAmelCase__    						=						j
																														lowerCAmelCase__    						=						True

												if not check:
																		increment_time += 1
																		continue
												remaining_time[short] -= 1

												lowerCAmelCase__    						=						remaining_time[short]
												if minm == 0:
																		lowerCAmelCase__    						=						9_9999_9999

												if remaining_time[short] == 0:
																		complete += 1
																		lowerCAmelCase__    						=						False

																		# Find finish time of current process
																		lowerCAmelCase__    						=						increment_time + 1

																		# Calculate waiting time
																		lowerCAmelCase__    						=						finish_time - arrival_time[short]
																		lowerCAmelCase__    						=						finar - burst_time[short]

																		if waiting_time[short] < 0:
																								lowerCAmelCase__    						=						0

        # Increment time
												increment_time += 1
						return waiting_time







def 	_UpperCamelCase   (    UpperCamelCase_       :					list[int]    ,       UpperCamelCase_       :					int    ,       UpperCamelCase_       :					list[int]		)  ->   list[int]:

						"""simple docstring"""



						lowerCAmelCase__    						=						[0] * no_of_processes
						for i in range(UpperCamelCase_		):
												lowerCAmelCase__    						=						burst_time[i] + waiting_time[i]
						return turn_around_time







def 	_UpperCamelCase   (    UpperCamelCase_       :					list[int]    ,       UpperCamelCase_       :					list[int]    ,       UpperCamelCase_       :					int		)  ->   None:

						"""simple docstring"""



						lowerCAmelCase__    						=						0
						lowerCAmelCase__    						=						0
						for i in range(UpperCamelCase_		):
												lowerCAmelCase__    						=						total_waiting_time + waiting_time[i]
												lowerCAmelCase__    						=						total_turn_around_time + turn_around_time[i]
						print(F"Average waiting time = {total_waiting_time / no_of_processes:.5f}"		)
						print('Average turn around time ='    ,       total_turn_around_time / no_of_processes		)


if __name__ == "__main__":
					print("""Enter how many process you want to analyze""")
					__snake_case    :    Dict         =     int(input())
					__snake_case    :    List[Any]         =     [0] * no_of_processes
					__snake_case    :    str         =     [0] * no_of_processes
					__snake_case    :    Optional[int]         =     list(range(1, no_of_processes + 1))

					for i in range(no_of_processes):
										print("""Enter the arrival time and burst time for process:--""" + str(i + 1))
										__snake_case     , __snake_case    :    Any         =     map(int, input().split())

					__snake_case    :    str         =     calculate_waitingtime(arrival_time, burst_time, no_of_processes)

					__snake_case    :    Dict         =     burst_time
					__snake_case    :    Optional[int]         =     no_of_processes
					__snake_case    :    str         =     waiting_time
					__snake_case    :    int         =     calculate_turnaroundtime(bt, n, wt)

					calculate_average_times(waiting_time, turn_around_time, no_of_processes)

					__snake_case    :    Dict         =     pd.DataFrame(
					    list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)),
					    columns=[
					        """Process""",
					        """BurstTime""",
					        """ArrivalTime""",
					        """WaitingTime""",
					        """TurnAroundTime""",
					    ],
					)

					# Printing the dataFrame
					pd.set_option("""display.max_rows""", fcfs.shape[0] + 1)
					print(fcfs)





