





'''simple docstring'''

import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
from transformers.models.auto import get_values
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, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import (
        MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
        TimesformerForVideoClassification,
        TimesformerModel,
    )
    from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from transformers import VideoMAEImageProcessor







class __a :





   def __init__(					self				:			Any				,lowerCamelCase				:			int				,lowerCamelCase				:			Any=13				,lowerCamelCase				:			Any=10				,lowerCamelCase				:			Optional[int]=3				,lowerCamelCase				:			str=2				,lowerCamelCase				:			List[str]=2				,lowerCamelCase				:			Any=True				,lowerCamelCase				:			str=True				,lowerCamelCase				:			Optional[int]=32				,lowerCamelCase				:			Optional[Any]=5				,lowerCamelCase				:			List[str]=4				,lowerCamelCase				:			Union[str, Any]=37				,lowerCamelCase				:			Union[str, Any]="gelu"				,lowerCamelCase				:			int=0.1				,lowerCamelCase				:			Dict=0.1				,lowerCamelCase				:			List[str]=10				,lowerCamelCase				:			List[Any]=0.02				,lowerCamelCase				:			List[str]="divided_space_time"				,lowerCamelCase				:			Optional[int]=None				,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       parent
      __SCREAMING_SNAKE_CASE      							=       batch_size
      __SCREAMING_SNAKE_CASE      							=       image_size
      __SCREAMING_SNAKE_CASE      							=       num_channels
      __SCREAMING_SNAKE_CASE      							=       patch_size
      __SCREAMING_SNAKE_CASE      							=       num_frames
      __SCREAMING_SNAKE_CASE      							=       is_training
      __SCREAMING_SNAKE_CASE      							=       use_labels
      __SCREAMING_SNAKE_CASE      							=       hidden_size
      __SCREAMING_SNAKE_CASE      							=       num_hidden_layers
      __SCREAMING_SNAKE_CASE      							=       num_attention_heads
      __SCREAMING_SNAKE_CASE      							=       intermediate_size
      __SCREAMING_SNAKE_CASE      							=       hidden_act
      __SCREAMING_SNAKE_CASE      							=       hidden_dropout_prob
      __SCREAMING_SNAKE_CASE      							=       attention_probs_dropout_prob
      __SCREAMING_SNAKE_CASE      							=       attention_type
      __SCREAMING_SNAKE_CASE      							=       initializer_range
      __SCREAMING_SNAKE_CASE      							=       scope
      __SCREAMING_SNAKE_CASE      							=       num_labels

      # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
      __SCREAMING_SNAKE_CASE      							=       (image_size // patch_size) ** 2
      __SCREAMING_SNAKE_CASE      							=       (num_frames) * self.num_patches_per_frame + 1





   def      UpperCAmelCase__     (					self				:			str    ):

      '''simple docstring'''

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

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

      __SCREAMING_SNAKE_CASE      							=       self.get_config()

      return config, pixel_values, labels





   def      UpperCAmelCase__     (					self				:			Dict    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       TimesformerConfig(
          image_size=self.image_size				,patch_size=self.patch_size				,num_channels=self.num_channels				,num_frames=self.num_frames				,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				,initializer_range=self.initializer_range				,attention_type=self.attention_type				,)
      __SCREAMING_SNAKE_CASE      							=       self.num_labels
      return config





   def      UpperCAmelCase__     (					self				:			Optional[int]				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			Any				,lowerCamelCase				:			Optional[int]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       TimesformerModel(config=A_    )
      model.to(A_    )
      model.eval()
      __SCREAMING_SNAKE_CASE      							=       model(A_    )
      self.parent.assertEqual(result.last_hidden_state.shape				,(self.batch_size, self.seq_length, self.hidden_size)    )





   def      UpperCAmelCase__     (					self				:			List[str]				,lowerCamelCase				:			Optional[int]				,lowerCamelCase				:			List[str]				,lowerCamelCase				:			Tuple    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       TimesformerForVideoClassification(A_    )
      model.to(A_    )
      model.eval()

      __SCREAMING_SNAKE_CASE      							=       model(A_    )

      # verify the logits shape
      __SCREAMING_SNAKE_CASE      							=       torch.Size((self.batch_size, self.num_labels)    )
      self.parent.assertEqual(result.logits.shape				,A_    )





   def      UpperCAmelCase__     (					self				:			str    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.prepare_config_and_inputs()
      __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE      							=       config_and_inputs
      __SCREAMING_SNAKE_CASE      							=       {"""pixel_values""": pixel_values}
      return config, inputs_dict







@require_torch
class __a (   _SCREAMING_SNAKE_CASE,   _SCREAMING_SNAKE_CASE,   unittest.TestCase			):
   __UpperCamelCase   : Optional[int]	      =	(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
   __UpperCamelCase   : Dict	      =	(
       {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification}
       if is_torch_available()
       else {}
   )

   __UpperCamelCase   : Optional[Any]	      =	False
   __UpperCamelCase   : int	      =	False
   __UpperCamelCase   : Any	      =	False
   __UpperCamelCase   : Any	      =	False





   def      UpperCAmelCase__     (					self				:			Tuple    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       TimesformerModelTester(self    )
      __SCREAMING_SNAKE_CASE      							=       ConfigTester(
          self				,config_class=A_				,has_text_modality=A_				,hidden_size=37    )





   def      UpperCAmelCase__     (					self				:			List[str]				,lowerCamelCase				:			Optional[int]				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			str=False    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       copy.deepcopy(A_    )

      if return_labels:
         if model_class in get_values(A_    ):
            __SCREAMING_SNAKE_CASE      							=       torch.zeros(
                self.model_tester.batch_size				,dtype=torch.long				,device=A_    )

      return inputs_dict





   def      UpperCAmelCase__     (					self				:			Optional[Any]    ):

      '''simple docstring'''

      self.config_tester.run_common_tests()





   @unittest.skip(reason="""TimeSformer does not use inputs_embeds"""    )
   def      UpperCAmelCase__     (					self				:			Union[str, Any]    ):

      '''simple docstring'''

      pass





   def      UpperCAmelCase__     (					self				:			Union[str, Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs_for_common()

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





   def      UpperCAmelCase__     (					self				:			Union[str, Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs_for_common()

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

         __SCREAMING_SNAKE_CASE      							=       ["""pixel_values"""]
         self.assertListEqual(arg_names[:1]				,A_    )





   def      UpperCAmelCase__     (					self				:			str    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A_    )





   def      UpperCAmelCase__     (					self				:			Tuple    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_video_classification(*A_    )





   @slow
   def      UpperCAmelCase__     (					self				:			Optional[int]    ):

      '''simple docstring'''

      for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         __SCREAMING_SNAKE_CASE      							=       TimesformerModel.from_pretrained(A_    )
         self.assertIsNotNone(A_    )





   def      UpperCAmelCase__     (					self				:			List[Any]    ):

      '''simple docstring'''

      if not self.has_attentions:
         pass

      else:
         __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs_for_common()
         __SCREAMING_SNAKE_CASE      							=       True

         for model_class in self.all_model_classes:
            __SCREAMING_SNAKE_CASE      							=       self.model_tester.seq_length
            __SCREAMING_SNAKE_CASE      							=       self.model_tester.num_frames

            __SCREAMING_SNAKE_CASE      							=       True
            __SCREAMING_SNAKE_CASE      							=       False
            __SCREAMING_SNAKE_CASE      							=       True
            __SCREAMING_SNAKE_CASE      							=       model_class(A_    )
            model.to(A_    )
            model.eval()
            with torch.no_grad():
               __SCREAMING_SNAKE_CASE      							=       model(**self._prepare_for_class(A_				,A_    )    )
            __SCREAMING_SNAKE_CASE      							=       outputs.attentions
            self.assertEqual(len(A_    )				,self.model_tester.num_hidden_layers    )

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

            # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
            self.assertListEqual(
                list(attentions[0].shape[-3:]    )				,[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]				,)
            __SCREAMING_SNAKE_CASE      							=       len(A_    )

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

            self.assertEqual(out_len + 1				,len(A_    )    )

            __SCREAMING_SNAKE_CASE      							=       outputs.attentions

            self.assertEqual(len(A_    )				,self.model_tester.num_hidden_layers    )

            # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
            self.assertListEqual(
                list(self_attentions[0].shape[-3:]    )				,[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]				,)





   def      UpperCAmelCase__     (					self				:			Optional[Any]    ):

      '''simple docstring'''

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

         with torch.no_grad():
            __SCREAMING_SNAKE_CASE      							=       model(**self._prepare_for_class(A_				,A_    )    )

         __SCREAMING_SNAKE_CASE      							=       outputs.hidden_states
         __SCREAMING_SNAKE_CASE      							=       self.model_tester.num_hidden_layers + 1
         self.assertEqual(len(A_    )				,A_    )

         __SCREAMING_SNAKE_CASE      							=       self.model_tester.seq_length

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

      __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         __SCREAMING_SNAKE_CASE      							=       True
         check_hidden_states_output(A_				,A_				,A_    )

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

         check_hidden_states_output(A_				,A_				,A_    )





def 						__magic_name__       (							)						->					int:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE      							=       hf_hub_download(
       repo_id="""hf-internal-testing/spaghetti-video"""							,	filename="""eating_spaghetti.npy"""							,	repo_type="""dataset"""      )
   __SCREAMING_SNAKE_CASE      							=       np.load(__UpperCAmelCase      )
   return list(__UpperCAmelCase      )







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





   @cached_property
   def      UpperCAmelCase__     (					self				:			Optional[Any]    ):

      '''simple docstring'''

      return (
          VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]				,image_std=[0.5, 0.5, 0.5]    )
          if is_vision_available()
          else None
      )





   @slow
   def      UpperCAmelCase__     (					self				:			str    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       TimesformerForVideoClassification.from_pretrained("""facebook/timesformer-base-finetuned-k400"""    ).to(
          A_    )

      __SCREAMING_SNAKE_CASE      							=       self.default_image_processor
      __SCREAMING_SNAKE_CASE      							=       prepare_video()
      __SCREAMING_SNAKE_CASE      							=       image_processor(video[:8]				,return_tensors="""pt"""    ).to(A_    )

      # forward pass
      with torch.no_grad():
         __SCREAMING_SNAKE_CASE      							=       model(**A_    )

      # verify the logits
      __SCREAMING_SNAKE_CASE      							=       torch.Size((1, 400)    )
      self.assertEqual(outputs.logits.shape				,A_    )

      __SCREAMING_SNAKE_CASE      							=       torch.tensor([-0.3_016, -0.7_713, -0.4_205]    ).to(A_    )

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












'''simple docstring'''

from __future__ import annotations

import bisect

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase = 0							,	__UpperCAmelCase = -1      )						->					int:

   '''simple docstring'''







   if hi < 0:
      __SCREAMING_SNAKE_CASE      							=       len(__UpperCAmelCase      )

   while lo < hi:
      __SCREAMING_SNAKE_CASE      							=       lo + (hi - lo) // 2
      if sorted_collection[mid] < item:
         __SCREAMING_SNAKE_CASE      							=       mid + 1
      else:
         __SCREAMING_SNAKE_CASE      							=       mid

   return lo

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase = 0							,	__UpperCAmelCase = -1      )						->					int:

   '''simple docstring'''







   if hi < 0:
      __SCREAMING_SNAKE_CASE      							=       len(__UpperCAmelCase      )

   while lo < hi:
      __SCREAMING_SNAKE_CASE      							=       lo + (hi - lo) // 2
      if sorted_collection[mid] <= item:
         __SCREAMING_SNAKE_CASE      							=       mid + 1
      else:
         __SCREAMING_SNAKE_CASE      							=       mid

   return lo

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase = 0							,	__UpperCAmelCase = -1      )						->					None:

   '''simple docstring'''







   sorted_collection.insert(bisect_left(__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase      )							,	__UpperCAmelCase      )

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase = 0							,	__UpperCAmelCase = -1      )						->					None:

   '''simple docstring'''







   sorted_collection.insert(bisect_right(__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase      )							,	__UpperCAmelCase      )

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase      )						->					int | None:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE      							=       0
   __SCREAMING_SNAKE_CASE      							=       len(__UpperCAmelCase      ) - 1

   while left <= right:
      __SCREAMING_SNAKE_CASE      							=       left + (right - left) // 2
      __SCREAMING_SNAKE_CASE      							=       sorted_collection[midpoint]
      if current_item == item:
         return midpoint
      elif item < current_item:
         __SCREAMING_SNAKE_CASE      							=       midpoint - 1
      else:
         __SCREAMING_SNAKE_CASE      							=       midpoint + 1
   return None

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase      )						->					int | None:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE      							=       bisect.bisect_left(__UpperCAmelCase							,	__UpperCAmelCase      )
   if index != len(__UpperCAmelCase      ) and sorted_collection[index] == item:
      return index
   return None

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase      )						->					int | None:

   '''simple docstring'''







   if right < left:
      return None

   __SCREAMING_SNAKE_CASE      							=       left + (right - left) // 2

   if sorted_collection[midpoint] == item:
      return midpoint
   elif sorted_collection[midpoint] > item:
      return binary_search_by_recursion(__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase							,	midpoint - 1      )
   else:
      return binary_search_by_recursion(__UpperCAmelCase							,	__UpperCAmelCase							,	midpoint + 1							,	__UpperCAmelCase      )


if __name__ == "__main__":
    a        =						input("Enter numbers separated by comma:\n").strip()
    a        =						sorted(int(item) for item in user_input.split(","))
    a        =						int(input("Enter a single number to be found in the list:\n"))
    a        =						binary_search(collection, target)
    if result is None:
        print(F'''{target} was not found in {collection}.''')
    else:
        print(F'''{target} was found at position {result} in {collection}.''')





