
'''simple docstring'''
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  __A				:
 def __init__(   self			:    List[Any]				,   lowerCamelCase			:    List[str]				,   lowerCamelCase			:    Tuple=13				,   lowerCamelCase			:    Optional[int]=[30, 30]				,   lowerCamelCase			:    Optional[int]=2				,   lowerCamelCase			:    Tuple=3				,   lowerCamelCase			:    str=True				,   lowerCamelCase			:    str=True				,   lowerCamelCase			:    List[str]=32				,   lowerCamelCase			:    List[Any]=5				,   lowerCamelCase			:    List[str]=4				,   lowerCamelCase			:    Optional[int]=37				,   lowerCamelCase			:    Union[str, Any]="gelu"				,   lowerCamelCase			:    Tuple=0.1				,   lowerCamelCase			:    List[Any]=0.1				,   lowerCamelCase			:    Optional[Any]=10				,   lowerCamelCase			:    List[Any]=0.02				,   lowerCamelCase			:    List[Any]=3				,   lowerCamelCase			:    Union[str, Any]=None				,   lowerCamelCase			:    int=8				,   lowerCamelCase			:    Optional[int]=10				,   ):



   """simple docstring"""





   __A		:     List[Any]												=		parent
   __A		:     Tuple												=		batch_size
   __A		:     Tuple												=		image_size
   __A		:     str												=		patch_size
   __A		:     Union[str, Any]												=		num_channels
   __A		:     List[Any]												=		is_training
   __A		:     str												=		use_labels
   __A		:     List[str]												=		hidden_size
   __A		:     Dict												=		num_hidden_layers
   __A		:     Union[str, Any]												=		num_attention_heads
   __A		:     Dict												=		intermediate_size
   __A		:     Tuple												=		hidden_act
   __A		:     List[Any]												=		hidden_dropout_prob
   __A		:     List[Any]												=		attention_probs_dropout_prob
   __A		:     Union[str, Any]												=		type_sequence_label_size
   __A		:     str												=		initializer_range
   __A		:     Optional[Any]												=		num_labels
   __A		:     Optional[int]												=		scope
   __A		:     Union[str, Any]												=		n_targets
   __A		:     Tuple												=		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
   __A		:     List[Any]												=		(image_size[1] // patch_size) * (image_size[0] // patch_size)
   __A		:     Optional[Any]												=		num_patches + 1 + self.num_detection_tokens
 def 		lowercase_(   self			:    List[Any]       ):



   """simple docstring"""





   __A		:     Tuple												=		floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]       )

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

   __A		:     Optional[int]												=		self.get_config()

   return config, pixel_values, labels
 def 		lowercase_(   self			:    str       ):



   """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=lowerCamelCase				,   initializer_range=self.initializer_range				,   num_detection_tokens=self.num_detection_tokens				,   num_labels=self.num_labels				,   )
 def 		lowercase_(   self			:    Optional[int]				,   lowerCamelCase			:    Optional[Any]				,   lowerCamelCase			:    Optional[int]				,   lowerCamelCase			:    Optional[int]       ):



   """simple docstring"""





   __A		:     Optional[Any]												=		YolosModel(config=lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()
   __A		:     Optional[Any]												=		model(lowerCamelCase       )
   self.parent.assertEqual(
       result.last_hidden_state.shape				,   (self.batch_size, self.expected_seq_len, self.hidden_size)       )
 def 		lowercase_(   self			:    Optional[Any]				,   lowerCamelCase			:    Dict				,   lowerCamelCase			:    str				,   lowerCamelCase			:    Optional[Any]       ):



   """simple docstring"""





   __A		:     Union[str, Any]												=		YolosForObjectDetection(lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()

   __A		:     Union[str, Any]												=		model(pixel_values=lowerCamelCase       )
   __A		:     int												=		model(lowerCamelCase       )

   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)       )

   __A		:     Optional[int]												=		model(pixel_values=lowerCamelCase				,   labels=lowerCamelCase       )

   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 		lowercase_(   self			:    int       ):



   """simple docstring"""





   __A		:     Optional[Any]												=		self.prepare_config_and_inputs()
   __A		:     Any												=		config_and_inputs
   __A		:     Union[str, Any]												=		{"""pixel_values""": pixel_values}
   return config, inputs_dict







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

 lowerCamelCase				       =False
 lowerCamelCase				       =False
 lowerCamelCase				       =False
 lowerCamelCase				       =False
 def 		lowercase_(   self			:    Dict				,   lowerCamelCase			:    List[Any]				,   lowerCamelCase			:    Optional[int]				,   lowerCamelCase			:    Tuple=False       ):



   """simple docstring"""





   __A		:     Dict												=		super()._prepare_for_class(lowerCamelCase				,   lowerCamelCase				,   return_labels=lowerCamelCase       )

   if return_labels:
     if model_class.__name__ == "YolosForObjectDetection":
       __A		:     int												=		[]
       for i in range(self.model_tester.batch_size       ):
         __A		:     Any												=		{}
         __A		:     List[Any]												=		torch.ones(
             size=(self.model_tester.n_targets,)				,   device=lowerCamelCase				,   dtype=torch.long       )
         __A		:     Dict												=		torch.ones(
             self.model_tester.n_targets				,   4				,   device=lowerCamelCase				,   dtype=torch.float       )
         labels.append(lowerCamelCase       )
       __A		:     Union[str, Any]												=		labels

   return inputs_dict
 def 		lowercase_(   self			:    str       ):



   """simple docstring"""





   __A		:     Tuple												=		YolosModelTester(self       )
   __A		:     List[Any]												=		ConfigTester(self				,   config_class=lowerCamelCase				,   has_text_modality=lowerCamelCase				,   hidden_size=37       )
 def 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





   self.config_tester.run_common_tests()
 def 		lowercase_(   self			:    List[Any]       ):



   """simple docstring"""





   pass
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   __A		:     Tuple												=		self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     __A		:     Optional[int]												=		model_class(lowerCamelCase       )
     self.assertIsInstance(model.get_input_embeddings()				,   (nn.Module)       )
     __A		:     Union[str, Any]												=		model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(lowerCamelCase				,   nn.Linear       )       )
 def 		lowercase_(   self			:    Optional[int]       ):



   """simple docstring"""





   __A		:     List[Any]												=		self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     __A		:     Optional[Any]												=		model_class(lowerCamelCase       )
     __A		:     Union[str, Any]												=		inspect.signature(model.forward       )
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     __A		:     Tuple												=		[*signature.parameters.keys()]

     __A		:     Any												=		["""pixel_values"""]
     self.assertListEqual(arg_names[:1]				,   lowerCamelCase       )
 def 		lowercase_(   self			:    Union[str, Any]       ):



   """simple docstring"""





   __A		:     Any												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCamelCase       )
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   __A		:     Any												=		self.model_tester.prepare_config_and_inputs_for_common()
   __A		:     Optional[int]												=		True

   # in YOLOS, the seq_len is different
   __A		:     Union[str, Any]												=		self.model_tester.expected_seq_len
   for model_class in self.all_model_classes:
     __A		:     Union[str, Any]												=		True
     __A		:     List[str]												=		False
     __A		:     Optional[Any]												=		True
     __A		:     Union[str, Any]												=		model_class(lowerCamelCase       )
     model.to(lowerCamelCase       )
     model.eval()
     with torch.no_grad():
       __A		:     List[str]												=		model(**self._prepare_for_class(lowerCamelCase				,   lowerCamelCase       )       )
     __A		:     Dict												=		outputs.attentions
     self.assertEqual(len(lowerCamelCase       )				,   self.model_tester.num_hidden_layers       )

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

     self.assertListEqual(
         list(attentions[0].shape[-3:]       )				,   [self.model_tester.num_attention_heads, seq_len, seq_len]				,   )
     __A		:     Optional[int]												=		len(lowerCamelCase       )

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

     __A		:     Any												=		1
     self.assertEqual(out_len + added_hidden_states				,   len(lowerCamelCase       )       )

     __A		:     Any												=		outputs.attentions

     self.assertEqual(len(lowerCamelCase       )				,   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 		lowercase_(   self			:    Union[str, Any]       ):



   """simple docstring"""





   def check_hidden_states_output(lowerCamelCase			:    List[Any]				,   lowerCamelCase			:    Dict				,   lowerCamelCase			:    Tuple       ):
     __A		:     Union[str, Any]												=		model_class(lowerCamelCase       )
     model.to(lowerCamelCase       )
     model.eval()

     with torch.no_grad():
       __A		:     List[str]												=		model(**self._prepare_for_class(lowerCamelCase				,   lowerCamelCase       )       )

     __A		:     Any												=		outputs.hidden_states

     __A		:     Optional[Any]												=		getattr(
         self.model_tester				,   """expected_num_hidden_layers"""				,   self.model_tester.num_hidden_layers + 1       )
     self.assertEqual(len(lowerCamelCase       )				,   lowerCamelCase       )

     # YOLOS has a different seq_length
     __A		:     str												=		self.model_tester.expected_seq_len

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

   __A		:     Tuple												=		self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     __A		:     str												=		True
     check_hidden_states_output(lowerCamelCase				,   lowerCamelCase				,   lowerCamelCase       )

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __A		:     Union[str, Any]												=		True

     check_hidden_states_output(lowerCamelCase				,   lowerCamelCase				,   lowerCamelCase       )
 def 		lowercase_(   self			:    Optional[int]       ):



   """simple docstring"""





   __A		:     Optional[Any]												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_object_detection(*lowerCamelCase       )






 @slow
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __A		:     Optional[int]												=		YolosModel.from_pretrained(lowerCamelCase       )
     self.assertIsNotNone(lowerCamelCase       )







def        A_     (						)				->       List[str]:





  """simple docstring"""

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







@require_torch
@require_vision
class  __A				( unittest.TestCase			):
 @cached_property
 def 		lowercase_(   self			:    int       ):



   """simple docstring"""





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






 @slow
 def 		lowercase_(   self			:    str       ):



   """simple docstring"""





   __A		:     List[Any]												=		YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""       ).to(lowerCamelCase       )

   __A		:     List[Any]												=		self.default_image_processor
   __A		:     Any												=		prepare_img()
   __A		:     List[str]												=		image_processor(images=lowerCamelCase				,   return_tensors="""pt"""       ).to(lowerCamelCase       )

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

   # verify outputs
   __A		:     List[Any]												=		torch.Size((1, 1_00, 92)       )
   self.assertEqual(outputs.logits.shape				,   lowerCamelCase       )

   __A		:     Tuple												=		torch.tensor(
       [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]]				,   device=lowerCamelCase				,   )
   __A		:     List[Any]												=		torch.tensor(
       [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]]				,   device=lowerCamelCase       )
   self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]				,   lowerCamelCase				,   atol=1e-4       )       )
   self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]				,   lowerCamelCase				,   atol=1e-4       )       )

   # verify postprocessing
   __A		:     Union[str, Any]												=		image_processor.post_process_object_detection(
       lowerCamelCase				,   threshold=0.3				,   target_sizes=[image.size[::-1]]       )[0]
   __A		:     Tuple												=		torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]       ).to(lowerCamelCase       )
   __A		:     str												=		[75, 75, 17, 63, 17]
   __A		:     str												=		torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]       ).to(lowerCamelCase       )

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





'''simple docstring'''
import os
import zipfile

import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links







def        A_     (						__SCREAMING_SNAKE_CASE						:  List[str]			,     __SCREAMING_SNAKE_CASE						:  Optional[int]=7 )				->       List[Any]:





  """simple docstring"""

  __A		:     Optional[int]												=		None
  if token is not None:
    __A		:     str												=		{"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"}

  # The id of a workflow (not of a workflow run)
  __A		:     Union[str, Any]												=		"""636036"""

  __A		:     Optional[int]												=		F"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"
  # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
  url += F"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"

  __A		:     int												=		requests.get(__SCREAMING_SNAKE_CASE			,     headers=__SCREAMING_SNAKE_CASE ).json()

  return result["workflow_runs"]







def        A_     (						__SCREAMING_SNAKE_CASE						:  Union[str, Any] )				->       Tuple:





  """simple docstring"""

  __A		:     str												=		get_daily_ci_runs(__SCREAMING_SNAKE_CASE )
  __A		:     List[Any]												=		None
  for workflow_run in workflow_runs:
    if workflow_run["status"] == "completed":
      __A		:     Dict												=		workflow_run["""id"""]
      break

  return workflow_run_id







def        A_     (						__SCREAMING_SNAKE_CASE						:  List[Any]			,     __SCREAMING_SNAKE_CASE						:  Any			,     __SCREAMING_SNAKE_CASE						:  Tuple )				->       Tuple:





  """simple docstring"""

  __A		:     Dict												=		get_last_daily_ci_runs(__SCREAMING_SNAKE_CASE )
  if workflow_run_id is not None:
    __A		:     str												=		get_artifacts_links(worflow_run_id=__SCREAMING_SNAKE_CASE			,     token=__SCREAMING_SNAKE_CASE )
    for artifact_name in artifact_names:
      if artifact_name in artifacts_links:
        __A		:     List[Any]												=		artifacts_links[artifact_name]
        download_artifact(
            artifact_name=__SCREAMING_SNAKE_CASE			,     artifact_url=__SCREAMING_SNAKE_CASE			,     output_dir=__SCREAMING_SNAKE_CASE			,     token=__SCREAMING_SNAKE_CASE )







def        A_     (						__SCREAMING_SNAKE_CASE						:  List[Any]			,     __SCREAMING_SNAKE_CASE						:  Optional[int]			,     __SCREAMING_SNAKE_CASE						:  Optional[Any] )				->       Union[str, Any]:





  """simple docstring"""

  get_last_daily_ci_artifacts(__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE )

  __A		:     List[Any]												=		{}
  for artifact_name in artifact_names:
    __A		:     Any												=		os.path.join(__SCREAMING_SNAKE_CASE			,     F"{artifact_name}.zip" )
    if os.path.isfile(__SCREAMING_SNAKE_CASE ):
      __A		:     str												=		{}
      with zipfile.ZipFile(__SCREAMING_SNAKE_CASE ) as z:
        for filename in z.namelist():
          if not os.path.isdir(__SCREAMING_SNAKE_CASE ):
            # read the file
            with z.open(__SCREAMING_SNAKE_CASE ) as f:
              __A		:     Tuple												=		f.read().decode("""UTF-8""" )

  return results



